Search completed in 1.57 seconds.
:is() (:matches(), :any()) - CSS: Cascading Style Sheets
Note: :matches
() was renamed to :is
() in CSSWG issue #3258. The :is
() CSS pseudo-class function takes a selector list as its argument, and selects any element that can be selected by one of the selectors in that list. This is useful for writing large selectors in a more compact form. Note that currently browsers support this functionality as :matches
(), or through an older, prefixed pseudo-class -- :any
(), including older versions of Chrome, Firefox, and Safari. :any
() works in exactly the same way as :matches
()/:is
(), except that it requires vendor prefixes and doesn't support complex selectors. /* Selects any paragraph inside a header, main or footer element that is being hovered */ :is(header, main, footer) p:hover { color: red; cursor: pointer; } /* The above is equivalen...
...ires vendor prefixes and doesn't support complex selectors. ...
...fixes and doesn't support complex selectors. ...
...And 27 more matches
EventTarget.addEventListener() - Web APIs
Syntax target.addEventListener(type, listener [, options]); target.addEventListener(type, listener [, useCapture]); target.addEventListener(type, listener [, useCapture, wantsUntrusted ]); // Gecko/Mozilla only Parameters type A case-sensitive string representing the event type to listen for. ...
... will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. once A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked. passive A Boolean that, if true, indicates that the function specified by listener will never call preventDefault
(). If a passive listener does call preventDefault
(), the user agent will do nothing other than generate a console warning. See Improving scrolling performance with passive listeners to learn more. mozSystemGroup A Boolean indicating that the listener should be added to the system group. Available only in code running in XBL or in the chrome of the Firefox browser. useCapture Optional A ...
...ves synthetic events dispatched by web content (the default is false for browser chrome and true for regular web pages). This parameter is useful for code found in add-ons, as well as the browser itself. Return value undefined Usage notes The event listener callback The event listener can be specified as either a callback function or an object that implements EventListener, whose handleEvent
() method serves as the callback function. The callback function itself has the same parameters and return value as the handleEvent
() method; that is, the callback accepts a single parameter: an object based on Event describing the event that has occurred, and it returns nothing. For example, an event handler callback that can be used to handle both fullscreenchange and fullscreenerror might look ...
...And 40 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
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. ...
...valID = 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 delay milliseconds. This syntax is not recommended for the same reasons that make using eval
() a security risk. delayOptional The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. See Delay restrictions below for details on the permitted range of delay values. arg1, ..., argN Optional Additional arguments which are passed through to the function specified by func once the timer expires. Note: Passing addi...
...l The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. See Delay restrictions below for details on the permitted range of delay values. arg1, ..., argN Optional Additional arguments which are passed through to the function specified by func once the timer expires. ...
...And 40 more matches
eval() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax eval(string) Parameters string A string representing a JavaScript expression, statement, or sequence of statements. ...
...m/mdn/interactive-examples and send us a pull request. Syntax eval(string) Parameters string A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. Return value The completion value of evaluating the given code. If the completion value is empty, undefined is returned. Description eval
() is a function property of the global object. The argument of the eval
() function is a string. If the string represents an expression, eval
() evaluates the expression. If the argument represents one or more JavaScript statements, eval
() evaluates the statements. Do not call eval
() to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically. If you construct an...
...rgument of the eval
() function is a string. If the string represents an expression, eval
() evaluates the expression. If the argument represents one or more JavaScript statements, eval
() evaluates the statements. Do not call eval
() to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically. If you construct an arithmetic expression as a string, you can use eval
() to evaluate it at a later time. For example, suppose you have a variable x. You can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then calling eval
() at a later point in your script. If the argument of eval
() is not a string, eval
() returns the argument unchanged. In the following example, the String construc...
...And 32 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
The setTimeout
() method of the WindowOrWorkerGlobalScope mixin (and successor to Window.setTimeout
()) sets a timer which executes a function or specified piece of code once the timer expires. Syntax var timeoutID = scope.setTimeout(function[, delay, arg1, arg2, ...]); var timeoutID = scope.setTimeout(function[, delay]); var timeoutID = scope.setTimeout(code[, delay]); Parameters function A function to be executed after the timer expires. 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. delay Optional The time, in milliseconds (thousandths of a second), the timer should wait before the specified fun...
... to the function specified by function. Note: Passing additional parameters to the function in the first syntax does not work in Internet Explorer 9 and below. If you want to enable this functionality on that browser, you must use a polyfill (see the Polyfill section). Return value The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout
(); this value can be passed to clearTimeout
() to cancel the timeout. It may be helpful to be aware that setTimeout
() and setInterval
() share the same pool of IDs, and that clearTimeout
() and clearInterval
() can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. It is guaranteed that a timeout ID will never ...
... to cancel the timeout. It may be helpful to be aware that setTimeout
() and setInterval
() share the same pool of IDs, and that clearTimeout
() and clearInterval
() can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. It is guaranteed that a timeout ID will never be reused by a subsequent call to setTimeout
() or setInterval
() on the same object (a window or a worker). However, different objects use separate pools of IDs. Example The following example sets up two simple buttons in a web page and hooks them to the setTimeout
() and clearTimeout
() routines. Pressing the first button will set a timeout which calls an alert dialog after two seconds and stores the timeout id for use by clearTimeout
(). You ...
...And 28 more matches
Function.prototype.bind() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax let boundFunc = func.bind(thisArg[, arg1[, arg2[, ...argN]]]) Parameters thisArg The value to be passed as the this parameter to the target function func when the bound function is called. The value is ignored if the bound function is constructed using the new operator. ...
...ents 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 2015) that wraps the original function object. Calling the bound function generally results in the execution of its wrapped function. A bound function has the following internal properties: [[BoundTargetFunction]] The wrapped function object [[BoundThis]] The value that is always passed as thi...
...d. The provided this value is ignored, while prepended arguments are provided to the emulated function. Polyfill Because older browsers are generally also slower browsers, it is far more critical than most people recognize to create performance polyfills to make the browsing experience in outdated browsers slightly less horrible. Thus, presented below are two options for Function.prototype.bind
() polyfills: The first one is much smaller and more performant, but does not work when using the new operator. The second one is bigger and less performant, but it permits some usage of the new operator on bound functions. Generally, in most code it's very rare to see new used on a bound function, so it is generally best to go with the first option. // Does not work with `new (funcA.bind(th...
...And 24 more matches
Object.defineProperty() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Object.defineProperty(obj, prop, descriptor) Parameters obj The object on which to define the property. prop The name or Symbol of the property to be defined or modified. descriptor The descriptor for the property being defined or modified. Return value The object that was passed to the function. ...
...d allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (for...in loop or Object.keys method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, values added using Object.defineProperty
() are immutable and not enumerable. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and acces...
...ptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys (note: the default value is in the case of defining properties using Object.defineProperty
()): configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to false. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false. A data descriptor also has the following optional keys: value The value as...
...And 23 more matches
Promise.prototype.then() - JavaScript
It takes up to two arguments: callback functions for the success and failure cases of the Promise. The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. If one or both arguments are omitted or are provided non-functions, then then will be missing the handler(s), but will not generate any errors. If the Promise that then is called on adopts a state (fulfillment or rejection) for which then has no handler, the returned promise simply adopts the final state of the original Promise on which then was called. ...
... const resolvedProm = Promise.resolve(33); let thenProm = resolvedProm.then(value => { console.log("this gets called after the end of the main stack. ...
...f a function to the moment the stack is empty setTimeout(
() => { console.log(thenProm); }); // logs, in order: // Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} // "this gets called after the end of the main stack. the value received and returned is: 33" // Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: 33} Description As the then and Promise.prototype.catch
() methods return promises, they can be chained -- an operation called composition. Examples Using the then method var p1 = new Promise((resolve, reject) => { resolve('Success!'); // or // reject(new Error("Error!")); }); p1.then(value => { console.log(value); // Success! }, reason => { console.error(reason); // Error! }); Chaining The then method returns a Promise which allows for ...
...And 21 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
he user agent has the opportunity to react to actions taken by the microtask. JavaScript promises and the Mutation Observer API both use the microtask queue to run their callbacks, but there are other times when the ability to defer work until the current event loop pass is wrapping up. 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 JavaSc...
...nt callback being run, or an interval or timeout being fired. These all get scheduled on the task queue. Tasks get added to the task queue when: A new JavaScript program or subprogram is executed (such as from a console, or by running the code in a <script> element) directly. An event fires, adding the event's callback function to the task queue. A timeout or interval created with setTimeout
() or setInterval
() is reached, causing the corresponding callback to be added to the task queue. The event loop driving your code handles these tasks one after another, in the order in which they were enqueued. Only tasks which were already in the task queue when the event loop pass began will be executed during the current iteration. The rest will have to wait until the following iteration. Mic...
..., each time a task exits, the event loop checks to see if the task is returning control to other JavaScript code. If not, it runs all of the microtasks in the microtask queue. The microtask queue is, then, processed multiple times per iteration of the event loop, including after handling events and other callbacks. Second, if a microtask adds more microtasks to the queue by calling queueMicrotask
(), those newly-added microtasks execute before the next task is run. That's because the event loop will keep calling microtasks until there are none left in the queue, even if more keep getting added. Warning: Since microtasks can themselves enqueue more microtasks, and the event loop continues processing microtasks until the queue is empty, there's a real risk of getting the event loop endlessly...
...And 20 more matches
PaymentRequest.show() - Web APIs
The PaymentRequest interface's show
() method instructs the user agent to begin the process of showing and handling the user interface for the payment request to the user. For security reasons, the PaymentRequest.show
() method can't just be initiated at any time. It may only be called while handling events that represent user interactions, such as click, keyup, or the like. Only one payment request can be in the process of being handled at once, across all documents. Once one PaymentRequest's show
() method has been called, any other call to show
() will by rejected with an AbortError until the returned promise has been concluded, either by being fulfilled with a PaymentResponse indicating the results of the payment request, or by being rejected with an error. Note: In reality, d...
...se indicating the results of the payment request, or by being rejected with an error. Note: In reality, despite the fact that the specification says this can't be done, some browsers, including Firefox, support multiple active payment requests at a time. ...
...he specification says this can't be done, some browsers, including Firefox, support multiple active payment requests at a time. If your architecture doesn't necessarily have all of the data ready to go at the moment it instantiates the payment interface by calling show
(), specify the detailsPromise parameter, providing a Promise that is fulfilled once the data is ready. If this is provided, show
() will not allow the user to interact with the payment interface until the promise is fulfilled, so that data can be updated prior to the user engaging with the payment process. Processing the result and, if necessary, calling PaymentResponse.retry
() to retry a failed payment can all be done either asynchronously or synchronously, depending on your needs. For the best user experience, asynchronous...
...And 20 more matches
Window.open() - Web APIs
If the name doesn't exist, then a new browsing context is opened in a new tab or a new window, and the specified resource is loaded into it. Syntax var window = window.open(url, windowName, [windowFeatures]); Parameters url A DOMString indicating the URL of the resource to be loaded. This can be a path or URL to an HTML page, image file, or any other resource that is supported by the browser. If the empty string ("") is specified as url, a blank page is opened into the targeted browsing context. ...
... WindowProxy object, which is basically a thin wrapper for the Window object representing the newly created window, and has all its features available. If the window couldn't be opened, the returned value is instead null. The returned reference can be used to access properties and methods of the new window as long as it complies with Same-origin policy security requirements. ...
... Description The open
() method creates a new secondary browser window, similar to choosing New Window from the File menu. The url parameter specifies the URL to be fetched and loaded in the new window. If url is an empty string, then a new blank, empty window (URL about:blank) is created with the default toolbars of the main window. Note that remote URLs won't load immediately. When window.open
() returns, the window always contains about:blank. The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously. ...
...And 16 more matches
MediaDevices.getUserMedia() - Web APIs
That stream can include, for example, a video track (produced by either a hardware or virtual video source such as a camera, video recording device, screen sharing service, and so forth), an audio track (similarly, produced by a physical or virtual audio source like a microphone, A/D converter, or the like), and possibly other track types. It returns a Promise that resolves to a MediaStream object. If the user denies permission, or matching media is not available, then the promise is rejected with NotAllowedError or NotFoundError respectively. ...
... catch(err) { /* handle the error */ } } Similarly, using the raw promises directly, the code looks like this: navigator.mediaDevices.getUserMedia(constraints) .then(function(stream) { /* use the stream */ }) .catch(function(err) { /* handle the error */ }); Note: If the current document isn't loaded securely, navigator.mediaDevices will be undefined, and you cannot use getUserMedia
(). See Security for more information on this and other security issues related to using getUserMedia
(). Syntax var promise = navigator.mediaDevices.getUserMedia(constraints); Parameters constraints A MediaStreamConstraints object specifying the types of media to request, along with any requirements for each type. The constraints parameter is a MediaStreamConstraints object with two mem...
...th the specified types that meet the constraints given, then the returned promise is rejected with NotFoundError. The following requests both audio and video without any specific requirements: { audio: true, video: true } If true is specified for a media type, the resulting stream is required to have that type of track in it. If one cannot be included for any reason, the call to getUserMedia
() will result in an error. While information about a user's cameras and microphones are inaccessible for privacy reasons, an application can request the camera and microphone capabilities it needs and wants, using additional constraints. The following expresses a preference for 1280x720 camera resolution: { audio: true, video: { width: 1280, height: 720 } } The browser will try to honour ...
...And 15 more matches
:where() - CSS: Cascading Style Sheets
This <a href="https://mozilla.org">contains a link</a>. </section> <aside class="is-styling"> <p>Here is my aside content. ...
...This <a href="https://mozilla.org">contains a link</a>. </section> <aside class="is-styling"> <p>Here is my aside content. ...
...This <a href="https://mozilla.org">contains a link</a>. </section> <aside class="is-styling"> <p>Here is my aside content. ...
...And 15 more matches
Array.prototype.forEach() - JavaScript
The forEach
() method executes a provided function once for each array element. 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 arr.forEach(callback(currentValue [, index [, array]])[, thisArg]) Parameters callback Function to execute on each element. It accepts between one and three arguments: currentValue The current element being processed in the array. index Optional The index currentValue in the array. array Optional The array forEach
() was called upon. thisArg Optional Value to use as this when executing callback. Return value undefined. ...
...eters callback Function to execute on each element. It accepts between one and three arguments: currentValue The current element being processed in the array. index Optional The index currentValue in the array. array Optional The array forEach
() was called upon. thisArg Optional Value to use as this when executing callback. Return value undefined. Description forEach
() calls a provided callback function once for each element in an array in ascending order. ...
...orEach
() calls a provided callback function once for each element in an array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized. (For sparse arrays, see example below.) callback is invoked with three arguments: the value of the element the index of the element the Array object being traversed If a thisArg parameter is provided to forEach
(), it will be used as callback's this value. The thisArg value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. The range of elements processed by forEach
() is set before the first invocation of callback. Elements which are appended to the array after the call to forEach
() begins will not be visited by callback. If existing e...
...And 15 more matches
Object.create() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Object.create(proto, [propertiesObject]) Parameters proto The object which should be the prototype of the newly-created object. ...
...object. propertiesObject Optional If specified and not undefined, an object whose enumerable own properties (that is, those properties defined upon itself and not enumerable properties along its prototype chain) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of Object.defineProperties
(). Return value A new object with the specified prototype object and properties. Exceptions The proto parameter has to be either null or an Object excluding primitive wrapper objects. If proto is neither of these a TypeError is thrown. Custom and Null objects A new object created from a completely custom object (especially one created from the null object, which is basically a custom o...
...nces quickly become apparent: > "oco is: " + oco // shows "oco is: [object Object]" > "ocn is: " + ocn // throws error: Cannot convert object to primitive value Testing just a few of the many most basic built-in functions shows the magnitude of the problem more clearly: > alert(oco) // shows [object Object] > alert(ocn) // throws error: Cannot convert object to primitive value > oco.toString
() // shows [object Object] > ocn.toString
() // throws error: ocn.toString is not a function > oco.valueOf
() // shows {} > ocn.valueOf
() // throws error: ocn.valueOf is not a function > oco.hasOwnProperty("p") // shows "true" > ocn.hasOwnProperty("p") // throws error: ocn.hasOwnProperty is not a function > oco.constructor // shows "Object
() { [native code] }" > ocn.constructor // shows "undefined...
...And 15 more matches
cross-fade() - CSS: Cascading Style Sheets
The percent value must be coded without quotes, must contain the "%" symbol, and its value must be between 0% and 100%. ...
...more images at a defined transparency. It can be used for many simple image manipulations, such as tinting an image with a solid color or highlighting a particular area of the page by combining an image with a radial gradient. Syntax Important: The specification and current implementations have different syntaxes. The specification syntax is explained first. Specification syntax The cross-fade
() function takes a list of images with a percentage defining how much of each image is retained in terms of opacity when it is blended with the other images. The percent value must be coded without quotes, must contain the "%" symbol, and its value must be between 0% and 100%. The function can be used in CSS anywhere an ordinary image reference can be used. Cross-fade percentages Think of the pe...
...d three images are included, each image will be 33.33% opaque. The two following are lines (almost) identical: cross-fade( url(red.png), url(yellow.png), url(blue.png)); /* all three will be 33.3333% opaque */ cross-fade( url(red.png) 33.33%, url(yellow.png) 33.33%, url(blue.png) 33.33%); Older, implemented syntax cross-fade( <image, <image>, <percentage> ) The specification for the cross-fade
() function allows for multiple images and for each image to have transparency values independent of the other values. This was not always the case. The original syntax, which has been implemented in some browsers, only allowed for two images, with the sum of the transparency of those two images being exactly 100%. The original syntax is supported in Safari and supported with the -webkit- prefix in ...
...And 14 more matches
image() - CSS: Cascading Style Sheets
The image
() CSS function defines an <image> in a similar fashion to the <url> function, but with added functionality including specifying the image's directionality, specifying fallback images for when the preferred image is not supported, displaying just a part of that image defined by a media fragment, and specifying a solid color as a fallback in case none of the specified images are able to be rendered. Disambiguation: Image
(), the HTMLImageElement constructor. ...
...referred image is not supported, displaying just a part of that image defined by a media fragment, and specifying a solid color as a fallback in case none of the specified images are able to be rendered. Disambiguation: Image
(), the HTMLImageElement constructor. ...
...age is not supported, displaying just a part of that image defined by a media fragment, and specifying a solid color as a fallback in case none of the specified images are able to be rendered. Disambiguation: Image
(), the HTMLImageElement constructor. ...
...And 13 more matches
Function.prototype.toString() - JavaScript
Description The Function object overrides the toString method inherited from Object; it does not inherit Object.prototype.toString. For user-defined Function objects, the toString method returns a string containing the source text segment which was used to define the function. ...
... Description The Function object overrides the toString method inherited from Object; it does not inherit Object.prototype.toString. For user-defined Function objects, the toString method returns a string containing the source text segment which was used to define the function. ...
...tring method inherited from Object; it does not inherit Object.prototype.toString. For user-defined Function objects, the toString method returns a string containing the source text segment which was used to define the function. JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string. ...
...And 13 more matches
CanvasRenderingContext2D.arcTo() - Web APIs
The arc is automatically connected to the path's latest point with a straight line, if necessary for the specified parameters. This method is commonly used for making rounded corners. Note: Be aware that you may get unexpected results when using a relatively large radius: the arc's connecting line will go in whatever direction it must to meet the specified radius. Syntax void ctx.arcTo(x1, y1, x2, y2, radius); Parameters x1 The x-axis coordinate of the first control point. y1 The y-axis coordinate of the first control point. x2 The x-axis coordinate of the second control point. ...
...adius. Syntax void ctx.arcTo(x1, y1, x2, y2, radius); Parameters x1 The x-axis coordinate of the first control point. y1 The y-axis coordinate of the first control point. x2 The x-axis coordinate of the second control point. y2 The y-axis coordinate of the second control point. radius The arc's radius. Must be non-negative. Examples How arcTo works One way to think about arcTo
() is to imagine two straight segments: one from the starting point to a first control point, and another from there to a second control point. Without arcTo
(), these two segments would form a sharp corner: arcTo
() creates a circular arc that fits this corner and smooths is out. In other words, the arc is tangential to both segments. HTML <canvas id="canvas"></canvas> JavaScript const canvas = d...
...rom there to a second control point. Without arcTo
(), these two segments would form a sharp corner: arcTo
() creates a circular arc that fits this corner and smooths is out. In other words, the arc is tangential to both segments. ...
...And 12 more matches
DataTransferItem.webkitGetAsEntry() - Web APIs
Return value A FileSystemEntry-based object describing the dropped item. This will be either FileSystemFileEntry or FileSystemDirectoryEntry. ...
... Return value A FileSystemEntry-based object describing the dropped item. This will be either FileSystemFileEntry or FileSystemDirectoryEntry. ...
... Return value A FileSystemEntry-based object describing the dropped item. This will be either FileSystemFileEntry or FileSystemDirectoryEntry. ...
...And 12 more matches
WritableStream.WritableStream() - Web APIs
Syntax var writableStream = new WritableStream(underlyingSink[, queuingStrategy]); Parameters underlyingSink An object containing methods and properties that define how the constructed stream instance will behave. underlyingSink can contain the following: start(controller) Optional This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the underlying sink. If this process is to be done asynchronously, it can return a promise to signal success or failure. The controller parameter passed to this method is a WritableStreamDefaultController. ...
...tes have succeeded. The controller parameter passed to this method is a WritableStreamDefaultController, which can be used to control the stream at the end of writing. abort(reason) Optional This method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. It can clean up any held resources, much like close
(), but abort
() will be called even if writes are queued up -- those chunks will be thrown away. If this process is asynchronous, it can return a promise to signal success or failure. The reason parameter contains a DOMString describing why the stream was aborted. queuingStrategy Optional An object that optionally defines a queuing strategy for the stream. This takes two parameters: highWa...
...ueuingStrategy is supplied, the default used is the same as a CountQueuingStrategy with a high water mark of 1. Return value An instance of the WritableStream object. Examples The following example illustrates several features of this interface. It shows the creation of the WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a function called sendMessage
(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter
() method, which returns an instance of WritableStreamDefaultWriter. A forEach
() call is used to write each chunk of the string to the stream. Finally, write
() and close
() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySelect...
...And 12 more matches
JSON.stringify() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax JSON.stringify(value[, replacer[, space]]) Parameters value The value to convert to a JSON string. ...
...t) is used as white space. If this parameter is not provided (or is null), no white space is used. Return value A JSON string representing the given value. Exceptions Throws a TypeError ("cyclic object value") exception when a circular reference is found. Throws a TypeError ("BigInt value can't be serialized in JSON") when trying to stringify a BigInt value. Description JSON.stringify
() converts a value to JSON notation representing it: If the value has a toJSON
() method, it's responsible to define what data will be serialized. Boolean, Number, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics. undefined, Functions, and Symbols are not valid JSON values. If any such values are e...
...rialized. Boolean, Number, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics. undefined, Functions, and Symbols are not valid JSON values. If any such values are encountered during conversion they are either omitted (when found in an object) or changed to null (when found in an array). JSON.stringify
() can return undefined when passing in "pure" values like JSON.stringify(function
(){}) or JSON.stringify(undefined). All Symbol-keyed properties will be completely ignored, even when using the replacer function. The instances of Date implement the toJSON
() function by returning a string (the same as date.toISOString
()). Thus, they are treated as strings. The numbers Infinity and NaN, as well as ...
...And 12 more matches
FileSystemDirectoryReader.readEntries() - Web APIs
The objects in the array are all based upon FileSystemEntry. Generally, they are either FileSystemFileEntry objects, which represent standard files, or FileSystemDirectoryEntry objects, which represent directories. Syntax readEntries(successCallback[, errorCallback]); Parameters successCallback A function which is called when the directory's contents have been retrieved. The function receives a single input parameter: an array of file system entry objects, each based on FileSystemEntry. ...
...ch is called when the directory's contents have been retrieved. The function receives a single input parameter: an array of file system entry objects, each based on FileSystemEntry. Generally, they are either FileSystemFileEntry objects, which represent standard files, or FileSystemDirectoryEntry objects, which represent directories. If there are no files left, or you've already called readEntries
() on this FileSystemDirectoryReader, the array is empty. errorCallback Optional A callback function which is called if an error occurs while reading from the directory. It receives one input parameter: a FileError object describing the error which occurred. Return value undefined. Example In this example, a drop zone is created, which responds to the drop event by scanning through the droppe...
...This function takes as input a FileSystemEntry representing an entry in the file system to be scanned and processed (the item parameter), and an element into which to insert the list of contents (the container parameter). Note that to read all files in a directory, readEntries needs to be called repeatedly until it returns an empty array. In Chromium-based browsers, the following exam...
...And 11 more matches
RTCPeerConnection.addTrack() - Web APIs
Note: Adding a track to a connection triggers renegotiation by firing a negotiationneeded event. See Starting negotiation in Signaling and video calling for details. Syntax rtpSender = rtcPeerConnection.addTrack(track, stream...); Parameters track A MediaStreamTrack object representing the media track to add to the peer connection. stream... Optional One or more local MediaStream objects to which the track should be added. The specified track doesn't necessarily have to already be part of any of the specified streams. ...
...orresponding stream (or streams) automatically on the other end of the connection, and will then automatically add the received track to those streams. Streamless tracks If no streams are specified, then the track is streamless. This is perfectly acceptable, although it will be up to the remote peer to decide what stream to insert the track into, if any. ...
... addTrack
() when building many types of simple applications, where only one stream is needed. For example, if all you're sharing with the remote peer is a single stream with an audio track and a video track, you don't need to deal with managing what track is in what stream, so you might as well just let the transceiver handle it for you. ...
...And 11 more matches
RTCPeerConnection.setRemoteDescription() - Web APIs
The RTCPeerConnection method setRemoteDescription
() sets the specified session description as the remote peer's current offer or answer. The description specifies the properties of the remote end of the connection, including the media format. The method takes a single parameter--the session description--and it returns a Promise which is fulfilled once the description has been changed, asynchronously. This is typically called after receiving an offer or answer from another peer over the signaling server. Keep in mind that if setRemoteDescription
() is called while a connection is already in place, it means renegotiation is underway (possibly to adapt to changing network conditions). Because descriptions will be exchanged until the two peers agree on a configuration, the description submitte...
...Instead, the current connection configuration remains in place until negotiation is complete. Only then does the agreed-upon configuration take effect. ...
...ur implementation of The sessionDescription parameter is technically of type RTCSessionDescriptionInit, but because RTCSessionDescription serializes to be indistinguishable from RTCSessionDescriptionInit, you can also pass in an RTCSessionDescription. This lets you simplify code such as the following: myPeerConnection.setRemoteDescription(new RTCSessionDescription(description)) .then(function
() { return createMyStream
(); }) to simply be: myPeerConnection.setRemoteDescription(description) .then(function
() { return createMyStream
(); }) Using async/await syntax, you can further simplify this to: await myPeerConnection.setRemoteDescription(description); createMyStream
(); Since it's unnecessary, the RTCSessionDescription
() constructor is deprecated. Return value A Promise which ...
...And 11 more matches
SubtleCrypto.deriveBits() - Web APIs
See Supported algorithms for some more detail on these algorithms. ...
...See Supported algorithms for some more detail on these algorithms. ...
...See Supported algorithms for some more detail on these algorithms. ...
...And 11 more matches
WebGLRenderingContext.vertexAttribPointer() - Web APIs
Syntax void gl.vertexAttribPointer(index, size, type, normalized, stride, offset); Parameters index A GLuint specifying the index of the vertex attribute that is to be modified. size A GLint specifying the number of components per vertex attribute. Must be 1, 2, 3, or 4. type A GLenum specifying the data type of each component in the array. ...
...nt to render some 3D geometry, and for that we will need to supply our vertices to the Vertex Shader. Each vertex has a few attributes, like position, normal vector, or texture coordinate, that are defined in an ArrayBuffer and will be supplied to the Vertex Buffer Object (VBO). First, we need to bind the WebGLBuffer we want to use to gl.ARRAY_BUFFER, then, with this method, gl.vertexAttribPointer
(), we specify in what order the attributes are stored, and what data type they are in. In addition, we need to include the stride, which is the total byte length of all attributes for one vertex. Also, we have to call gl.enableVertexAttribArray
() to tell WebGL that this attribute should be filled with data from our array buffer. Usually, your 3D geometry is already in a certain binary format, so y...
...mum is 16, on lower-end graphics cards, the value will be lower. Attribute index For each attribute, you must specify its index. This is independent from the location inside the array buffer, so your attributes can be sent in a different order than how they are stored in the array buffer. You have two options: Either you specify the index yourself. ...
...And 11 more matches
SubtleCrypto.encrypt() - Web APIs
It takes as its arguments a key to encrypt with, some algorithm-specific parameters, and the data to encrypt (also known as "plaintext"). It returns a Promise which will be fulfilled with the encrypted data (also known as "ciphertext"). Syntax const result = crypto.subtle.encrypt(algorithm, key, data); Parameters algorithm is an object specifying the algorithm to be used and any extra parameters if required: To use RSA-OAEP, pass an RsaOaepParams object. To use AES-CTR, pass an AesCtrParams object. To use AES-CBC, pass an AesCbcParams object. To use AES-GCM, pass an AesGcmParams object. key is a CryptoKey containing the key to be used for encryption. ...
...n is not valid for the provided key (e.g. invalid encryption algorithm, or invalid key for the specified encryption algorithm). OperationError Raised when the operation failed for an operation-specific reason (e.g. algorithm parameters of invalid sizes, or AES-GCM plaintext longer than 239-256 bytes). Supported algorithms The Web Crypto API provides four algorithms that support the encrypt
() and decrypt
() operations. One of these algorithms -- RSA-OAEP -- is a public-key cryptosystem. The other three encryption algorithms here are all symmetric algorithms, and they're all based on the same underlying cipher, AES (Advanced Encryption Standard). The difference between them is the mode. The Web Crypto API supports three different AES modes: CTR (Counter Mode) CBC (Cipher Block Cha...
...e and the others is that GCM is an "authenticated" mode, which means that it includes checks that the ciphertext has not been modified by an attacker. Examples Note: You can try the working examples out on GitHub. RSA-OAEP This code fetches the contents of a text box, encodes it for encryption, and encrypts it with using RSA-OAEP. See the complete code on GitHub. ...
...And 10 more matches
SubtleCrypto.unwrapKey() - Web APIs
The unwrapKey
() method of the SubtleCrypto interface "unwraps" a key. This means that it takes as its input a key that has been exported and then encrypted (also called "wrapped"). It decrypts the key and then imports it, returning a CryptoKey object that can be used in the Web Crypto API. As with SubtleCrypto.importKey
(), you specify the key's import format and other attributes of the key to import details such as whether it is extractable, and which operations it can be used for. But because unwrapKey
() also decrypts the key to be imported, you also need to pass in the key that must be used to decrypt it. This is sometimes called the "unwrapping key". ...
.... As with SubtleCrypto.importKey
(), you specify the key's import format and other attributes of the key to import details such as whether it is extractable, and which operations it can be used for. But because unwrapKey
() also decrypts the key to be imported, you also need to pass in the key that must be used to decrypt it. This is sometimes called the "unwrapping key". The inverse of unwrapKey
() is SubtleCrypto.wrapKey
(): while unwrapKey is composed of decrypt + import, wrapKey is composed of encrypt + export. Syntax const result = crypto.subtle.unwrapKey( format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages ); Parameters format is a string describing the data format of the key to unwrap. It can be one of the following...
... For ECDSA or ECDH: Pass an EcKeyImportParams object. For HMAC: Pass an HmacImportParams object. For AES-CTR, AES-CBC, AES-GCM, or AES-KW: Pass the string identifying the algorithm or an object of the form { "name": ALGORITHM }, where ALGORITHM is the name of the algorithm. extractable is a Boolean indicating whether it will be possible to export the key using SubtleCrypto.exportKey
() or SubtleCrypto.wrapKey
(). keyUsages is an Array indicating what can be done with the key. Possible values of the array are: encrypt: The key may be used to encrypt messages. decrypt: The key may be used to decrypt messages. sign: The key may be used to sign messages. verify: The key may be used to verify signatures. deriveKey: The key may be used in deriving a new key. deri...
...And 10 more matches
SubtleCrypto.verify() - Web APIs
To use RSASSA-PKCS1-v1_5, pass the string "RSASSA-PKCS1-v1_5" or an object of the form { "name": "RSASSA-PKCS1-v1_5" }. ...
...se which will be fulfilled with a Boolean value indicating whether the signature is valid. Syntax const result = crypto.subtle.verify(algorithm, key, signature, data); Parameters algorithm is a DOMString or object defining the algorithm to use, and for some algorithm choices, some extra parameters. The values given for the extra parameters must match those passed into the corresponding sign
() call. To use RSASSA-PKCS1-v1_5, pass the string "RSASSA-PKCS1-v1_5" or an object of the form { "name": "RSASSA-PKCS1-v1_5" }. To use RSA-PSS, pass an RsaPssParams object. To use ECDSA, pass an EcdsaParams object. To use HMAC, pass the string "HMAC" or an object of the form { "name": "HMAC" }. key is a CryptoKey containing the key that will be used to verify the signature. I...
...hat fulfills with a Boolean: true if the signature is valid, false otherwise. Exceptions The promise is rejected when the following exception is encountered: InvalidAccessError Raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. ...
...And 10 more matches
WritableStreamDefaultWriter.close() - Web APIs
Return value A Promise, which fulfills with the undefined if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. Exceptions TypeError The stream you are trying to close is not a WritableStream. ...
... Return value A Promise, which fulfills with the undefined if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. Exceptions TypeError The stream you are trying to close is not a WritableStream. ...
...f all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. Exceptions TypeError The stream you are trying to close is not a WritableStream. Examples The following example shows the creation of a WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a function called sendMessage
(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter
() method, which returns an instance of WritableStreamDefaultWriter. A forEach
() call is used to write each chunk of the string to the stream. Finally, write
() and close
() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySelect...
...And 10 more matches
Array.prototype.values() - JavaScript
The values
() method returns a new Array Iterator object that contains the values for each index in the array. Syntax arr.values
() Return value A new Array iterator object. Examples Iteration using for...of loop var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values
(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" Array.prototype.values is default implementation of Array.prototype[Symbol.iterator]. ...
...A new Array iterator object. Examples Iteration using for...of loop var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values
(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" Array.prototype.values is default implementation of Array.prototype[Symbol.iterator]. ...
...oop var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values
(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" Array.prototype.values is default implementation of Array.prototype[Symbol.iterator]. ...
...And 10 more matches
String.prototype.substring() - JavaScript
The substring
() method returns the part of the string between the start and end indexes, or to the end of the string. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.substring(indexStart[, indexEnd]) Parameters indexStart The index of the first character to include in the returned substring. indexEnd Optional The index of the first character to exclude from the returned substring. Return value A new string containing the specified part of the given string. Description substring
() extracts characters from indexStart up to but not including indexEnd. In particular: If indexEnd is omitted, ...
...exStart The index of the first character to include in the returned substring. indexEnd Optional The index of the first character to exclude from the returned substring. Return value A new string containing the specified part of the given string. Description substring
() extracts characters from indexStart up to but not including indexEnd. In particular: If indexEnd is omitted, substring
() extracts characters to the end of the string. If indexStart is equal to indexEnd, substring
() returns an empty string. If indexStart is greater than indexEnd, then the effect of substring
() is as if the two arguments were swapped; See example below. Any argument value that is less than 0 or greater than stringName.length is treated as if it were 0 and stringName.length, respectively. Any arg...
...xEnd, substring
() returns an empty string. If indexStart is greater than indexEnd, then the effect of substring
() is as if the two arguments were swapped; See example below. Any argument value that is less than 0 or greater than stringName.length is treated as if it were 0 and stringName.length, respectively. Any argument value that is NaN is treated as if it were 0. ...
...And 10 more matches
BaseAudioContext.decodeAudioData() - Web APIs
In this case the ArrayBuffer is loaded from XMLHttpRequest and FileReader. The decoded AudioBuffer is resampled to the AudioContext's sampling rate, then passed to a callback or promise. This is the preferred method of creating an audio source for Web Audio API from an audio track. This method only works on complete file data, not fragments of audio file data. ...
...ta, 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 callback, ...
...layed and manipulated how you want. errorCallback An optional error callback, to be invoked if an error occurs when the audio data is being decoded. Return value Void, or a Promise object that fulfills with the decodedData. Example In this section we will first cover the older callback-based system and then the newer promise-based syntax. ...
...And 9 more matches
DataTransfer.setData() - Web APIs
If data for the given type does not exist, it is added at the end of the drag data store, such that the last item in the types list will be the new type. If data for the given type already exists, the existing data is replaced in the same position. That is, the order of the types list is not changed when replacing data of the same type. Example data types are text/plain and text/uri-list. Syntax void dataTransfer.setData(format, data); Arguments format A DOMString representing the type of the drag data to add to the drag object. data A DOMString representing the data to add to the drag object. ...
...lacing data of the same type. Example data types are text/plain and text/uri-list. Syntax void dataTransfer.setData(format, data); Arguments format A DOMString representing the type of the drag data to add to the drag object. data A DOMString representing the data to add to the drag object. ...
... of the same type. Example data types are text/plain and text/uri-list. Syntax void dataTransfer.setData(format, data); Arguments format A DOMString representing the type of the drag data to add to the drag object. data A DOMString representing the data to add to the drag object. ...
...And 9 more matches
EventTarget.removeEventListener() - Web APIs
The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see Matching event listeners for removal Syntax target.removeEventListener(type, listener[, options]); target.removeEventListener(type, listener[, useCapture]); Parameters type A string which specifies the type of event for which to remove an event listener. listener The EventListener function of the event handler to remove from the event target. ...
... parameter is absent, a default value of false is assumed. If a listener is registered twice, one with capture and one without, remove each one separately. Removal of a capturing listener does not affect a non-capturing version of the same listener, and vice versa. ...
...al of a capturing listener does not affect a non-capturing version of the same listener, and vice versa. Return value undefined Matching event listeners for removal Given an event listener previously added by calling addEventListener
(), you may eventually come to a point at which you need to remove it. Obviously, you need to specify the same type and listener parameters to removeEventListener
(). ...
...And 9 more matches
ParentNode.append() - Web APIs
Syntax // [Throws, Unscopable] ParentNode.append(...nodesOrDOMStrings) // returns undefined Parameters nodes A set of Node or DOMString objects to insert. ...
... Syntax // [Throws, Unscopable] ParentNode.append(...nodesOrDOMStrings) // returns undefined Parameters nodes A set of Node or DOMString objects to insert. ...
... Syntax // [Throws, Unscopable] ParentNode.append(...nodesOrDOMStrings) // returns undefined Parameters nodes A set of Node or DOMString objects to insert. ...
...And 9 more matches
SubtleCrypto.sign() - Web APIs
Syntax const signature = crypto.subtle.sign(algorithm, key, data); Parameters algorithm is a string or object that specifies the signature algorithm to use and its parameters: To use RSASSA-PKCS1-v1_5, pass the string "RSASSA-PKCS1-v1_5" or an object of the form { "name": "RSASSA-PKCS1-v1_5" }. To use RSA-PSS, pass an RsaPssParams object. To use ECDSA, pass an EcdsaParams object. ...
...gorithms that can be used for signing and signature verification. Three of these algorithms -- RSASSA-PKCS1-v1_5, RSA-PSS, and ECDSA -- are public-key cryptosystems that use the private key for signing and the public key for verification. These systems all use a digest algorithm to hash the message to a short fixed size before signing. The choice of digest algorithm is passed into the generateKey
() or importKey
() functions. The fourth algorithm -- HMAC -- uses the same algorithm and key for signing and for verification: this means that the verification key must be kept secret, which in turn means that this algorithm is not suitable for many signature use cases. It can be a good choice however when the signer and verifier are the same entity. RSASSA-PKCS1-v1_5 The RSASSA-PKCS1-v1_5 algori...
...ASSA-PKCS1-v1_5 The RSASSA-PKCS1-v1_5 algorithm is specified in RFC 3447. RSA-PSS The RSA-PSS algorithm is specified in RFC 3447. It's different from RSASSA-PKCS1-v1_5 in that it incorporates a random salt in the signature operation, so the same message signed with the same key will not result in the same signature each time. An extra property, defining the salt length, is passed into the sign
() and verify
() functions when they are invoked. ECDSA ECDSA (Elliptic Curve Digital Signature Algorithm) is a variant of the Digital Signature Algorithm, specified in FIPS-186, that uses Elliptic Curve Cryptography (RFC 6090). HMAC The HMAC algorithm calculates and verifies hash-based message authentication codes according to the FIPS 198-1 standard. The digest algorithm to use is specified in...
...And 9 more matches
WritableStream.getWriter() - Web APIs
The getWriter
() method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. Syntax var writer = writableStream.getWriter
(); Parameters None. Return value A WritableStreamDefaultWriter object instance. Exceptions TypeError The stream you are trying to create a writer for is not a WritableStream. Examples The following example illustrates several features of this interface. It shows the creation of the WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a function called sendMessage
(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter...
...stream you are trying to create a writer for is not a WritableStream. Examples The following example illustrates several features of this interface. It shows the creation of the WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a function called sendMessage
(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter
() method, which returns an instance of WritableStreamDefaultWriter. A forEach
() call is used to write each chunk of the string to the stream. Finally, write
() and close
() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySelector('ul'); function sendMessage(message, writableStream) { // defaultWriter is of type WritableStream...
...ter. A forEach
() call is used to write each chunk of the string to the stream. Finally, write
() and close
() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 9 more matches
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
The WritableStreamDefaultWriter
() constructor creates a new WritableStreamDefaultWriter object instance. Note: You generally wouldn't use this constructor manually; instead, you'd use the WritableStream.getWriter
() method. Syntax var writableStreamDefaultWriter = new WritableStreamDefaultWriter(stream); Parameters stream The WritableStream to be written to. Return value An instance of the WritableStreamDefaultWriter object. Exceptions TypeError The provided stream value is not a WritableStream, or it is locked to another writer already. Examples The following example shows the creation of a WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a function called sendMessage
(), passing the newly created stream and a string. Inside this f...
...ct. Exceptions TypeError The provided stream value is not a WritableStream, or it is locked to another writer already. Examples The following example shows the creation of a WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a function called sendMessage
(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter
() method, which returns an instance of WritableStreamDefaultWriter. A forEach
() call is used to write each chunk of the string to the stream. Finally, write
() and close
() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySelector('ul'); function sendMessage(message, writableStream) { // defaultWriter is of type WritableStream...
...ter. A forEach
() call is used to write each chunk of the string to the stream. Finally, write
() and close
() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 9 more matches
WritableStreamDefaultWriter.write() - Web APIs
Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. Syntax var promise = writableStreamDefaultWriter.write(chunk); Parameters chunk A block of binary data to pass to the WritableStream. Return value A Promise, which fulfills with the undefined upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. ...
...ined upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. Exceptions TypeError The target stream is not a writable stream, or it does not have an owner. Examples The following example shows the creation of a WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a function called sendMessage
(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter
() method, which returns an instance of WritableStreamDefaultWriter. A forEach
() call is used to write each chunk of the string to the stream. Finally, write
() and close
() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySelect...
...ter. A forEach
() call is used to write each chunk of the string to the stream. Finally, write
() and close
() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 9 more matches
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
The XRReferenceSpace interface's getOffsetReferenceSpace
() method returns a new reference space object which describes the relative difference in position between the object on which the method is called and a given point in 3D space. The object returned by getOffsetReferenceSpace
() is an XRReferenceSpace if called on an XRReferenceSpace, or an XRBoundedReferenceSpace if called on an object of that type. In other words, when you have an object in 3D space and need to position another object relative to that one, you can call getOffsetReferenceSpace
(), passing into it the position and orientation you want the second object to have relative to the position and orientation of the object on which you call getOffsetReferenceSpace
(). Then, when drawing the scene, you can use the offset refere...
...rom the object to the point given by originOffset. If the object on which you call this method is an XRBoundedReferenceSpace, the returned object is one as well. The boundsGeometry of the new reference space is set to the original object's boundsGeometry with each of its points multiplied by the inverse of originOffset. Examples Below are some examples showing how to use getOffsetReferenceSpace
(). Teleporting or setting the position of the viewer Upon first creating a scene, you may need to set the user's position within the 3D world. You can do that using getOffsetReferenceSpace
(). xrSession.requestReferenceSpace("local") .then((refSpace) => { xrReferenceSpace = refSpace; xrReferenceSpace = xrReferenceSpace.getOffsetReferenceSpace( new XRRigidTransform(startPosition, {x:0,...
... Implementing rotation based on non-XR inputs The input controls supported directly by WebXR are all dedicated VR or AR input devices. ...
...And 9 more matches
clamp() - CSS: Cascading Style Sheets
The clamp
() CSS function clamps a value between an upper and lower bound. clamp
() enables selecting a middle value within a range of values between a defined minimum and maximum. It takes three parameters: a minimum value, a preferred value, and a maximum allowed value. The clamp
() function can be used anywhere a <length>, <frequency>, <angle>, <time>, <percentage>, <number>, or <integer> is allowed. clamp(MIN, VAL, MAX) is resolved as max(MIN, min(VAL, MAX)) 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. ...
... <length>, <frequency>, <angle>, <time>, <percentage>, <number>, or <integer> is allowed. clamp(MIN, VAL, MAX) is resolved as max(MIN, min(VAL, MAX)) 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. ...
... The minimum value is the smallest (most negative) value. This is the lower bound in the range of allowed values. ...
...And 9 more matches
Array.prototype.reduce() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a Pull Request. The reducer function takes four arguments: Accumulator (acc) Current Value (cur) Current Index (idx) Source Array (src) Your reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array, and ultimately becomes the final, single resulting value. ...
...e accumulated value previously returned in the last invocation of the callback--or initialValue, if it was supplied (see below). currentValue The current element being processed in the array. index Optional The index of the current element being processed in the array. Starts from index 0 if an initialValue is provided. Otherwise, it starts from index 1. array Optional The array reduce
() was called upon. initialValue Optional A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first element in the array will be used as the initial accumulator value and skipped as currentValue. Calling reduce
() on an empty array without an initialValue will throw a TypeError. Return value The single value that results from the reduct...
...lValue Optional A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first element in the array will be used as the initial accumulator value and skipped as currentValue. Calling reduce
() on an empty array without an initialValue will throw a TypeError. Return value The single value that results from the reduction. ...
...And 9 more matches
Generator.prototype.next() - JavaScript
Return value An Object with two properties: done (boolean) Has the value true if the iterator is past the end of the iterated sequence. In this case value optionally specifies the return value of the iterator. Has the value false if the iterator was able to produce the next value in the sequence. This is equivalent of not specifying the done property altogether. ...
... Return value An Object with two properties: done (boolean) Has the value true if the iterator is past the end of the iterated sequence. In this case value optionally specifies the return value of the iterator. Has the value false if the iterator was able to produce the next value in the sequence. This is equivalent of not specifying the done property altogether. ...
... if the iterator is past the end of the iterated sequence. In this case value optionally specifies the return value of the iterator. Has the value false if the iterator was able to produce the next value in the sequence. This is equivalent of not specifying the done property altogether. value Any JavaScript value returned by the iterator. Can be omitted when done is true. ...
...And 9 more matches
Object.prototype.toString() - JavaScript
The toString
() method returns a string representing the object. 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 obj.toString
() Return value A string representing the object. Description Every object has a toString
() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString
() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString
() returns "[object type]", where type is the object type. The following code ill...
...called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString
() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString
() returns "[object type]", where type is the object type. The following code illustrates this: const o = new Object
(); o.toString
(); // returns [object Object] Note: Starting in JavaScript 1.8.5, toString
() called on null returns [object Null], and undefined returns [object Undefined], as defined in the 5th Edition of ECMAScript and subsequent Errata. ...
...ustom object, toString
() returns "[object type]", where type is the object type. The following code illustrates this: const o = new Object
(); o.toString
(); // returns [object Object] Note: Starting in JavaScript 1.8.5, toString
() called on null returns [object Null], and undefined returns [object Undefined], as defined in the 5th Edition of ECMAScript and subsequent Errata. See Using toString
() to detect object class. Parameters For Numbers and BigInts toString
() takes an optional parameter radix the value of radix must be minimum 2 and maximum 36. By using radix you can also convert base 10 numbers (like 1,2,3,4,5,.........) to another base numbers, in example below we are converting base 10 number to a base 2 (binary) number let baseTenInt = 10; console.log(baseTenInt.toStrin...
...And 9 more matches
Object.prototype.valueOf() - JavaScript
Also see Using unary plus. Description JavaScript calls the valueOf method to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ...
...Also see Using unary plus. Description JavaScript calls the valueOf method to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ...
...Also see Using unary plus. Description JavaScript calls the valueOf method to convert an object to a primitive value. ...
...And 9 more matches
String.prototype.match() - JavaScript
Return value An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found. ...
...itHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.match(regexp) Parameters regexp A regular expression object. If regexp is a non-RegExp object, it is implicitly converted to a RegExp by using new RegExp(regexp). If you don't give any parameter and use the match
() method directly, you will get an Array with an empty string: [""]. Return value An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found. If the g flag is used, all results matching the complete regular expression will be returned, but capturing groups will not. if the g flag is not used, only the first complete match and its related...
...ribed below. groups An object of named capturing groups whose keys are the names and values are the capturing groups or undefined if no named capturing groups were defined. See Groups and Ranges for more information. index The index of the search at which the result was found. input A copy of the search string. ...
...And 9 more matches
AnalyserNode.getFloatFrequencyData() - Web APIs
The getFloatFrequencyData
() method of the AnalyserNode Interface copies the current frequency data into a Float32Array array passed into it. Each item in the array represents the decibel value for a specific frequency. The frequencies are spread linearly from 0 to 1/2 of the sample rate. For example, for 48000 sample rate, the last item of the array will represent the decibel value for 24000 Hz. If you need higher performance and don't care about precision, you can use AnalyserNode.getByteFrequencyData
() instead, which works on a Uint8Array. ...
...lue for a specific frequency. The frequencies are spread linearly from 0 to 1/2 of the sample rate. For example, for 48000 sample rate, the last item of the array will represent the decibel value for 24000 Hz. If you need higher performance and don't care about precision, you can use AnalyserNode.getByteFrequencyData
() instead, which works on a Uint8Array. Syntax var audioCtx = new AudioContext
(); var analyser = audioCtx.createAnalyser
(); var dataArray = new Float32Array(analyser.frequencyBinCount); // Float32Array should be the same length as the frequencyBinCount void analyser.getFloatFrequencyData(dataArray); // fill the Float32Array with data returned from getFloatFrequencyData
() Parameters array The Float32Array that the frequency domain data will be copied to. For any sample ...
...loatFrequencyData
() Parameters array The Float32Array that the frequency domain data will be copied to. For any sample which is silent, the value is -Infinity. 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. ...
...And 8 more matches
MouseEvent.initMouseEvent() - Web APIs
The page on Creating and triggering events gives more information about the way to use these. ...
...The page on Creating and triggering events gives more information about the way to use these. ...
...The page on Creating and triggering events gives more information about the way to use these. ...
...And 8 more matches
PaymentResponse.retry() - Web APIs
This lets your app gracefully deal with situations such as invalid shipping addresses or declined credit cards. Syntax retryPromise = paymentRequest.retry(errorFields); Parameters errorFields A PaymentValidationErrors object, with the following properties: error Optional A general description of a payment error from which the user may attempt to recover by retrying the payment, possibly after correcting mistakes in the payment information. ...
...asicCardErrors object. shippingAddress Optional An AddressErrors object which contains error messages for any of the fields in the shipping address that failed validation. Return value A Promise which is resolved when the payment is successfully completed. The promise is rejected with an appropriate exception value if the payment fails again. Typically you will use this by calling show
(), then entering a loop or recursive function that checks the PaymentResponse for errors or other reasons to retry the payment request. If a retry is needed, the loop calls retry
(), then loops back to check the response when it comes in. The loop exits only when the user either cancels the payment request or the request is successful. See the example below for a thorough example, but the basic con...
...for errors or other reasons to retry the payment request. If a retry is needed, the loop calls retry
(), then loops back to check the response when it comes in. The loop exits only when the user either cancels the payment request or the request is successful. See the example below for a thorough example, but the basic concept, in outline form, is: Create a new PaymentRequest (new PaymentRequest
()) Display the payment request (PaymentRequest.show
() If show
() resolves, the returned PaymentResponse describes the requested payment and the options chosen by the user. Continue by... Validate the returned reponse; if there are any fields whose values are not acceptable, call the response's complete
() method with a value of "fail" to indicate failure. If the response's data is valid an...
...And 8 more matches
Array.prototype.filter() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax let newArray = arr.filter(callback(element[, index, [array]])[, thisArg]) Parameters callback Function is a predicate, to test each element of the array. Return true to keep the element, false otherwise. It accepts three arguments: element The current element being processed in the array. indexOptional The index of the current element being processed in the array. arrayOptional The array filter was called upon. ...
...The current element being processed in the array. indexOptional The index of the current element being processed in the array. arrayOptional The array filter was called upon. thisArgOptional Value to use as this when executing callback. Return value A new array with the elements that pass the test. If no elements pass the test, an empty array will be returned. Description filter
() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test ar...
...arguments: the value of the element the index of the element the Array object being traversed If a thisArg parameter is provided to filter, it will be used as the callback's this value. Otherwise, the value undefined will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. ...
...And 8 more matches
Promise.all() - JavaScript
This returned promise will resolve when all of the input's promises have resolved, or if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error. The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Promise.all(iterable); Parameters iterable An iterable object such as an Array. ...
...d, regardless of completion order. Description This method can be useful for aggregating the results of multiple promises. It is typically used when there are multiple asynchronous tasks that are dependent on one another to complete successfully, as it does not wait and will reject immediately upon any of the input promises rejecting. In comparison, the promise returned by Promise.allSettled
() will wait for all input promises to complete, regardless of whether or not one rejects. Consequently, it will always return the final result of every promise and function from the input iterable. Fulfillment The returned promise is fulfilled with an array containing all the values of the iterable passed as argument (also non-promise values). If an empty iterable is passed, then this method r...
...led asynchronously. Rejection If any of the passed-in promises reject, Promise.all asynchronously rejects with the value of the promise that rejected, whether or not the other promises have resolved. Examples Using Promise.all Promise.all waits for all fulfillments (or the first rejection). ...
...And 8 more matches
encodeURIComponent() - JavaScript
The encodeURIComponent
() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters). 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 encodeURIComponent(str); Parameters str String. A component of a URI. Return value A new string representing the provided string encoded as a URI component. Description encodeURIComponent
() escapes all characters except: Not Escaped: A-Z a-z 0-9 - _ . ! ~ * ' ( ) ...
...ect, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax encodeURIComponent(str); Parameters str String. A component of a URI. Return value A new string representing the provided string encoded as a URI component. Description encodeURIComponent
() escapes all characters except: Not Escaped: A-Z a-z 0-9 - _ . ...
...IComponent(str); Parameters str String. A component of a URI. Return value A new string representing the provided string encoded as a URI component. Description encodeURIComponent
() escapes all characters except: Not Escaped: A-Z a-z 0-9 - _ . ...
...And 8 more matches
AudioNode.connect() - Web APIs
Syntax var destinationNode = AudioNode.connect(destination, outputIndex, inputIndex); AudioNode.connect(destination, outputIndex); Parameters destination The AudioNode or AudioParam to which to connect. outputIndex Optional An index specifying which output of the current AudioNode to connect to the destination. The index numbers are defined according to the number of output channels (see Audio channels). ...
... AudioParam to which to connect. outputIndex Optional An index specifying which output of the current AudioNode to connect to the destination. The index numbers are defined according to the number of output channels (see Audio channels). While you can only connect a given output to a given input once (repeated attempts are ignored), you can connect an output to multiple inputs by calling connect
() repeatedly. This makes fan-out possible. The default value is 0. inputIndex Optional An index describing which input of the destination you want to connect the current AudioNode to; the default is 0. The index numbers are defined according to the number of input channels (see Audio channels). It is possible to connect an AudioNode to another AudioNode, which in turn connects back to the first A...
...nels (see Audio channels). It is possible to connect an AudioNode to another AudioNode, which in turn connects back to the first AudioNode, creating a cycle. This is allowed only if there is at least one DelayNode in the cycle. Otherwise, a NotSupportedError exception is thrown. This parameter is not allowed if the destination is an AudioParam. Return value If the destination is a node, connect
() returns a reference to the destination AudioNode object, allowing you to chain multiple connect
() calls. In some browsers, older implementations of this interface return undefined. If the destination is an AudioParam, connect
() returns undefined. Exceptions IndexSizeError The value specified as outputIndex or inputIndex doesn't correspond to an existing input or output. InvalidAccessError ...
...And 7 more matches
Document.getElementsByTagName() - Web APIs
The getElementsByTagName method of Document interface returns an HTMLCollection of elements with the given tag name. The complete document is searched, including the root node. The returned HTMLCollection is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to call document.getElementsByTagName
() again. Syntax var elements = document.getElementsByTagName(name); elements is a live HTMLCollection (but see the note below) of found elements in the order they appear in the tree. name is a string representing the name of the elements. The special string "*" represents all elements. The latest W3C specification says elements is an HTMLCollection; however, this method returns a NodeList in WebKit browsers. See bug 14869 for details. Example...
...ion (but see the note below) of found elements in the order they appear in the tree. name is a string representing the name of the elements. The special string "*" represents all elements. The latest W3C specification says elements is an HTMLCollection; however, this method returns a NodeList in WebKit browsers. See bug 14869 for details. Example In the following example, getElementsByTagName
() starts from a particular parent element and searches top-down recursively through the DOM from that parent element, building a collection of all descendant elements which match the tag name parameter. This demonstrates both document.getElementsByTagName
() and the functionally identical Element.getElementsByTagName
(), which starts the search at a specific element within the DOM tree. Clicking the...
...lement and searches top-down recursively through the DOM from that parent element, building a collection of all descendant elements which match the tag name parameter. This demonstrates both document.getElementsByTagName
() and the functionally identical Element.getElementsByTagName
(), which starts the search at a specific element within the DOM tree. Clicking the buttons uses getElementsByTagName
() to count the descendant paragraph elements of a particular parent (either the document itself or one of two nested <div> elements). ...
...And 7 more matches
Document.requestStorageAccess() - Web APIs
Conditions for granting storage access Storage access is granted based on a series of checks described here: If the document already has been granted access, resolve. If the document has a null origin, reject. If the document's frame is the main frame, resolve. If the sub frame's origin is equal to the main frame's, resolve. If the sub frame is not sandboxed, skip to step 7. If the sub frame doesn't have the token allow-storage-access-by-user-activation, reject. If the sub frame's parent frame is not the top frame, reject. If the browser is not processing a user gesture, reject. ...
...esture, reject. Check any additional rules that the browser has. Examples: allow lists, block lists, on-device classification, user settings, anti-clickjacking heuristics, or prompting the user for explicit permission. Reject if some rule is not fulfilled. Grant the document access to cookies and other site storage and store that fact for the purposes of future calls to Document.hasStorageAccess
() and requestStorageAccess
(). Assuming all of the requirements above are satisfied, Firefox will automatically grant storage access to the requesting origin on up to a threshold number of first-party origins in the current session for the duration of user's session, up to a maximum of 24 hours. After the requesting origin has exceeded the maximum allowable number of storage access grants, any fut...
...ssuming all of the requirements above are satisfied, Firefox will automatically grant storage access to the requesting origin on up to a threshold number of first-party origins in the current session for the duration of user's session, up to a maximum of 24 hours. After the requesting origin has exceeded the maximum allowable number of storage access grants, any future call to requestStorageAccess
() during the same browsing session will prompt the user. The maximum number of concurrent storage access grants an origin can obtain is a positive integer currently defined as one percent of the number of top-level origins visited in the current session or 5, whichever is higher. The threshold is enforced on the level of eTLD+1, so for example two storage access grants for foo.example.com and bar.
...And 7 more matches
IDBCursor.update() - Web APIs
Note: This feature is available in Web Workers. Syntax var anIDBRequest = myIDBCursor.update(value); Parameters value The new value to be stored at the current position. Return value An IDBRequest object on which subsequent events related to this operation are fired. ...
... Note: This feature is available in Web Workers. Syntax var anIDBRequest = myIDBCursor.update(value); Parameters value The new value to be stored at the current position. Return value An IDBRequest object on which subsequent events related to this operation are fired. ...
... Note: This feature is available in Web Workers. Syntax var anIDBRequest = myIDBCursor.update(value); Parameters value The new value to be stored at the current position. Return value An IDBRequest object on which subsequent events related to this operation are fired. ...
...And 7 more matches
KeyboardEvent.getModifierState() - Web APIs
The KeyboardEvent.getModifierState
() method returns the current state of the specified modifier key: true if the modifier is active (that is the modifier key is pressed or locked), otherwise, false. Syntax var active = event.getModifierState(keyArg); Returns A Boolean Parameters keyArg A modifier key value. The value must be one of the KeyboardEvent.key values which represent modifier keys, or the string "Accel" . This is case-sensitive. Modifier keys on Internet Explorer IE9 uses "Scroll" for "ScrollLock" and "Win" for "OS". ...
...lse. Syntax var active = event.getModifierState(keyArg); Returns A Boolean Parameters keyArg A modifier key value. The value must be one of the KeyboardEvent.key values which represent modifier keys, or the string "Accel" . This is case-sensitive. Modifier keys on Internet Explorer IE9 uses "Scroll" for "ScrollLock" and "Win" for "OS". ...
...ntrol" and "Shift" may be supported. All modifiers (except "FnLock", "Hyper", "Super" and "Symbol" which are defined after Gecko implements this) are always supported for untrusted events on Gecko. This doesn't depend on the platform. "Accel" virtual modifier Note: The "Accel" virtual modifier has been effectively deprecated in current drafts of the DOM3 Events specification. getModifierState
() also accepts a deprecated virtual modifier named "Accel". event.getModifierState("Accel") returns true when at least one of KeyboardEvent.ctrlKey or KeyboardEvent.metaKey is true. In old implementations and outdated specifications, it returned true when a modifier which is the typical modifier key for the shortcut key is pressed. For example, on Windows, pressing Ctrl key may make it return true...
...And 7 more matches
RTCPeerConnection.setLocalDescription() - Web APIs
The RTCPeerConnection method setLocalDescription
() changes the local description associated with the connection. This description specifies the properties of the local end of the connection, including the media format. The method takes a single parameter--the session description--and it returns a Promise which is fulfilled once the description has been changed, asynchronously. If setLocalDescription
() is called while a connection is already in place, it means renegotiation is underway (possibly to adapt to changing network conditions). Because descriptions will be exchanged until the two peers agree on a configuration, the description submitted by calling setLocalDescription
() does not immediately take effect. Instead, the current connection configuration remains in place until negotiation...
... WebRTC runtime tries to automatically do the right thing. Implicit description If you don't explicity provide a session description, the WebRTC runtime will try to handle it correctly. If the signaling state is one of stable, have-local-offer, or have-remote-pranswer, the WebRTC runtime automatically creates a new offer and sets that as the new local description. ...
...RTC runtime automatically creates a new offer and sets that as the new local description. Otherwise, setLocalDescription
() creates an answer, which becomes the new local description. Type of the description parameter The description is of type RTCSessionDescriptionInit, which is a serialized version of a RTCSessionDescription browser object. They're interchangeable: myPeerConnection.createOffer
().then(function(offer) { return myPeerConnection.setLocalDescription(offer); }); This is equivalent to: myPeerConnection.createOffer
().then(function(offer) { return myPeerConnection.setLocalDescription(new RTCSessionDescription(offer)); }); For this reason, the RTCSessionDescription
() constructor is deprecated. Return value A Promise which is fulfilled once the value of RTCPeerConnection...
...And 7 more matches
ReadableStream.cancel() - Web APIs
Syntax var promise = readableStream.cancel(reason); Parameters reason A DOMString providing a human-readable reason for the cancellation. Return value A Promise, which fulfills with the value given in the reason parameter. ...
...erlying source, which may or may not use it. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use ReadableStreamDefaultController.close
(). Syntax var promise = readableStream.cancel(reason); Parameters reason A DOMString providing a human-readable reason for the cancellation. Return value A Promise, which fulfills with the value given in the reason parameter. Exceptions TypeError The stream you are trying to cancel is not a ReadableStream, or it is locked. Examples In Jake Archibald's cancelling a fetch example, a...
...alue A Promise, which fulfills with the value given in the reason parameter. Exceptions TypeError The stream you are trying to cancel is not a ReadableStream, or it is locked. Examples In Jake Archibald's cancelling a fetch example, a stream is used to fetch the WHATWG HTML spec chunk by chunk; each chunk is searched for the string "service workers". When the search terms is found, cancel
() is used to cancel the stream -- the job is finished so it is no longer needed. var searchTerm = "service workers"; // Chars to show either side of the result in the match var contextBefore = 30; var contextAfter = 30; var caseInsensitive = true; var url = 'https://html.spec.whatwg.org/'; console.log(`Searching '${url}' for '${searchTerm}'`); fetch(url).then(response => { console.log('Receive...
...And 7 more matches
SubtleCrypto.deriveKey() - Web APIs
It takes as arguments some initial key material, the derivation algorithm to use, and the desired properties for the key to derive. It returns a Promise which will be fulfilled with a CryptoKey object representing the new key. It's worth noting that the three key derivation algorithms you can use have quite different characteristics and are appropriate in quite different situations. See Supported algorithms for some more detail on this. Syntax const result = crypto.subtle.deriveKey( algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages ); Parameters algorithm is an object defining the derivation algorithm to use. ...
...se HKDF, pass an HkdfParams object. To use PBKDF2, pass a Pbkdf2Params object. baseKey is a CryptoKey representing the input to the derivation algorithm. If algorithm is ECDH, then this will be the ECDH private key. Otherwise it will be the initial key material for the derivation function: for example, for PBKDF2 it might be a password, imported as a CryptoKey using SubtleCrypto.importKey
(). derivedKeyAlgorithm is an object defining the algorithm the derived key will be used for. For HMAC: pass an HmacKeyGenParams object. For AES-CTR, AES-CBC, AES-GCM, or AES-KW: pass an AesKeyGenParams object. extractable is a Boolean indicating whether it will be possible to export the key using SubtleCrypto.exportKey
() or SubtleCrypto.wrapKey
(). keyUsages is an Array indicating...
... value of that key doesn't contain deriveKey. NotSupported Raised when trying to use an algorithm that is either unknown or isn't suitable for derivation, or if the algorithm requested for the derived key doesn't define a key length. SyntaxError Raised when keyUsages is empty but the unwrapped key is of type secret or private. Supported algorithms The three algorithms supported by deriveKey
() have quite different characteristics and are appropriate in different situations. ECDH ECDH (Elliptic Curve Diffie-Hellman) is a key-agreement algorithm. It enables two people who each have an ECDH public/private key pair to generate a shared secret: that is, a secret that they -- and noone else -- share. They can then use this shared secret as a symmetric key to secure their communication, or ...
...And 7 more matches
SubtleCrypto.wrapKey() - Web APIs
The wrapKey
() method of the SubtleCrypto interface "wraps" a key. This means that it exports the key in an external, portable format, then encrypts the exported key. Wrapping a key helps protect it in untrusted environments, such as inside an otherwise unprotected data store or in transmission over an unprotected network. As with SubtleCrypto.exportKey
(), you specify an export format for the key. To export a key, it must have CryptoKey.extractable set to true. But because wrapKey
() also encrypts the key to be imported, you also need to pass in the key that must be used to encrypt it. This is sometimes called the "wrapping key". The inverse of wrapKey
() is SubtleCrypto.unwrapKey
(): while wrapKey is composed of export + encrypt, unwrapKey is composed of import + decrypt. Syntax const r...
...RFC 3394. Examples Note: You can try the working examples out on GitHub. Raw wrap This example wraps an AES key. It uses "raw" as the export format and AES-KW, with a password-derived key, to encrypt it. See the complete code on GitHub. let salt; /* Get some key material to use as input to the deriveKey method. The key material is a password supplied by the user. */ function getKeyMaterial
() { const password = window.prompt("Enter your password"); const enc = new TextEncoder
(); return window.crypto.subtle.importKey( "raw", enc.encode(password), {name: "PBKDF2"}, false, ["deriveBits", "deriveKey"] ); } /* Given some key material and some random salt derive an AES-KW key using PBKDF2. */ function getKey(keyMaterial, salt) { return window.crypto.subtle.der...
...) { return window.crypto.subtle.deriveKey( { "name": "PBKDF2", salt: salt, "iterations": 100000, "hash": "SHA-256" }, keyMaterial, { "name": "AES-KW", "length": 256}, true, [ "wrapKey", "unwrapKey" ] ); } /* Wrap the given key. */ async function wrapCryptoKey(keyToWrap) { // get the key encryption key const keyMaterial = await getKeyMaterial
(); salt = window.crypto.getRandomValues(new Uint8Array(16)); const wrappingKey = await getKey(keyMaterial, salt); return window.crypto.subtle.wrapKey( "raw", keyToWrap, wrappingKey, "AES-KW" ); } /* Generate an encrypt/decrypt secret key, then wrap it. */ window.crypto.subtle.generateKey( { name: "AES-GCM", length: 256, }, true, ["encrypt", "decrypt"] ) .t...
...And 7 more matches
attr() - CSS: Cascading Style Sheets
It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned. ...
...It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned. ...
...tr(data-width px, inherit); attr(data-something, "default"); Syntax Values attribute-name Is the name of an attribute on the HTML element referenced in the CSS. <type-or-unit> Is a keyword representing either the type of the attribute's value, or its unit, as in HTML some attributes have implicit units. If the use of <type-or-unit> as a value for the given attribute is invalid, the attr
() expression will be invalid too. If omitted, it defaults to string. The list of valid values are: Keyword Associated type Comment Default value string <string> The attribute value is treated as a CSS <string>. It is NOT reparsed, and in particular the characters are used as-is instead of CSS escapes being turned into different characters. An e...
...And 7 more matches
min() - CSS: Cascading Style Sheets
The min
() CSS function lets you set the smallest (most negative) value from a list of comma-separated expressions as the value of a CSS property value. The min
() function can be used anywhere a <length>, <frequency>, <angle>, <time>, <percentage>, <number>, or <integer> is allowed. 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. In the first above example, the width will be at most 200px, but will be smaller if the viewport is less than 400px wide (in which case 1vw would be 4px, so 50vw would be 200px). In other words, the maximum width is 200px. ...
...pository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. In the first above example, the width will be at most 200px, but will be smaller if the viewport is less than 400px wide (in which case 1vw would be 4px, so 50vw would be 200px). In other words, the maximum width is 200px. ...
...ease clone https://github.com/mdn/interactive-examples and send us a pull request. In the first above example, the width will be at most 200px, but will be smaller if the viewport is less than 400px wide (in which case 1vw would be 4px, so 50vw would be 200px). In other words, the maximum width is 200px. Think of the min
() value as providing the maximum value a property can have. Syntax The min
() function takes one or more comma-separated expressions as its parameter, with the smallest (most negative) expression value result used as the value. The expressions can be math expressions (using arithmetic operators), literal values, or other expressions, such as attr
(), that evaluate to a valid argument type (like <length>). You can use different units for each value in your expression, if y...
...And 7 more matches
Array.prototype.some() - JavaScript
The some
() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean 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 arr.some(callback(element[, index[, array]])[, thisArg]) Parameters callback A function to test for each element, taking three arguments: element The current element being processed in the array. indexOptional The index of the current element being processed in the array. arrayOptional The array some
() was called upon. thisArgOptional A value to use as this when executing callback. R...
...he current element being processed in the array. indexOptional The index of the current element being processed in the array. arrayOptional The array some
() was called upon. thisArgOptional A value to use as this when executing callback. Return value true if the callback function returns a truthy value for at least one element in the array. Otherwise, false. Description The some
() method executes the callback function once for each element present in the array until it finds the one where callback returns a truthy value (a value that becomes true when converted to a Boolean). If such an element is found, some
() immediately returns true. Otherwise, some
() returns false. callback is invoked only for indexes of the array with assigned values. It is not invoked for indexes whi...
...ediately returns true. Otherwise, some
() returns false. callback is invoked only for indexes of the array with assigned values. It is not invoked for indexes which have been deleted or which have never been assigned values. callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. If a thisArg parameter is provided to some
(), it will be used as the callback's this value. Otherwise, the value undefined will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. some
() does not mutate the array on which it is called. The range of elements processed by some
() is set before the first invocation of callback. Elem...
...And 7 more matches
Map.prototype[@@iterator]() - JavaScript
operty is the same function object as the initial value of the entries method. 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. ...
...ue of the entries method. 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 myMap[Symbol.iterator] Return value The map iterator function, which is the entries
() function by default. ...
... 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 myMap[Symbol.iterator] Return value The map iterator function, which is the entries
() function by default. ...
...And 7 more matches
Object.prototype.toLocaleString() - JavaScript
The toLocaleString
() method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes. 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 obj.toLocaleString
() Return value A string representing the object. Description Object's toLocaleString returns the result of calling toString
(). This function is provided to give objects a generic toLocaleString method, even though not all may use it. See the list below. ...
...-examples and send us a pull request. Syntax obj.toLocaleString
() Return value A string representing the object. Description Object's toLocaleString returns the result of calling toString
(). This function is provided to give objects a generic toLocaleString method, even though not all may use it. See the list below. ...
...ax obj.toLocaleString
() Return value A string representing the object. Description Object's toLocaleString returns the result of calling toString
(). This function is provided to give objects a generic toLocaleString method, even though not all may use it. See the list below. ...
...And 7 more matches
Promise.prototype.catch() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax p.catch(onRejected); p.catch(function(reason) { // rejection }); Parameters onRejected A Function called when the Promise is rejected. ...
... 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 p.catch(onRejected); p.catch(function(reason) { // rejection }); Parameters onRejected A Function called when the Promise is rejected. ...
...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 p.catch(onRejected); p.catch(function(reason) { // rejection }); Parameters onRejected A Function called when the Promise is rejected. This function has one argument: reason The rejection reason. The Promise returned by catch
() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved. Return value Internally calls Promise.prototype.then on the object upon which it was called, passing the parameters undefined and the received onRejected handler. Returns the value of that call, which is a Promise. Note the examples below are throwing instances of Error. This i...
...And 7 more matches
AudioContext.getOutputTimestamp() - Web APIs
The getOutputTimestamp
() property of the AudioContext interface returns a new AudioTimestamp object containing two audio timestamp values relating to the current audio context. The two values are as follows: AudioTimestamp.contextTime: The time of the sample frame currently being rendered by the audio output device (i.e., output audio stream position), in the same units and origin as the context's AudioContext.currentTime. Basically, this is the time after the audio context was first created. AudioTimestamp.performanceTime: An estimation of the moment when the sample frame corresponding to the stored contextTime value was rendered by the audio output device, in the same units and origin as performance.now
(). This is the time after the document containing the audio context was first ren...
... Returns An AudioTimestamp object, which has the following properties. ...
...; the time after the document containing the audio context was first rendered Examples In the following code we start to play an audio file after a play button is clicked, and start off a requestAnimationFrame loop running, which constantly outputs the contextTime and performanceTime. You can see full code of this example at output-timestamp (see it live also). ...
...And 6 more matches
CanvasRenderingContext2D.rect() - Web APIs
Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. ...
... Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. ...
... Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. ...
...And 6 more matches
CustomElementRegistry.define() - Web APIs
There are two types of custom elements you can create: Autonomous custom element: Standalone elements; they don't inherit from built-in HTML elements. Customized built-in element: These elements inherit from -- and extend -- built-in HTML elements. Syntax customElements.define(name, constructor, options); Parameters name Name for the new custom element. Note that custom element names must contain a hyphen. constructor Constructor for the new custom element. options Optional Object that controls how the element is defined. One option is currently supported: extends: String specifying the name of a built-in element to extend. Used to create a customized built-in element. ...
...rwise already defined), or extends is specified and it is a valid custom element name, or extends is specified but the element it is trying to extend is an unknown element. SyntaxError The provided name is not a valid custom element name. TypeError The referenced constructor is not a constructor. ...
...ement name, or extends is specified but the element it is trying to extend is an unknown element. SyntaxError The provided name is not a valid custom element name. TypeError The referenced constructor is not a constructor. Note: You'll often get NotSupportedErrors thrown that seem like define
() is failing, but instead it is likely a problem with Element.attachShadow
(). ...
...And 6 more matches
DataTransfer.setDragImage() - Web APIs
The image will typically be an <image> element but it can also be a <canvas> or any other visible element. ...
...'s image (at its intrinsic size); otherwise, set the drag data store bitmap to an image generated from the given element (the exact mechanism for doing so is not currently specified). xOffset A long indicating the horizontal offset within the image. yOffset A long indicating the vertical offset within the image. ...
...cal offset within the image. Return value void Example This example shows how to use the setDragImage
() method. Note the example refers to an image file named example.gif. If that file is present, it will be used as the drag image and if that file is not present, the browser will use its default drag image. demo <!DOCTYPE html> <html lang=en> <title>Example of DataTransfer.setDragImage
()</title> <meta name="viewport" content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> <script> function dragstart_handler(ev) { console.log("dragStart"); // Set the drag's format and data. Use the event target's id for the data ev.dataTransfer.setData...
...And 6 more matches
Document.write() - Web APIs
The Document.write
() method writes a string of text to a document stream opened by document.open
(). Note: Because document.write
() writes to the document stream, calling document.write
() on a closed (loaded) document automatically calls document.open
(), which will clear the document. Syntax document.write(markup); Parameters markup A string containing the text to be written to the document. ...
...In the example above, the h1 element becomes a node in the document. ...
...In the example above, the h1 element becomes a node in the document. ...
...And 6 more matches
HTMLMediaElement.play() - Web APIs
Exceptions The promise's rejection handler is called with an exception name passed in as its sole input parameter (as opposed to a traditional exception being thrown). ...
... Exceptions The promise's rejection handler is called with an exception name passed in as its sole input parameter (as opposed to a traditional exception being thrown). ...
... Exceptions The promise's rejection handler is called with an exception name passed in as its sole input parameter (as opposed to a traditional exception being thrown). ...
...And 6 more matches
IDBCursor.delete() - Web APIs
The result attribute is set to undefined. ...
...The result attribute is set to undefined. ...
...The result attribute is set to undefined. ...
...And 6 more matches
ParentNode.querySelectorAll() - Web APIs
This string must be a valid CSS selector string; if it's not, a SyntaxError exception is thrown. ...
...This string must be a valid CSS selector string; if it's not, a SyntaxError exception is thrown. ...
...This string must be a valid CSS selector string; if it's not, a SyntaxError exception is thrown. ...
...And 6 more matches
performance.clearResourceTimings() - Web APIs
The clearResourceTimings
() method removes all performance entries with an entryType of "resource" from the browser's performance data buffer and sets the size of the performance data buffer to zero. To set the size of the browser's performance data buffer, use the Performance.setResourceTimingBufferSize
() method. Note: This feature is available in Web Workers. Syntax performance.clearResourceTimings
(); Arguments void Return value none This method has no return value. ...
...rmance data buffer and sets the size of the performance data buffer to zero. To set the size of the browser's performance data buffer, use the Performance.setResourceTimingBufferSize
() method. Note: This feature is available in Web Workers. Syntax performance.clearResourceTimings
(); Arguments void Return value none This method has no return value. ...
...the size of the performance data buffer to zero. To set the size of the browser's performance data buffer, use the Performance.setResourceTimingBufferSize
() method. Note: This feature is available in Web Workers. Syntax performance.clearResourceTimings
(); Arguments void Return value none This method has no return value. ...
...And 6 more matches
RTCPeerConnection.addStream() - Web APIs
If the signalingState is set to closed, an InvalidStateError is raised. If the signalingState is set to stable, the event negotiationneeded is sent on the RTCPeerConnection to indicate that ICE negotiation must be repeated to consider the new stream. Syntax rtcPeerConnection.addStream(mediaStream); Parameters mediaStream A MediaStream object indicating the stream to add to the WebRTC peer connection. Return value None. ...
... rtcPeerConnection.addStream(mediaStream); Parameters mediaStream A MediaStream object indicating the stream to add to the WebRTC peer connection. Return value None. Example This simple example adds the audio and video stream coming from the user's camera to the connection. ...
...s mediaStream A MediaStream object indicating the stream to add to the WebRTC peer connection. Return value None. Example This simple example adds the audio and video stream coming from the user's camera to the connection. ...
...And 6 more matches
RTCPeerConnection.createOffer() - Web APIs
The SDP offer includes information about any MediaStreamTracks already attached to the WebRTC session, codec, and options supported by the browser, and any candidates already gathered by the ICE agent, for the purpose of being sent over the signaling channel to a potential peer to request a connection or to update the configuration of an existing connection. The return value is a Promise which, when the offer has been created, is resolved with a RTCSessionDescription object containing the newly-created offer. ...
...lume sounds. Also, emergency calls should never cut audio when quiet. This option defaults to true (voice activity detection enabled). Deprecated parameters In older code and documentation, you may see a callback-based version of this function. This has been deprecated and its use is strongly discouraged. You should update any existing code to use the Promise-based version of createOffer
() instead. The parameters for this form of createOffer
() are described below, to aid in updating existing code. successCallback An RTCSessionDescriptionCallback which will be passed a single RTCSessionDescription object describing the newly-created offer. errorCallback An RTCPeerConnectionErrorCallback which will be passed a single DOMException object explaining why the request to create...
...ld be delivered through the signaling server to a remote peer. Exceptions These exceptions are returned by rejecting the returned promise. Your rejection handler should examine the received exception to determine which occurred. InvalidStateError The RTCPeerConnection is closed. NotReadableError No certificate or set of certificates was provided for securing the connection, and createOffer
() was unable to create a new one. Since all WebRTC connections are required to be secured, that results in an error. OperationError Examining the state of the system to determine resource availability in order to generate the offer failed for some reason. Example Here we see a handler for the negotiationneeded event which creates the offer and sends it to the remote system over a signaling cha...
...And 6 more matches
SubtleCrypto.importKey() - Web APIs
The function accepts several import formats: see Supported formats for details. Syntax const result = crypto.subtle.importKey( format, keyData, algorithm, extractable, usages ); Parameters format is a string describing the data format of the key to import. It can be one of the following: raw: Raw format. pkcs8: PKCS #8 format. spki: SubjectPublicKeyInfo format. jwk: JSON Web Key format. keyData is an ArrayBuffer, a TypedArray, a DataView, or a JSONWebKey object containing the key in the given format. ...
...rtParams object. For HMAC: Pass an HmacImportParams object. For AES-CTR, AES-CBC, AES-GCM, or AES-KW: Pass the string identifying the algorithm or an object of the form { "name": ALGORITHM }, where ALGORITHM is the name of the algorithm. For PBKDF2 : Pass the string PBKDF2. extractable is a Boolean indicating whether it will be possible to export the key using SubtleCrypto.exportKey
() or SubtleCrypto.wrapKey
(). keyUsages is an Array indicating what can be done with the key. Possible array values are: encrypt: The key may be used to encrypt messages. decrypt: The key may be used to decrypt messages. sign: The key may be used to sign messages. verify: The key may be used to verify signatures. deriveKey: The key may be used in deriving a new key. deriveBits:...
... You can use this format to import or export RSA or Elliptic Curve private keys. The PKCS #8 format is defined in RFC 5208., using the ASN.1 notation: PrivateKeyInfo ::= SEQUENCE { version Version, privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, privateKey PrivateKey, attributes [0] IMPLICIT Attributes OPTIONAL } The importKey
() method expects to receive this object as an ArrayBuffer containing the DER-encoded form of the PrivateKeyInfo. DER is a set of rules for encoding ASN.1 structures into a binary form. You are most likely to encounter this object in PEM format. PEM format is a way to encode binary data in ASCII. It consists of a header and a footer, and in between, the base64-encoded binary data. A PEM-encoded Pri...
...And 6 more matches
WindowOrWorkerGlobalScope.clearTimeout() - Web APIs
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. If you click the page multiple times in one second, the alert only appears once. ...
...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. If you click the page multiple times in one second, the alert only appears once. ...
...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. If you click the page multiple times in one second, the alert only appears once. ...
...And 6 more matches
XMLHttpRequest.getAllResponseHeaders() - Web APIs
Return value A ByteString representing all of the response's headers (except those whose field name is Set-Cookie or Set-Cookie2) separated by CRLF, or null if no response has been received. If a network error happened, an empty string is returned. ...
... Return value A ByteString representing all of the response's headers (except those whose field name is Set-Cookie or Set-Cookie2) separated by CRLF, or null if no response has been received. If a network error happened, an empty string is returned. ...
...ower case, as per the latest spec. Example This example examines the headers in the request's readystatechange event handler, XMLHttpRequest.onreadystatechange. The code shows how to obtain the raw header string, as well as how to convert it into an array of individual headers and then how to take that array and create a mapping of header names to their values. ...
...And 6 more matches
calc() - CSS: Cascading Style Sheets
The expression can be any simple expression combining the following operators, using standard operator precedence rules: + Addition. - Subtraction. * Multiplication. ...
...here a <length>, <frequency>, <angle>, <time>, <percentage>, <number>, or <integer> is allowed. 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 /* property: calc(expression) */ width: calc(100% - 80px); The calc
() function takes a single expression as its parameter, with the expression's result used as the value. The expression can be any simple expression combining the following operators, using standard operator precedence rules: + Addition. - Subtraction. * Multiplication. At least one of the arguments must be a <number>. / Division. The right-hand side must be a <number>. The operands in th...
...e, but adding it for consistency is both allowed and recommended. Division by zero results in an error being generated by the HTML parser. Math expressions involving percentages for widths and heights on table columns, table column groups, table rows, table row groups, and table cells in both auto and fixed layout tables may be treated as if auto had been specified. ...
...And 6 more matches
max() - CSS: Cascading Style Sheets
The max
() CSS function lets you set the largest (most positive) value from a list of comma-separated expressions as the value of a CSS property value. The max
() function can be used anywhere a <length>, <frequency>, <angle>, <time>, <percentage>, <number>, or <integer> is allowed. 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. In the first above example, the width will be at least 400px, but will be wider if the the viewport is more than 2000px wide (in which case 1vw would be 20px, so 20vw would be 400px). Think of the max
() value as providing the minimum value a property can have. ...
...to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. In the first above example, the width will be at least 400px, but will be wider if the the viewport is more than 2000px wide (in which case 1vw would be 20px, so 20vw would be 400px). Think of the max
() value as providing the minimum value a property can have. ...
... You can use different units for each value in your expression. You may also use parentheses to establish computation order when needed. ...
...And 6 more matches
Array.from() - JavaScript
The Array.from
() static method creates a new, shallow-copied Array instance from an array-like or iterable object. 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 Array.from(arrayLike [, mapFn [, thisArg]]) Parameters arrayLike An array-like or iterable object to convert to an array. mapFn Optional Map function to call on every element of the array. thisArg Optional Value to use as this when executing mapFn. Return value A new Array instance. ...
...tps://github.com/mdn/interactive-examples and send us a pull request. Syntax Array.from(arrayLike [, mapFn [, thisArg]]) Parameters arrayLike An array-like or iterable object to convert to an array. mapFn Optional Map function to call on every element of the array. thisArg Optional Value to use as this when executing mapFn. Return value A new Array instance. Description Array.from
() lets you create Arrays from: array-like objects (objects with a length property and indexed elements); or iterable objects (objects such as Map and Set). Array.from
() has an optional parameter mapFn, which allows you to execute a map
() function on each element of the array being created. More clearly, Array.from(obj, mapFn, thisArg) has the same result as Array.from(obj).map(mapFn, thisArg...
...the array being created. More clearly, Array.from(obj, mapFn, thisArg) has the same result as Array.from(obj).map(mapFn, thisArg), except that it does not create an intermediate array. This is especially important for certain array subclasses, like typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type. The length property of the from
() method is 1. In ES2015, the class syntax allows sub-classing of both built-in and user-defined classes. As a result, static methods such as Array.from
() are "inherited" by subclasses of Array, and create new instances of the subclass, not Array. Polyfill Array.from
() was added to the ECMA-262 standard in the 6th Edition (ES2015). As such, it may not be present in other implementations of the s...
...And 6 more matches
Error.prototype.toString() - JavaScript
The toString
() method returns a string representing the specified Error object. Syntax e.toString
() Return value A string representing the specified Error object. Description The Error object overrides the Object.prototype.toString
() method inherited by all objects. ...
... The toString
() method returns a string representing the specified Error object. Syntax e.toString
() Return value A string representing the specified Error object. Description The Error object overrides the Object.prototype.toString
() method inherited by all objects. ...
... e.toString
() Return value A string representing the specified Error object. Description The Error object overrides the Object.prototype.toString
() method inherited by all objects. ...
...And 6 more matches
Function.prototype.call() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax func.call([thisArg[, arg1, arg2, ...argN]]) Parameters thisArg Optional The value to use as this when calling func. Caution: In certain cases, thisArg may not be the actual value seen by the method. If the method is a function in non-strict mode, null and undefined will be replaced with the global object, and primitive values will be converted to objects. arg1, arg2, ...argN Optional Arguments for the function. ...
..., thisArg may not be the actual value seen by the method. If the method is a function in non-strict mode, null and undefined will be replaced with the global object, and primitive values will be converted to objects. arg1, arg2, ...argN Optional Arguments for the function. Return value The result of calling the function with the specified this value and arguments. ...
...l and undefined will be replaced with the global object, and primitive values will be converted to objects. arg1, arg2, ...argN Optional Arguments for the function. Return value The result of calling the function with the specified this value and arguments. Description The call
() allows for a function/method belonging to one object to be assigned and called for a different object. call
() provides a new value of this to the function/method. With call
(), you can write a method once and then inherit it in another object, without having to rewrite the method for the new object. Note: While the syntax of this function is almost identical to that of apply
(), the fundamental difference is that call
() accepts an argument list, while apply
() accepts a single array of arguments. Exampl...
...And 6 more matches
Reflect.construct() - JavaScript
It is equivalent to calling new target(...args). It gives also the added option to specify a different prototype. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.construct(target, argumentsList[, newTarget]) Parameters target The target function to call. argumentsList An array-like object specifying the arguments with which target should be called. newTarget Optional The constructor whose prototype should be used. See also the new.target operator. ...
...ewTarget Optional The constructor whose prototype should be used. See also the new.target operator. If newTarget is not present, its value defaults to target. Return value A new instance of target (or newTarget, if present), initialized by target as a constructor with the given argumentsList. Exceptions A TypeError, if target or newTarget are not constructors. ...
... as a constructor with the given argumentsList. Exceptions A TypeError, if target or newTarget are not constructors. Description Reflect.construct
() allows you to invoke a constructor with a variable number of arguments. (This would also be possible by using the spread syntax combined with the new operator.) let obj = new Foo(...args) let obj = Reflect.construct(Foo, args) Reflect.construct
() vs Object.create
() Prior to the introduction of Reflect, objects could be constructed using an arbitrary combination of constructor and prototype by using Object.create
(). ...
...And 6 more matches
WebAssembly.instantiate() - JavaScript
The WebAssembly.instantiate
() function allows you to compile and instantiate WebAssembly code. This function has two overloads: The primary overload takes the WebAssembly binary code, in the form of a typed array or ArrayBuffer, and performs both compilation and instantiation in one step. The returned Promise resolves to both a compiled WebAssembly.Module and its first WebAssembly.Instance. The secondary overload takes an already-compiled WebAssembly.Module and returns a Promise that resolves to an Instance of that Module. This overload is useful if the Module has already been compiled. Important: This method is not the most efficient way of fetching and instantiating wasm modules. ...
...WebAssembly.Instance. The secondary overload takes an already-compiled WebAssembly.Module and returns a Promise that resolves to an Instance of that Module. This overload is useful if the Module has already been compiled. Important: This method is not the most efficient way of fetching and instantiating wasm modules. If at all possible, you should use the newer WebAssembly.instantiateStreaming
() method instead, which fetches, compiles, and instantiates a module all in one step, directly from the raw bytecode, so doesn't require conversion to an ArrayBuffer. Syntax Primary overload -- taking wasm binary code Promise<ResultObject> WebAssembly.instantiate(bufferSource, importObject); Parameters bufferSource A typed array or ArrayBuffer containing the binary code of the .wasm modul...
... functions or WebAssembly.Memory objects. There must be one matching property for each declared import of the compiled module or else a WebAssembly.LinkError is thrown. Return value A Promise that resolves to a ResultObject which contains two fields: module: A WebAssembly.Module object representing the compiled WebAssembly module. This Module can be instantiated again, shared via postMessage
() or cached in IndexedDB. instance: A WebAssembly.Instance object that contains all the Exported WebAssembly functions. Exceptions If either of the parameters are not of the correct type or structure, a TypeError is thrown. If the operation fails, the promise rejects with a WebAssembly.CompileError, WebAssembly.LinkError, or WebAssembly.RuntimeError, depending on the cause of the failure. ...
...And 6 more matches
AudioContext.createMediaStreamTrackSource() - Web APIs
The createMediaStreamTrackSource
() method of the AudioContext interface creates and returns a MediaStreamTrackAudioSourceNode which represents an audio source whose data comes from the specified MediaStreamTrack. This differs from createMediaStreamSource
(), which creates a MediaStreamAudioSourceNode whose audio comes from the audio track in a specified MediaStream whose id is first, lexicographically (alphabetically). Syntax var audioCtx = new AudioContext
(); var track = audioCtx.createMediaStreamTrackSource(track); Parameters track The MediaStreamTrack to use as the source of all audio data for the new node. Return value A MediaStreamTrackAudioSourceNode object which acts as a source for audio data found in the specified audio track. ...
...phically (alphabetically). Syntax var audioCtx = new AudioContext
(); var track = audioCtx.createMediaStreamTrackSource(track); Parameters track The MediaStreamTrack to use as the source of all audio data for the new node. Return value A MediaStreamTrackAudioSourceNode object which acts as a source for audio data found in the specified audio track. Example In this example, getUserMedia
() is used to request access to the user's microphone. Once that access is attained, an audio context is established and a MediaStreamTrackAudioSourceNode is created using createMediaStreamTrackSource
(), taking its audio from the first audio track in the stream returned by getUserMedia
(). ...
...The output from the microphone is then routed into the new biquad filter, and the filter's output is in turn routed to the audio context's destination. ...
...And 5 more matches
AudioParam.cancelAndHoldAtTime() - Web APIs
Working Draft Initial definition. ...
...aram = AudioParam.cancelAndHoldAtTime(cancelTime) Parameters cancelTime A double representing the time (in seconds) after the AudioContext was first created after which all scheduled changes will be cancelled. Return value A reference to the AudioParam it was called on. Specifications Specification Status Comment Web Audio APIThe definition of 'cancelAndHoldAtTime
()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for...
...nternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetcancelAndHoldAtTimeChrome Full support 57 Full support 57 No support ? -- 56Alternate Name Alternate Name Uses the non-standard name: cancelValuesAndHoldAtTime
()Edge Full support <=79Firefox No support NoIE No support NoOpera Full support 44 Full support 44 No support ? -- 43Alternate Name Alternate Name Uses...
...And 5 more matches
BaseAudioContext.createBiquadFilter() - Web APIs
The createBiquadFilter
() method of the BaseAudioContext interface creates a BiquadFilterNode, which represents a second order filter configurable as several different common filter types. Syntax baseAudioContext.createBiquadFilter
(); Returns A BiquadFilterNode. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
...able as several different common filter types. Syntax baseAudioContext.createBiquadFilter
(); Returns A BiquadFilterNode. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
...ns A BiquadFilterNode. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
...And 5 more matches
BaseAudioContext.createBuffer() - Web APIs
The createBuffer
() method of the BaseAudioContext Interface is used to create a new, empty AudioBuffer object, which can then be populated by data, and played via an AudioBufferSourceNode For more details about audio buffers, check out the AudioBuffer reference page. Note: createBuffer
() used to be able to take compressed data and give back decoded samples, but this ability was removed from the spec, because all the decoding was done on the main thread, therefore createBuffer
() was blocking other code execution. The asynchronous method decodeAudioData
() does the same thing -- takes compressed audio, say, an MP3 file, and directly gives you back an AudioBuffer that you can then set to play via in an AudioBufferSourceNode. ...
...moved from the spec, because all the decoding was done on the main thread, therefore createBuffer
() was blocking other code execution. The asynchronous method decodeAudioData
() does the same thing -- takes compressed audio, say, an MP3 file, and directly gives you back an AudioBuffer that you can then set to play via in an AudioBufferSourceNode. For simple uses like playing an MP3, decodeAudioData
() is what you should be using. Syntax var buffer = baseAudioContext.createBuffer(numOfchannels, length, sampleRate); Parameters Note: For an in-depth explanation of how audio buffers work, and what these parameters mean, read Audio buffers: frames, samples and channels from our Basic concepts guide. numOfChannels An integer representing the number of channels this buffer should have. The...
... NotSupportedError One or more of the options are negative or otherwise has an invalid value (such as numberOfChannels being higher than supported, or a sampleRate outside the nominal range). RangeError There isn't enough memory available to allocate the buffer. ...
...And 5 more matches
Body.arrayBuffer() - Web APIs
The arrayBuffer
() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer. Syntax response.arrayBuffer
().then(function(buffer) { // do something with buffer }); Parameters None. Return value A promise that resolves with an ArrayBuffer. Examples Playing music In our fetch array buffer live, we have a Play button. When pressed, the getData
() function is run. Note that before playing full audio file will be downloaded. If you need to play ogg during downloading (stream it) - consider HTMLAudioElement: new Audio("music.ogg").play
(); In getData
() we create a new request using the Request
() constructor, then use it to fetch an OGG music track. We also use AudioContext.createBufferSource to create an audio bu...
...d. If you need to play ogg during downloading (stream it) - consider HTMLAudioElement: new Audio("music.ogg").play
(); In getData
() we create a new request using the Request
() constructor, then use it to fetch an OGG music track. We also use AudioContext.createBufferSource to create an audio buffer source. When the fetch is successful, we read an ArrayBuffer out of the response using arrayBuffer
(), decode the audio data using AudioContext.decodeAudioData, set the decoded data as the audio buffer source's buffer (source.buffer), then connect the source up to the AudioContext.destination. ...
...ch an OGG music track. We also use AudioContext.createBufferSource to create an audio buffer source. When the fetch is successful, we read an ArrayBuffer out of the response using arrayBuffer
(), decode the audio data using AudioContext.decodeAudioData, set the decoded data as the audio buffer source's buffer (source.buffer), then connect the source up to the AudioContext.destination. ...
...And 5 more matches
Cache.put() - Web APIs
Note: Cache.add/Cache.addAll do not cache responses with Response.status values that are not in the 200 range, whereas Cache.put lets you store any request/response pair. ...
... Note: Cache.add/Cache.addAll do not cache responses with Response.status values that are not in the 200 range, whereas Cache.put lets you store any request/response pair. ...
... Note: Cache.add/Cache.addAll do not cache responses with Response.status values that are not in the 200 range, whereas Cache.put lets you store any request/response pair. ...
...And 5 more matches
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
The CanvasRenderingContext2D.scrollPathIntoView
() method of the Canvas 2D API scrolls the current or given path into view. It is similar to Element.scrollIntoView
(). Syntax void ctx.scrollPathIntoView
(); void ctx.scrollPathIntoView(path); Parameters path A Path2D path to use. Examples Using the scrollPathIntoView method This example demonstrates the scrollPathIntoView
() method. ...
...nt.scrollIntoView
(). Syntax void ctx.scrollPathIntoView
(); void ctx.scrollPathIntoView(path); Parameters path A Path2D path to use. Examples Using the scrollPathIntoView method This example demonstrates the scrollPathIntoView
() method. ...
...w
(); void ctx.scrollPathIntoView(path); Parameters path A Path2D path to use. Examples Using the scrollPathIntoView method This example demonstrates the scrollPathIntoView
() method. ...
...And 5 more matches
FileReader.readAsDataURL() - Web APIs
te: The blob's result cannot be directly decoded as Base64 without first removing the Data-URL declaration preceding the Base64-encoded data. To retrieve only the Base64 encoded string, first remove data:*/*;base64, from the result. Syntax instanceOfFileReader.readAsDataURL(blob); Parameters blob The Blob or File from which to read. ...
...URL declaration preceding the Base64-encoded data. To retrieve only the Base64 encoded string, first remove data:*/*;base64, from the result. Syntax instanceOfFileReader.readAsDataURL(blob); Parameters blob The Blob or File from which to read. ...
...nstanceOfFileReader.readAsDataURL(blob); Parameters blob The Blob or File from which to read. ...
...And 5 more matches
HTMLCanvasElement.mozGetAsFile() - Web APIs
Syntax canvas.mozGetAsFile(name, type); Parameters name A DOMString indicating the file name to give the file representing the image file in memory. type Optional A DOMString which specifies the image file format to use when creating the new image file. The default type is image/png. For other options, see our Image file type and format guide. Return value A File object representing the image contained in the canvas. The file's data is entirely located in memory until such time as it is explicitly written to disk. ...
...e image contained in the canvas. The file's data is entirely located in memory until such time as it is explicitly written to disk. Examples This example creates an image file from the <canvas> element on the page, then uses a FileReader to read the image data from the file. ...
...located in memory until such time as it is explicitly written to disk. Examples This example creates an image file from the <canvas> element on the page, then uses a FileReader to read the image data from the file. ...
...And 5 more matches
HTMLCanvasElement.toBlob() - Web APIs
If type is not specified, the image type is image/png. The created image is in a resolution of 96dpi. The third argument is used when creating images using lossy compression (namely, image/jpeg) to specify the quality of the output. Syntax canvas.toBlob(callback, mimeType, qualityArgument); Parameters callback A callback function with the resulting Blob object as a single argument. mimeType Optional A DOMString indicating the image format. The default type is image/png. ...
..., takes the image in the <canvas> element whose ID is "canvas", obtains a copy of it as a PNG image, then appends a new <img> element to the document, whose source image is the one created using the canvas. var canvas = document.getElementById('canvas'); canvas.toBlob(function(blob) { var newImg = document.createElement('img'), url = URL.createObjectURL(blob); newImg.onload = function
() { // no longer need to read the blob so it's revoked URL.revokeObjectURL(url); }; newImg.src = url; document.body.appendChild(newImg); }); Note that here we're creating a PNG image; if you add a second parameter to the toBlob
() call, you can specify the image type. For example, to get the image in JPEG format: canvas.toBlob(function(blob){...}, 'image/jpeg', 0.95); // JPEG at 9...
...Mozilla only) This uses -moz-parse to convert the canvas to ico. Windows XP doesn't support converting from PNG to ico, so it uses bmp instead. A download link is created by setting the download attribute. The value of the download attribute is the name it will use as the file name. ...
...And 5 more matches
HTMLElement.blur() - Web APIs
Living Standard HTML 5.1The definition of 'blur' in that specification. ...
... Living Standard HTML 5.1The definition of 'blur' in that specification. ...
... Living Standard HTML 5.1The definition of 'blur' in that specification. ...
...And 5 more matches
HTMLElement.focus() - Web APIs
The focused element is the element which will receive keyboard and similar events by default. Syntax element.focus(options); // Object parameter Parameters options Optional An optional object providing options to control aspects of the focusing process. This object may contain the following property: preventScroll Optional A Boolean value indicating whether or not the browser should scroll the document to bring the newly-focused element into view. A value of false for preventScroll (the default) means that the browser will scroll the element into view after focusing it. If preventScroll is set to true, no scrolling will occur. ...
...ional A Boolean value indicating whether or not the browser should scroll the document to bring the newly-focused element into view. A value of false for preventScroll (the default) means that the browser will scroll the element into view after focusing it. If preventScroll is set to true, no scrolling will occur. ...
... should scroll the document to bring the newly-focused element into view. A value of false for preventScroll (the default) means that the browser will scroll the element into view after focusing it. If preventScroll is set to true, no scrolling will occur. ...
...And 5 more matches
IDBObjectStore.delete() - Web APIs
Note: This feature is available in Web Workers. Syntax var request = objectStore.delete(Key); var request = objectStore.delete(KeyRange); Parameters Key The key of the record to be deleted, or an IDBKeyRange to delete all records with keys in range. ...
... Note: This feature is available in Web Workers. Syntax var request = objectStore.delete(Key); var request = objectStore.delete(KeyRange); Parameters Key The key of the record to be deleted, or an IDBKeyRange to delete all records with keys in range. ...
...nsaction is inactive. ReadOnlyError The object store's transaction mode is read-only. InvalidStateError The object store has been deleted. DataError The key is not a valid key or a key range. Example In the following code snippet, we open a read/write transaction on our database and delete one specific record out of our object store using delete
() -- a sample record with the key "Walk dog". For a full working example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. This is used a lot be...
...And 5 more matches
IDBObjectStore.get() - Web APIs
That method provides a cursor if the record exists, and no cursor if it does not. Note: This feature is available in Web Workers. ...
...d by the specified key. This is for retrieving specific records from an object store. If a value is successfully found, then a structured clone of it is created and set as the result of the request object. Note: This method produces the same result for: a) a record that doesn't exist in the database and b) a record that has an undefined value. To tell these situations apart, call the openCursor
() method with the same key. That method provides a cursor if the record exists, and no cursor if it does not. Note: This feature is available in Web Workers. Syntax var request = objectStore.get(key); Parameters key The key or key range that identifies the record to be retrieved. Return value An IDBRequest object on which subsequent events related to this operation are fired. Exceptions...
... TransactionInactiveError This IDBObjectStore's transaction is inactive. DataError The key or key range provided contains an invalid key. InvalidStateError The IDBObjectStore has been deleted or removed. Example In the following code snippet, we open a read/write transaction on our database and get one specific record from object store using get
() -- a sample record with the key "Walk dog". Once this data object is retrieved, you could then update it using normal JavaScript, then put it back into the database using a IDBObjectStore.put operation. For a full working example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = ...
...And 5 more matches
IDBObjectStore.put() - Web APIs
It returns an IDBRequest object, and, in a separate thread, creates a structured clone of the value and stores the cloned value in the object store. This is for adding new records, or updating existing records in an object store when the transaction's mode is readwrite. If the record is successfully stored, then a success event is fired on the returned request object with the result set to the key for the stored record, and the transaction set to the transaction in which this object store is opened. The put method is an update or insert method. See the IDBObjectStore.add method for an insert only method. ...
...event is fired on the returned request object with the result set to the key for the stored record, and the transaction set to the transaction in which this object store is opened. The put method is an update or insert method. See the IDBObjectStore.add method for an insert only method. Bear in mind that if you have a IDBCursor to the record you want to update, updating it with IDBCursor.update
() is preferable to using IDBObjectStore.put
(). Doing so makes it clear that an existing record will be updated, instead of a new record being inserted. Note: This feature is available in Web Workers. Syntax let request = objectStore.put(item); let request = objectStore.put(item, key); Parameters item The item you wish to update (or insert). key Optional The primary key of the record you w...
... of the object must be passed in to update the object. Example The following example requests a given record title; when that request is successful the onsuccess function gets the associated record from the IDBObjectStore (made available as objectStoreTitleRequest.result), updates one property of the record, and then puts the updated record back into the object store in another request with put
(). ...
...And 5 more matches
IDBTransaction.abort() - Web APIs
Example In the following code snippet, we open a read/write transaction on our database and add some data to an object store. ...
... Example In the following code snippet, we open a read/write transaction on our database and add some data to an object store. ...
... been committed or aborted. Example In the following code snippet, we open a read/write transaction on our database and add some data to an object store. Note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. At the end, we simply abort any activity done under the current transaction using abort
(). For a full working example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. This is used a lot below db = DBOpenRequest.result; // Run ...
...And 5 more matches
OfflineAudioContext.startRendering() - Web APIs
The startRendering
() method of the OfflineAudioContext Interface starts rendering the audio graph, taking into account the current connections and the current scheduled changes. The complete event (of type OfflineAudioCompletionEvent) is raised when the rendering is finished, containing the resulting AudioBuffer in its renderedBuffer property. Browsers currently support two versions of the startRendering
() method -- an older event-based version and a newer promise-based version. The former will eventually be removed, but currently both mechanisms are provided for legacy reasons. ...
...the rendering is finished, containing the resulting AudioBuffer in its renderedBuffer property. Browsers currently support two versions of the startRendering
() method -- an older event-based version and a newer promise-based version. The former will eventually be removed, but currently both mechanisms are provided for legacy reasons. Syntax Event-based version: offlineAudioCtx.startRendering
(); offlineAudioCtx.oncomplete = function(e) { // e.renderedBuffer contains the output buffer } Promise-based version: offlineAudioCtx.startRendering
().then(function(buffer) { // buffer contains the output buffer }); Parameters None. Returns Void. Example In this simple example, we declare both an AudioContext and an OfflineAudioContext object. We use the AudioContext to load an audio t...
...re both an AudioContext and an OfflineAudioContext object. We use the AudioContext to load an audio track via XHR (AudioContext.decodeAudioData), then the OfflineAudioContext to render the audio into an AudioBufferSourceNode and play the track through. After the offline audio graph is set up, you need to render it to an AudioBuffer using OfflineAudioContext.startRendering. When the startRendering
() promise resolves, rendering has completed and the output AudioBuffer is returned out of the promise. At this point we create another audio context, create an AudioBufferSourceNode inside it, and set its buffer to be equal to the promise AudioBuffer. This is then played as part of a simple standard audio graph. Note: For a working example, see our offline-audio-context-promise Github repo (see ...
...And 5 more matches
PannerNode.setOrientation() - Web APIs
The setOrientation
() method of the PannerNode Interface defines the direction the audio source is playing in. This can have a big effect if the sound is very directional -- controlled by the three cone-related attributes PannerNode.coneInnerAngle, PannerNode.coneOuterAngle, and PannerNode.coneOuterGain. In such a case, a sound pointing away from the listener can be very quiet or even silent. The three parameters x, y and z are unitless and describe a direction vector in 3D space using the right-hand Cartesian coordinate system. The default value of the direction vector is (1, 0, 0). Syntax var audioCtx = new AudioContext
(); var panner = audioCtx.createPanner
(); panner.setOrientation(1,0,0); Returns Void. Example In the following example, you can see an example of how the createPan...
...ree parameters x, y and z are unitless and describe a direction vector in 3D space using the right-hand Cartesian coordinate system. The default value of the direction vector is (1, 0, 0). Syntax var audioCtx = new AudioContext
(); var panner = audioCtx.createPanner
(); panner.setOrientation(1,0,0); Returns Void. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realist...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...And 5 more matches
PaymentRequest.canMakePayment() - Web APIs
The PaymentRequest method canMakePayment
() determines whether or not the request is configured in a way that is compatible with at least one payment method supported by the user agent. You can call this before calling show
() to provide a streamlined user experience when the user's browser can't handle any of the payment methods you accept. For instance, you might call canMakePayment
() to determine if the browser will let the user pay using Payment Request API, and if it won't, you could fall back to another payment method, or offer a list of methods that aren't handled by Payment Request API (or even provide instructions for paying by mail or by phone). Syntax paymentRequest.canMakePayment
() .then( canPay => { ... }) .catch( error => { ... }) canPay = await paymentRequest.canM...
...browser will let the user pay using Payment Request API, and if it won't, you could fall back to another payment method, or offer a list of methods that aren't handled by Payment Request API (or even provide instructions for paying by mail or by phone). Syntax paymentRequest.canMakePayment
() .then( canPay => { ... }) .catch( error => { ... }) canPay = await paymentRequest.canMakePayment
(); Returns A Promise to a Boolean that resolves to true if the user agent supports any of the payment methods supplied when instantiating the request using the PaymentRequest constructor. If the payment can't be processed, the promise receives a value of false. Note: If you call this too often, the browser may reject the returned promise with a DOMException. Parameters None Examples In th...
...Request constructor. If the payment can't be processed, the promise receives a value of false. Note: If you call this too often, the browser may reject the returned promise with a DOMException. Parameters None Examples In the following example, is excerpted from a demo that asynchronously builds a PaymentRequest object for both Apple Pay and credit cards. ...
...And 5 more matches
performance.getEntriesByName() - Web APIs
Note: This feature is available in Web Workers. Syntax entries = window.performance.getEntriesByName(name, type); Arguments name The name of the entry to retrieve. type Optional The type of entry to retrieve such as "mark". The valid entry types are listed in PerformanceEntry.entryType. Return value entries A list of PerformanceEntry objects that have the specified name and type. If the type argument is not specified, only the name will be used to determine the entries to return. ...
...ype. Return value entries A list of PerformanceEntry objects that have the specified name and type. If the type argument is not specified, only the name will be used to determine the entries to return. The items will be in chronological order based on the entries' startTime. If no objects meet the specified criteria, an empty list is returned. ...
... to return. The items will be in chronological order based on the entries' startTime. If no objects meet the specified criteria, an empty list is returned. Example function use_PerformanceEntry_methods
() { log("PerformanceEntry tests ..."); if (performance.mark === undefined) { log("... ...
...And 5 more matches
performance.getEntriesByType() - Web APIs
The getEntriesByType
() method returns a list of PerformanceEntry objects for a given type. The list's members (entries) can be created by making performance marks or measures (for example by calling the mark
() method) at explicit points in time. Note: This feature is available in Web Workers. Syntax entries = window.performance.getEntriesByType(type); Arguments type The type of entry to retrieve such as "mark". The valid entry types are listed in PerformanceEntry.entryType. Return value entries A list of PerformanceEntry objects that have the specified type. The items will be in chronological order based on the entries' startTime. If no objects have the specified type, or no argument is provided, an empty list is returned. ...
...o retrieve such as "mark". The valid entry types are listed in PerformanceEntry.entryType. Return value entries A list of PerformanceEntry objects that have the specified type. The items will be in chronological order based on the entries' startTime. If no objects have the specified type, or no argument is provided, an empty list is returned. ...
...l be in chronological order based on the entries' startTime. If no objects have the specified type, or no argument is provided, an empty list is returned. Example function usePerformanceEntryMethods
() { log("PerformanceEntry tests ..."); if (performance.mark === undefined) { log("... ...
...And 5 more matches
performance.mark() - Web APIs
// Create a bunch of marks. ...
... // Create a bunch of marks. ...
... // Create a bunch of marks. ...
...And 5 more matches
ReadableStream.ReadableStream() - Web APIs
Syntax var readableStream = new ReadableStream(underlyingSource[, queuingStrategy]); Parameters underlyingSource An object containing methods and properties that define how the constructed stream instance will behave. underlyingSource can contain the following: start(controller) This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream fuctionality. If this process is to be done asynchronously, it can return a promise to signal success or failure. ...
... method is a ReadableStreamDefaultController or a ReadableByteStreamController, depending on the value of the type property. This can be used by the developer to control the stream during set up. pull(controller) Optional This method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. If pull
() returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. The controller parameter passed to this method is a ReadableStreamDefaultController or a ReadableByteStreamController, depending on the value of the type property. This can be used by the developer to control the stream as more chunks are fetched. cancel(reason) ...
...meter passed to this method is a ReadableStreamDefaultController or a ReadableByteStreamController, depending on the value of the type property. This can be used by the developer to control the stream as more chunks are fetched. cancel(reason) Optional This method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if ReadableStream.cancel
() is called). The contents should do whatever is necessary to release access to the stream source. If this process is asynchronous, it can return a promise to signal success or failure. The reason parameter contains a DOMString describing why the stream was cancelled. type Optional This property controls what type of readable stream is being dealt with. If it is included with a value set to "by...
...And 5 more matches
ReadableStreamDefaultReader.read() - Web APIs
Return value A Promise, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: If a chunk is available, the promise will be fulfilled with an object of the form { value: theChunk, done: false }. If the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. If the stream becomes errored, the promise will be rejected with the relevant error. ...
... object is not a ReadableStreamDefaultReader, or the stream has no owner. Examples Example 1 - simple example This example shows the basic API usage, but doesn't try to deal with complications like stream chunks not ending on line boundaries for example. In this example stream is a previously-created custom ReadableStream. It is read using a ReadableStreamDefaultReader created using getReader
(). ...
...adableStream. It is read using a ReadableStreamDefaultReader created using getReader
(). (see our Simple random stream example for the full code). Each chunk is read sequentially and output to the UI as an array of UTF-8 bytes, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the UI. function fetchStream
() { const reader = stream.getReader
(); let charsReceived = 0; // read
() returns a promise that resolves // when a value has been received reader.read
().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) {...
...And 5 more matches
TextEncoder.prototype.encodeInto() - Web APIs
Syntax b1 = encoder.encodeInto(string, uint8Array); Parameters string Is a USVString containing the text to encode. uint8Array Is a Uint8Array object instance to place the resulting UTF-8 encoded text into. Return value A TextEncoderEncodeIntoResult dictionary, which contains two members: read The number of UTF-16 units of code from the source that has been converted over to UTF-8. ...
...y did not have enough space. written The number of bytes modified in the destination Uint8Array. The bytes written are guaranteed to form complete UTF-8 byte sequences. Encode Into A Specific Position encoder.encodeInto always puts its output at the start of the array. However, it is sometimes useful to make the output start at a particular index. The solution is TypedArray.prototype.subarray
(). ...
...ful to make the output start at a particular index. The solution is TypedArray.prototype.subarray
(). Observe. var encoder = new TextEncoder; function encodeIntoAtPosition(string, u8array, position) { return encoder.encodeInto(string, position ? u8array.subarray(position|0) : u8array); } var u8array = new Uint8Array(8); encodeIntoAtPosition("hello", u8array, 2); console.log( "" + u8array.join
() ); // 0,0,104,101,108,108,111,0 Buffer Sizing To convert a JavaScript string s, the output space needed for full conversion is never less than s.length bytes and never greater than s.length * 3 bytes. If the output allocation (typically within Wasm heap) is expected to be short-lived, it makes sense to simply allocate s.length * 3 bytes for the output, in which case the first conversion attemp...
...And 5 more matches
WebGLRenderingContext.makeXRCompatible() - Web APIs
Return value A Promise which successfully resolves once the WebGL context is ready to be used for rendering WebXR content. ...
...WebXR device on which it will be displayed. If necessary, the WebGL layer may reconfigure the context to be ready to render to a different device than it originally was. This is useful if you have an application which can start out being presented on a standard 2D display but can then be transitioned to a 3D immersion system. Syntax let makeCompatPromise = webGLRenderingContext.makeXRCompatible
(); Parameters None. Return value A Promise which successfully resolves once the WebGL context is ready to be used for rendering WebXR content. Exceptions This method doesn't throw traditional exceptions; instead, the promise rejects with one of the following errors as the value passed into the rejection handler: AbortError Switching the context over to the WebXR-compatible context failed.
...WebXR content. Exceptions This method doesn't throw traditional exceptions; instead, the promise rejects with one of the following errors as the value passed into the rejection handler: AbortError Switching the context over to the WebXR-compatible context failed. InvalidStateError The WebGL context has been lost or there is no available WebXR device. Usage notes Because makeXRCompatible
() may involve replacing the underlying WebGL context with a new one that uses the new rendering hardware, the existing contents of the context may be lost and, therefore, would need to be re-rendered. This is why the webglcontextlost and webglcontextrestored events are used: the first gives you the opportunity to discard anything you won't need anymore, while the second gives you the opportunity to...
...And 5 more matches
WindowOrWorkerGlobalScope.fetch() - Web APIs
The fetch
() method of the WindowOrWorkerGlobalScope mixin starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the Response object representing the response to your request. The promise does not reject on HTTP errors -- it only rejects on network errors. You must use then handlers to check for HTTP errors. 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). ...
...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 properties. The fetch
() method is controlled by the connect-src directive of Content Security Policy rather than the directive of the resources it's retrieving. Note: The fetch
() method's parameters are identical to those of the Request
() constructor. Syntax const ...
...origin, origin, strict-origin, origin-when-cross-origin, strict-origin-when-cross-origin, or unsafe-url. integrity Contains the subresource integrity value of the request (e.g., sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=). keepalive The keepalive option can be used to allow the request to outlive the page. Fetch with the keepalive flag is a replacement for the Navigator.sendBeacon
() API. signal An AbortSignal object instance; allows you to communicate with a fetch request and abort it if desired via an AbortController. Return value A Promise that resolves to a Response object. Exceptions AbortError The request was aborted due to a call to the AbortController method abort
() method. TypeError The specified URL string includes user credentials. This informatio...
...And 5 more matches
XMLHttpRequest.send() - Web APIs
Syntax XMLHttpRequest.send(body) Parameters body Optional A body of data to be sent in the XHR request. ...
... Syntax XMLHttpRequest.send(body) Parameters body Optional A body of data to be sent in the XHR request. ...
... Syntax XMLHttpRequest.send(body) Parameters body Optional A body of data to be sent in the XHR request. This can be: A Document, in which case it is serialized before being sent. ...
...And 5 more matches
Array.prototype.sort() - JavaScript
The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. 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 arr.sort([compareFunction]) Parameters compareFunction Optional Specifies a function that defines the sort order. ...
...alue of one of their properties. var items = [ { name: 'Edward', value: 21 }, { name: 'Sharpe', value: 37 }, { name: 'And', value: 45 }, { name: 'The', value: -12 }, { name: 'Magnetic', value: 13 }, { name: 'Zeros', value: 37 } ]; // sort by value items.sort(function (a, b) { return a.value - b.value; }); // sort by name items.sort(function(a, b) { var nameA = a.name.toUpperCase
(); // ignore upper and lowercase var nameB = b.name.toUpperCase
(); // ignore upper and lowercase if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } // names must be equal return 0; }); Examples Creating, displaying, and sorting an array The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are ...
...l array, then the sorted arrays. The numeric arrays are sorted without a compare function, then sorted using one. ...
...And 5 more matches
Date.parse() - JavaScript
2015-02-31). It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated). 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. ...
... a simplification of the ISO 8601 calendar date extended format. (Other formats may be used, but results are implementation-dependent.) Return value A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, NaN is returned. Description The parse
() method takes a date string (such as "2011-10-10T14:48:00") and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the setTime
() method and the Date object. Date Time String Format The standard string representation of a date time string is a simplification of the ISO 860...
...e parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time. While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or NaN. Because parse
() is a static method of Date, it is called as Date.parse
() rather than as a method of a Date instance. Fall-back to implementation-specific date formats This section contains implementation-specific behavior that can be inconsistent across implementations. The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation...
...And 5 more matches
Date.prototype.toLocaleString() - JavaScript
The new locales and options arguments let applications specify the language whose formatting conventions should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation-dependent. 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. ...
...bj.toLocaleString([locales[, options]]) Parameters The locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. See the Intl.DateTimeFormat
() constructor for details on these parameters and how to use them. The default value for each date-time component property is undefined. But, if the weekday, year, month, and day properties are all undefined, then year, month, and day are assumed to be "numeric". Return value A string representing the given date according to language-specific conventions. Performance When formatting large num...
...ay, year, month, and day properties are all undefined, then year, month, and day are assumed to be "numeric". Return value A string representing the given date according to language-specific conventions. Performance When formatting large numbers of dates, it is better to create an Intl.DateTimeFormat object and use the function provided by its format property. ...
...And 5 more matches
Math.hypot() - JavaScript
If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.hypot([value1[, value2[, ...]]]) Parameters value1, value2, ... Numbers. Return value The square root of the sum of squares of the given arguments. If at least one of the arguments cannot be converted to a number, NaN is returned. ...
... or Math.hypot(v1, v2, v3, v4, ...). Math.hypot also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is Number.MAX_VALUE, which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity . If you use hypot
() instead, you get better answer: Math.hypot(1e200, 1e200) = 1.4142...e+200 . This is also true with very small numbers. Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0, but Math.hypot(1e-200, 1e-200) =1.4142...e-200. Because hypot
() is a static method of Math, you always use it as Math.hypot
(), rather than as a method of a Math object you created (Math is not a constructor). If no arguments are gi...
...), rather than as a method of a Math object you created (Math is not a constructor). If no arguments are given, the result is +0. If any of the arguments is +-Infinity, the result is Infinity. If any of the arguments is NaN (unless another argument is +-Infinity), the result is NaN. If at least one of the arguments cannot be converted to a number, the result is NaN. ...
...And 5 more matches
Object.freeze() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Object.freeze(obj) Parameters obj The object to freeze. ...
...ect. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. In addition, freezing an object also prevents its prototype from being changed. freeze
() returns the same object that was passed in. 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 Object.freeze(obj) Parameters obj The object to freeze. Return value The object that was passed to the function...
...d configurable attributes are set to false. Accessor properties (getters and setters) work the same (and still give the illusion that you are changing the value). Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. freeze
() returns the same object that was passed into the function. It does not create a frozen copy. In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. In ES2015, a non-object argument will be treated as if it were a frozen ordinary object, and be simply returned. > Object.freeze(1) TypeError: 1 is not an object // ES5 code > Object.freeze(1) 1 ...
...And 5 more matches
Object.getOwnPropertyNames() - JavaScript
The Object.getOwnPropertyNames
() method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object. Syntax Object.getOwnPropertyNames(obj) Parameters obj The object whose enumerable and non-enumerable properties are to be returned. Return value An array of strings that corresponds to the properties found directly in the given object. Description Object.getOwnPropertyNames
() returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object obj. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a for...in loop (or by Object.keys
()) over the properties of the object. The ordering o...
...operties is not defined. In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. In ES2015, a non-object argument will be coerced to an object. Object.getOwnPropertyNames('foo'); // TypeError: "foo" is not an object (ES5 code) Object.getOwnPropertyNames('foo'); // ["0", "1", "2", "length"] (ES2015 code) Examples Using Object.getOwnPropertyNames
() var arr = ['a', 'b', 'c']; console.log(Object.getOwnPropertyNames(arr).sort
()); // .sort
() is an array method. // logs ["0", "1", "2", "length"] // Array-like object var obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(Object.getOwnPropertyNames(obj).sort
()); // .sort
() is an array method. // logs ["0", "1", "2"] // Logging property names and values using Array.forEach Object.getOwnPropertyNames(...
...t.getOwnPropertyNames(obj).sort
()); // .sort
() is an array method. // logs ["0", "1", "2"] // Logging property names and values using Array.forEach Object.getOwnPropertyNames(obj).forEach( function (val, idx, array) { console.log(val + ' -> ' + obj[val]); } ); // logs // 0 -> a // 1 -> b // 2 -> c // non-enumerable property var my_obj = Object.create({}, { getFoo: { value: function
() { return this.foo; }, enumerable: false } }); my_obj.foo = 1; console.log(Object.getOwnPropertyNames(my_obj).sort
()); // logs ["foo", "getFoo"] If you want only the enumerable properties, see Object.keys
() or use a for...in loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with hasOwnProperty
()). Item...
...And 5 more matches
Object.setPrototypeOf() - JavaScript
Warning: Changing the [[Prototype]] of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in the Object.setPrototypeOf(...) statement, but may extend to any code that has access to any object whose [[Prototype]] has been altered. Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). ...
...hose [[Prototype]] has been altered. Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the [[Prototype]] of an object. Instead, create a new object with the desired [[Prototype]] using Object.create
(). Syntax Object.setPrototypeOf(obj, prototype) Parameters obj The object which is to have its prototype set. prototype The object's new prototype (an object or null). Return value The specified object. Description Throws a TypeError exception if the object whose [[Prototype]] is to be modified is non-extensible according to Object.isExtensible
(). Does nothing if the prototype parame...
...ull). Return value The specified object. Description Throws a TypeError exception if the object whose [[Prototype]] is to be modified is non-extensible according to Object.isExtensible
(). Does nothing if the prototype parameter isn't an object or null (i.e., number, string, boolean, or undefined). Otherwise, this method changes the [[Prototype]] of obj to the new value. Object.setPrototypeOf
() is in the ECMAScript 2015 specification. It is generally considered the proper way to set the prototype of an object, vs. the more controversial Object.prototype.__proto__ property. ...
...And 5 more matches
Object.prototype.toSource() - JavaScript
The toSource
() method returns a string representing the source code of the object. Syntax Object.toSource
(); obj.toSource
(); Return value A string representing the source code of the object. Description The toSource
() method returns the following values: For the built-in Object object, toSource
() returns the following string indicating that the source code is not available: function Object
() { [native code] } For instances of Object, toSource
() returns a string representing the source code. You can call toSource
() while debugging to examine the contents of an object. Overriding the toSource
() method It is safe for objects to override the toSource
() method. For example: function Person(name) { this.name = name; } Person.prototype.toSource = function Per...
...ct
() { [native code] } For instances of Object, toSource
() returns a string representing the source code. You can call toSource
() while debugging to examine the contents of an object. Overriding the toSource
() method It is safe for objects to override the toSource
() method. For example: function Person(name) { this.name = name; } Person.prototype.toSource = function Person_toSource
() { return 'new Person(' + uneval(this.name) + ')'; }; console.log(new Person('Joe').toSource
()); // ---> new Person("Joe") Built-in toSource
() methods Each core JavaScript type has its own toSource
() method. These objects are: Array.prototype.toSource
() -- Array object. Boolean.prototype.toSource
() -- Boolean object. Date.prototype.toSource
() -- Date object. Function.prototype.toSou...
... return 'new Person(' + uneval(this.name) + ')'; }; console.log(new Person('Joe').toSource
()); // ---> new Person("Joe") Built-in toSource
() methods Each core JavaScript type has its own toSource
() method. These objects are: Array.prototype.toSource
() -- Array object. Boolean.prototype.toSource
() -- Boolean object. Date.prototype.toSource
() -- Date object. Function.prototype.toSource
() -- Function object. Number.prototype.toSource
() -- Number object. RegExp.prototype.toSource
() -- RegExp object. String.prototype.toSource
() -- String object. Symbol.prototype.toSource
() -- Symbol object. Math.toSource
() -- Returns the String "Math". Limitations on cyclical objects In the case of objects that contain references to themselves, e.g. a cyclically linked list or a tree th...
...And 5 more matches
RegExp.prototype.toString() - JavaScript
The toString
() method returns a string representing the regular expression. 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 regexObj.toString
(); Return value A string representing the given object. Description The RegExp object overrides the toString
() method of the Object object; it does not inherit Object.prototype.toString
(). For RegExp objects, the toString
() method returns a string representation of the regular expression. ...
.../mdn/interactive-examples and send us a pull request. Syntax regexObj.toString
(); Return value A string representing the given object. Description The RegExp object overrides the toString
() method of the Object object; it does not inherit Object.prototype.toString
(). For RegExp objects, the toString
() method returns a string representation of the regular expression. ...
...bject. Description The RegExp object overrides the toString
() method of the Object object; it does not inherit Object.prototype.toString
(). For RegExp objects, the toString
() method returns a string representation of the regular expression. ...
...And 5 more matches
String.prototype.replace() - JavaScript
The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. If pattern is a string, only the first occurrence will be replaced. The original string is left unchanged. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax const newStr = str.replace(regexp|substr, newSubstr|function) Parameters regexp (pattern) A RegExp object or literal. ...
... full match to be replaced if the regular expression in the first parameter is global. The arguments to the function are as follows: Possible name Supplied value match The matched substring. (Corresponds to $& above.) p1, p2, ... The nth string found by a parenthesized capture group (including named capturing groups), provided the first argument to replace
() was a RegExp object. (Corresponds to $1, $2, etc. above.) For example, if /(\a+)(\b+)/, was given, p1 is the match for \a+, and p2 for \b+. offset The offset of the matched substring within the whole string being examined. (For example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.) string The whole string being examined.
... let str = 'Twas the night before Xmas...'; let newstr = str.replace(/xmas/i, 'Christmas'); console.log(newstr); // Twas the night before Christmas... This logs 'Twas the night before Christmas...'. Note: See this guide for more explanations about regular expressions. Using global a...
...And 5 more matches
String.prototype.toLocaleUpperCase() - JavaScript
If multiple locales are given in an Array, the best available locale is used. The default locale is the host environment's current locale. ...
...If multiple locales are given in an Array, the best available locale is used. The default locale is the host environment's current locale. ...
...cale. Return value A new string representing the calling string converted to upper case, according to any locale-specific case mappings. Exceptions A RangeError ("invalid language tag: xx_yy") is thrown if a locale argument isn't a valid language tag. A TypeError ("invalid element in locales argument") is thrown if an array element isn't of type string. Description The toLocaleUpperCase
() method returns the value of the string converted to upper case according to any locale-specific case mappings. toLocaleUpperCase
() does not affect the value of the string itself. In most cases, this will produce the same result as toUpperCase
(), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. Also not...
...And 5 more matches
AnalyserNode.getByteFrequencyData() - Web APIs
The getByteFrequencyData
() method of the AnalyserNode interface copies the current frequency data into a Uint8Array (unsigned byte array) passed into it. The frequency data is composed of integers on a scale from 0 to 255. Each item in the array represents the decibel value for a specific frequency. The frequencies are spread linearly from 0 to 1/2 of the sample rate. For example, for 48000 sample rate, the last item of the array will represent the decibel value for 24000 Hz. 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. ...
...frequency. The frequencies are spread linearly from 0 to 1/2 of the sample rate. For example, for 48000 sample rate, the last item of the array will represent the decibel value for 24000 Hz. 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. Syntax var audioCtx = new AudioContext
(); var analyser = audioCtx.createAnalyser
(); var dataArray = new Uint8Array(analyser.frequencyBinCount); // Uint8Array should be the same length as the frequencyBinCount void analyser.getByteFrequencyData(dataArray); // fill the Uint8Array with data returned from getByteFrequencyData
() Parameters array The Uint8Array that the frequency domain data will be copied to. For any sample which is...
...e shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). ...
...And 4 more matches
AudioContext.close() - Web APIs
Closed contexts cannot have new nodes created, but can decode audio data, create buffers, etc. This function does not automatically release all AudioContext-created objects, unless other references have been released as well; however, it will forcibly release any system audio resources that might prevent additional AudioContexts from being created and used, suspend the progression of audio time in the audio context, and stop processing audio data. The returned Promise resolves when all AudioContext-creation-blocking resources have been released. This method throws an INVALID_STATE_ERR exception if called on an OfflineAudioContext. ...
...sources that might prevent additional AudioContexts from being created and used, suspend the progression of audio time in the audio context, and stop processing audio data. The returned Promise resolves when all AudioContext-creation-blocking resources have been released. This method throws an INVALID_STATE_ERR exception if called on an OfflineAudioContext. ...
... prevent additional AudioContexts from being created and used, suspend the progression of audio time in the audio context, and stop processing audio data. The returned Promise resolves when all AudioContext-creation-blocking resources have been released. This method throws an INVALID_STATE_ERR exception if called on an OfflineAudioContext. ...
...And 4 more matches
AudioContext.createMediaStreamDestination() - Web APIs
The createMediaStreamDestination
() method of the AudioContext Interface is used to create a new MediaStreamAudioDestinationNode object associated with a WebRTC MediaStream representing an audio stream, which may be stored in a local file or sent to another computer. The MediaStream is created when the node is created and is accessible via the MediaStreamAudioDestinationNode's stream attribute. This stream can be used in a similar way as a MediaStream obtained via navigator.getUserMedia -- it can, for example, be sent to a remote peer using the RTCPeerConnection addStream
() method. For more details about media stream destination nodes, check out the MediaStreamAudioDestinationNode reference page. ...
...ediaStreamAudioDestinationNode's stream attribute. This stream can be used in a similar way as a MediaStream obtained via navigator.getUserMedia -- it can, for example, be sent to a remote peer using the RTCPeerConnection addStream
() method. For more details about media stream destination nodes, check out the MediaStreamAudioDestinationNode reference page. Syntax var audioCtx = new AudioContext
(); var destination = audioCtx.createMediaStreamDestination
(); Returns A MediaStreamAudioDestinationNode. Examples In the following simple example, we create a MediaStreamAudioDestinationNode, an OscillatorNode and a MediaRecorder (the example will therefore only work in Firefox and Chrome at this time.) The MediaRecorder is set up to record information from the MediaStreamDestinationNode. When...
...e dataavailable event to fire, and the event data is pushed into the chunks array. After that, the stop event fires, a new blob is made of type opus -- which contains the data in the chunks array, and a new window (tab) is then opened that points to a URL created from the blob. From here, you can play and save the opus file. ...
...And 4 more matches
AudioListener.setOrientation() - Web APIs
The setOrientation
() method of the AudioListener interface defines the orientation of the listener. It consists of two direction vectors: The front vector, defined by the three unitless parameters x, y and z, describes the direction of the face of the listener, that is the direction the nose of the person is pointing towards. The front vector's default value is (0, 0, -1). The up vector, defined by three unitless parameters xUp, yUp and zUp, describes the direction of the top of the listener's head. The up vector's default value is (0, 1, 0). The two vectors must be separated by an angle of 90? -- in linear analysis terms, they must be perpendicular to each other. Syntax var audioCtx = new AudioContext
(); var myListener = audioCtx.listener; myListener.setOrientation(0,0,-1,0,1,...
...r's head. The up vector's default value is (0, 1, 0). The two vectors must be separated by an angle of 90? -- in linear analysis terms, they must be perpendicular to each other. Syntax var audioCtx = new AudioContext
(); var myListener = audioCtx.listener; myListener.setOrientation(0,0,-1,0,1,0); Returns Void. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realist...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...And 4 more matches
AudioListener.setPosition() - Web APIs
The setPosition
() method of the AudioListener Interface defines the position of the listener. The three parameters x, y and z are unitless and describe the listener's position in 3D space according to the right-hand Cartesian coordinate system. PannerNode objects use this position relative to individual audio sources for spatialisation. The default value of the position vector is (0, 0, 0). Syntax var audioCtx = new AudioContext
(); var myListener = audioCtx.listener; myListener.setPosition(1,1,1); Returns Void. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy ini...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 4 more matches
BaseAudioContext.createAnalyser() - Web APIs
The createAnalyser
() method of the BaseAudioContext interface creates an AnalyserNode, which can be used to expose audio 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). ...
...ic 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
(); ... ...
...o (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)
(); var analyser = audioCtx.createAnalyser
(); ... ...
...And 4 more matches
BaseAudioContext.createPanner() - Web APIs
The createPanner
() method of the BaseAudioContext Interface is used to create a new PannerNode, which is used to spatialize an incoming audio stream in 3D space. The panner node is spatialized in relation to the AudioContext's AudioListener (defined by the AudioContext.listener attribute), which represents the position and orientation of the person listening to the audio. Syntax baseAudioCtx.createPanner
(); Returns A PannerNode. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is us...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 4 more matches
CanvasPattern.setTransform() - Web APIs
The CanvasPattern.setTransform
() method uses an SVGMatrix or DOMMatrix object as the pattern's transformation matrix and invokes it on the pattern. Syntax void pattern.setTransform(matrix); Parameters matrix An SVGMatrix or DOMMatrix to use as the pattern's transformation matrix. Examples Using the setTransform method This is just a simple code snippet which uses the setTransform method to create a CanvasPattern with the specified pattern transformation from an SVGMatrix. The pattern gets applied if you set it as the current fillStyle and gets drawn onto the canvas when using the fillRect
() method, for example. HTML <canvas id="canvas"></canvas> <svg id="svg1"></svg> JavaScript var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var svg1 = do...
...tion from an SVGMatrix. The pattern gets applied if you set it as the current fillStyle and gets drawn onto the canvas when using the fillRect
() method, for example. ...
...The pattern gets applied if you set it as the current fillStyle and gets drawn onto the canvas when using the fillRect
() method, for example. ...
...And 4 more matches
CanvasRenderingContext2D.clearRect() - Web APIs
The rectangle's corner is at (x, y), and its size is specified by width and height. Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. ...
...The rectangle's corner is at (x, y), and its size is specified by width and height. Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. ...
...The rectangle's corner is at (x, y), and its size is specified by width and height. Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. ...
...And 4 more matches
DOMMatrixReadOnly.scale() - Web APIs
DOMMatrix.scale(scaleX[, scaleY][, scaleZ][, originX][, originY][, originZ]) Parameters scaleX A multiplier for the scale value on the x-axis. scaleY Optional A multiplier for the scale value on the y-axis. If not supplied, this defaults to the value of scaleX. scaleZ Optional A multiplier for the scale value on the z-axis. If this value is anything other than 1, the resulting matrix will be 3D. originX Optional An x-coordinate for the origin of the transformation. If no origin is supplied, this defaults to 0. ...
... We then create a new matrix scaled about a given origin, using either t...
...ight="250" viewBox="0 0 25 25"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> <rect id="transformedOrigin" width="25" height="25" fill="green" /> </svg> This JavaScript first creates an identity matrix, then uses the scale
() method to create a new matrix with a single parameter. We test if the browser supports a six parameter scale
() method by creating a new matrix using three parameters and observing it's is2D property -- if this is false then the third parameter has been accepted by the browser as a scaleZ parameter, making this a 3D matrix. We then create a new matrix scaled about a given origin, using either three or six parameters depending on the browser support. These new matrices are then applied to the blue and gre...
...And 4 more matches
DataTransfer.clearData() - Web APIs
If data for the given type does not exist, this method does nothing. If this method is called with no arguments or the format is an empty string, the data of all types will be removed. This method does not remove files from the drag operation, so it's possible for there still to be an entry with the type "Files" left in the object's DataTransfer.types list if there are any files included in the drag. This method can only be used in the handler for the dragstart event, because that's the only time the drag operation's data store is writeable. ...
...ler for the dragstart event, because that's the only time the drag operation's data store is writeable. Syntax DataTransfer.clearData([format]); Parameters format Optional A string which specifies the type of data to remove. If this parameter is an empty string or is not provided, the data for all types is removed. Example This example shows the use of the DataTransfer object's getData
(), setData
() and clearData
() methods. HTML <span class="tweaked" id="source" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element. </span> <span class="tweaked" id="target">Drop Zone</span> <div>Status: <span id="status">Drag to start</span></div> <div>Data is: <span id="data">uninitialized</span></div> CSS span.tweaked { displa...
...weaked" id="target">Drop Zone</span> <div>Status: <span id="status">Drag to start</span></div> <div>Data is: <span id="data">uninitialized</span></div> CSS span.tweaked { display: inline-block; margin: 1em 0; padding: 1em 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } JavaScript window.addEventListener('DOMContentLoaded', function
() { // Select HTML elements var draggable = document.getElementById('source'); var dropable = document.getElementById('target'); var status = document.getElementById('status'); var data = document.getElementById('data'); var dropped = false; // Register event handlers draggable.addEventListener('dragstart', dragStartHandler); draggable.addEventListener('dragend', dragEndHandler);...
...And 4 more matches
Document.importNode() - Web APIs
The imported node is a clone of the original. Syntax const importedNode = document.importNode(externalNode [, deep]); Parameters externalNode The external Node or DocumentFragment to import into the current document. ...
...The imported node is a clone of the original. Syntax const importedNode = document.importNode(externalNode [, deep]); Parameters externalNode The external Node or DocumentFragment to import into the current document. ...
...The imported node is a clone of the original. Syntax const importedNode = document.importNode(externalNode [, deep]); Parameters externalNode The external Node or DocumentFragment to import into the current document. ...
...And 4 more matches
Document.open() - Web APIs
The Document.open
() method opens a document for writing. This does come with some side effects. For example: All event listeners currently registered on the document, nodes inside the document, or the document's window are removed. All existing nodes are removed from the document. Syntax document.open
(); Parameters None. Return value A Document object instance. Examples The following simple code opens the document and replaces its content with a number of different HTML fragments, before closing it again. document.open
(); document.write("<p>Hello world!</p>"); document.write("<p>I am a fish</p>"); document.write("<p>The number is 42</p>"); document.close
(); Notes An automatic document.open
() call happens when document.write
() is called after the page has loaded. For year...
...plorer additionally erased all JavaScript variables, etc., in addition to removing all nodes. This is no longer the case.document non-spec'ed parameters to document.open Gecko-specific notes Starting with Gecko 1.9, this method is subject to the same same-origin policy as other properties, and does not work if doing so would change the document's origin. ...
...document.open Gecko-specific notes Starting with Gecko 1.9, this method is subject to the same same-origin policy as other properties, and does not work if doing so would change the document's origin. Starting with Gecko 1.9.2, document.open
() uses the principal of the document whose URI it uses, instead of fetching the principal off the stack. As a result, you can no longer call document.write
() into an untrusted document from chrome, even using wrappedJSObject. See Security check basics for more about principals. Three-argument document.open
() There is a lesser-known and little-used three-argument version of document.open
() , which is an alias of Window.open
() (see its page for full details). This call, for example opens github.com in a new window, with its opener set to null: docum...
...And 4 more matches
Element.attachShadow() - Web APIs
Elements you can attach a shadow to Note that you can't attach a shadow root to every type of element. There are some that can't have a shadow DOM for security reasons (for example <a>), and more besides. ...
...idStateError The element you are trying to attach to is already a shadow host. NotSupportedError You are trying to attach a shadow root to an element outside the HTML namespace, or the element cannot have a shadow attached to it (see above). Examples The following example is taken from our word-count-web-component demo (see it live also). ...
...ent cannot have a shadow attached to it (see above). Examples The following example is taken from our word-count-web-component demo (see it live also). You can see that we use attachShadow
() in the middle of the code to create a shadow root, which we then attach our custom element's contents to. ...
...And 4 more matches
Element.getBoundingClientRect() - Web APIs
The result is the smallest rectangle which contains the entire element, with read-only left, top, right, bottom, x, y, width, and height properties describing the overall border-box in pixels. ...
...The result is the smallest rectangle which contains the entire element, with read-only left, top, right, bottom, x, y, width, and height properties describing the overall border-box in pixels. ...
...nd its position relative to the viewport. The element's size is equal to its width/height + padding + border-width in the case that the standard box model is being used, or width/height only if box-sizing: border-box has been set on it. Syntax domRect = element.getBoundingClientRect
(); Value The returned value is a DOMRect object which is the union of the rectangles returned by getClientRects
() for the element, i.e., the CSS border-boxes associated with the element. The result is the smallest rectangle which contains the entire element, with read-only left, top, right, bottom, x, y, width, and height properties describing the overall border-box in pixels. Properties other than width and height are relative to the top-left of the viewport. Empty border-boxes are completely ignored. If...
...And 4 more matches
Element.requestFullscreen() - Web APIs
It's not guaranteed that the element will be put into full screen mode. If permission to enter full screen mode is granted, the returned Promise will resolve and the element will receive a fullscreenchange event to let it know that it's now in full screen mode. If permission is denied, the promise is rejected and the element receives a fullscreenerror event instead. If the element has been detached from the original document, then the document receives these events instead. ...
...ption is navigationUI, which controls whether or not to show navigation UI while the element is in full-screen mode. The default value is "auto", which indicates that the browser should decide what to do. Return value A Promise which is resolved with a value of undefined when the transition to full screen is complete. Exceptions Rather than throw a traditional exception, the requestFullscreen
() procedure announces error conditions by rejecting the Promise it has returned. The rejection handler receives one of the following exception values: TypeError The TypeError exception may be delivered in any of the following situations: The document containing the element isn't fully active; that is, it's not the current active document. The element is not contained by a document. The ...
...lement. It must either be located within the top-level document or in an <iframe> which has the allowfullscreen attribute applied to it. Additionally, of course, the Feature Policy "fullscreen" permission must be granted. Detecting full-screen activation You can determine whether or not your attempt to switch to full-screen mode is successful by using the Promise returned by requestFullscreen
(), as seen in the Example below. To learn when other code has toggled full-screen mode on and off, you should establish listeners for the fullscreenchange event on the Document. It's also important to listen for fullscreenchange to be aware when, for example, the user manually toggles full-screen mode, or when the user switches applications, causing your application to temporarily exit full-screen...
...And 4 more matches
Event.preventDefault() - Web APIs
The Event interface's preventDefault
() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. The event continues to propagate as usual, unless one of its event listeners calls stopPropagation
() or stopImmediatePropagation
(), either of which terminates propagation at once. As noted below, calling preventDefault
() for a non-cancelable event, such as one dispatched via EventTarget.dispatchEvent
(), without specifying cancelable: true has no effect. Syntax event.preventDefault
(); Examples Blocking default click handling Toggling a checkbox is the default action of clicking on a checkbox. This example demonstrates how to prevent that from happening: JavaScript document.querySelector("#id-checkbox").a...
...ffect. Syntax event.preventDefault
(); Examples Blocking default click handling Toggling a checkbox is the default action of clicking on a checkbox. ...
...ick handling Toggling a checkbox is the default action of clicking on a checkbox. This example demonstrates how to prevent that from happening: JavaScript document.querySelector("#id-checkbox").addEventListener("click", function(event) { document.getElementById("output-box").innerHTML += "Sorry! <code>preventDefault
()</code> won't let you check this!<br>"; event.preventDefault
(); }, false); HTML <p>Please click on the checkbox control.</p> <form> <label for="id-checkbox">Checkbox:</label> <input type="checkbox" id="id-checkbox"/> </form> <div id="output-box"></div> Result Stopping keystrokes from reaching an edit field The following example demonstrates how invalid text input can be stopped from reaching the input field with preventDefault
(). Nowadays, you s...
...And 4 more matches
HTMLDialogElement.showModal() - Web APIs
The showModal
() method of the HTMLDialogElement interface displays the dialog as a modal, over the top of any other dialogs that might be present. It displays into the top layer, along with a ::backdrop pseudo-element. Interaction outside the dialog is blocked and the content outside it is rendered inert. Syntax dialogInstance.showModal
(); Parameters None. Return value Void. Exceptions If the dialog is already open (i.e. if the open attribute is already set on the <dialog> element), an InvalidStateError is thrown. Examples The following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showModal
() method. ...
.... Return value Void. Exceptions If the dialog is already open (i.e. if the open attribute is already set on the <dialog> element), an InvalidStateError is thrown. Examples The following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showModal
() method. From there you can click the Cancel button to close the dialog (via the HTMLDialogElement.close
() method), or submit the form via the submit button. <!-- Simple pop-up dialog box, containing a form --> <dialog id="favDialog"> <form method="dialog"> <section> <p><label for="favAnimal">Favorite animal:</label> <select id="favAnimal" name="favAnimal"> <option></option> <option>Brine shrimp</option> <option>Red panda</option> ...
...ption>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function
() { var updateButton = document.getElementById('updateDetails'); var cancelButton = document.getElementById('cancel'); var dialog = document.getElementById('favDialog'); dialog.returnValue = 'favAnimal'; function openCheck(dialog) { if(dialog.open) { console.log('Dialog open'); } else { console.log('Dialog closed'); } ...
...And 4 more matches
HTMLInputElement.stepDown() - Web APIs
faults to the default value for step if not specified. Valid on all numeric, date, and time input types that support the step attribute, includingdate, month, week, time, datetime-local, number, and range. Given <input id="myTime" type="time" max="17:00" step="900" value="17:00">, invoking myTime.step(3) will change the value to 16:15, decrementing the time by 3 * 900, or 45 minutes. myTime.step
(), with no parameter, would have resulted in 16:45, as n defaults to 1. <!-- decrements by intervals of 900 seconds (15 minute) --> <input type="time" max="17:00" step="900"> <!-- decrements by intervals of 7 days (one week) --> <input type="date" max="2019-12-25" step="7"> <!-- decrements by intervals of 12 months (one year) --> <input type="month" max="2019-12" step="12"> The method, when in...
...ute, multiplied by the parameter, within the constraints set within the form control. The default value for the parameter, if not is passed, is 1. The method will not cause the value to go below the min value set or defy the constraints set by the step attribute. A negative value for n will increment the value, but will not increment beyond the max value. If the value before invoking the stepDown
() method is invalid, for example, if it doesn't match the constraints set by the step attribute, invoking the stepDown
() method will return a value that does match the form controls constraints. If the form control is non time, date, or numeric in nature, and therefore does not support the step attribute (see the list of supported input types in the the table above), or if the step value is set to...
...Throws an INVALID_STATE_ERR exception: if the method is not applicable to for the current type value, if the element has no step value, if the value cannot be converted to a number, if the resulting value is above the max or below the min. ...
...And 4 more matches
IDBIndex.count() - Web APIs
Return value A IDBRequest object on which subsequent events related to this operation are fired. Exceptions This method may raise a DOMException of one of the following types: Exception Description TransactionInactiveError This IDBIndex's transaction is inactive. DataError The key or key range provided contains an invalid key. ...
...mple In the following example we open a transaction and an object store, then get the index lName from a simple contacts database. We then open a basic cursor on the index using IDBIndex.openCursor -- this works the same as opening a cursor directly on an ObjectStore using IDBObjectStore.openCursor except that the returned records are sorted based on the index, not the primary key. ...
...the index, not the primary key. myIndex.count
() is then used to count the number of records in the index, and the result of that request is logged to the console when its success callback returns. Finally, we iterate through each record, and insert the data into an HTML table. ...
...And 4 more matches
IDBIndex.openCursor() - Web APIs
The method sets the position of the cursor to the appropriate record, based on the specified direction. If the key range is not specified or is null, then the range includes all the records. A success event is always fired on the result object. If at least one record matches the key range, then the result property of the event is set to the new IDBCursorWithValue object; the value of the cursor object is set to a structured clone of the referenced value. If no records match the key range then then the result property of the event is set to null. Note: This feature is available in Web Workers. ...
...least one record matches the key range, then the result property of the event is set to the new IDBCursorWithValue object; the value of the cursor object is set to a structured clone of the referenced value. If no records match the key range then then the result property of the event is set to null. Note: This feature is available in Web Workers. Syntax var request = myIndex.openCursor
(); var request = myIndex.openCursor(range); var request = myIndex.openCursor(range, direction); Parameters range Optional A key or IDBKeyRange to use as the cursor's range. If nothing is passed, this will default to a key range that selects all the records in this object store. direction Optional The cursor's direction. See IDBCursor Constants for possible values. Return value An IDBReque...
...ue for the direction parameter is invalid. DataError The key or key range provided contains an invalid key. InvalidStateError The IDBIndex has been deleted or removed. Example In the following example we open a transaction and an object store, then get the index lName from a simple contacts database. ...
...And 4 more matches
IDBIndex.openKeyCursor() - Web APIs
The method sets the position of the cursor to the appropriate key, based on the specified direction. If the key range is not specified or is null, then the range includes all the keys. A success event is always fired on the result object. If at least one key matches the key range, then the result property of the event is set to the new IDBCursor object; the key property of the cursor object is set to the found key and the primaryKey property is set to the the corresponding primary key of the found record. ...
...e key matches the key range, then the result property of the event is set to the new IDBCursor object; the key property of the cursor object is set to the found key and the primaryKey property is set to the the corresponding primary key of the found record. If no keys match the key range, then then the result property of the event is set to null. ...
...rimary key of the found record. If no keys match the key range, then then the result property of the event is set to null. Note: Cursors returned by openKeyCursor
() do not make the referenced value available as IDBIndex.openCursor does. This makes obtaining a list of keys much more efficient. Note: This feature is available in Web Workers. Syntax var request = myIndex.openKeyCursor
(); var request = myIndex.openKeyCursor(range); var request = myIndex.openKeyCursor(range, direction); Parameters range Optional A key or IDBKeyRange to use as the cursor's range. If nothing is passed, this will default to a key range that selects all the records in this object store. direction Optional The cursor's direction. See IDBCursor Constants for possible values. Return value An ID...
...And 4 more matches
IDBObjectStore.add() - Web APIs
This is for adding new records to an object store. To determine if the add operation has completed successfully, listen for the transaction's complete event in addition to the IDBObjectStore.add request's success event, because the transaction may still fail after the success event fires. In other words, the success event is only triggered when the transaction has been successfully queued. The add method is an insert only method. If a record already exists in the object store with the key parameter as its key, then an error ConstrainError event is fired on the returned request object. ...
... being stored could not be cloned by the internal structured cloning algorithm. ConstraintError An insert operation failed because the primary key constraint was violated (due to an already existing record with the same primary key value). Example In the following code snippet, we open a read/write transaction on our database and add some data to an object store using add
(). Note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. For a full working example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database ...
...king example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...And 4 more matches
ImageCapture.getPhotoCapabilities() - Web APIs
This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. ...
...This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. ...
...This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. ...
...And 4 more matches
LockManager.request() - Web APIs
The requested Lock is passed to a callback, while the function itself returns a Promise that resolves with undefined. The mode property of the options parameter may be either "exclusive" or "shared". Request an "exclusive" lock when it should only be held by one code instance at a time. This applies to code in both tabs and workers. Use this to represent mutually exclusive access to a resource. When an "exclusive" lock for a given name is held, no other lock with the same name can be held. Request a "shared" lock when multiple instances of the code can share access to a resource. ...
...e default value is false. signal Optional: An AbortSignal (the signal property of an AbortController); if specified and the AbortController is aborted, the lock request is dropped if it was not already granted. callback ... Return value A Promise that resolves with undefined when the request is granted. Examples General Example The following example shows the basic use of the request
() method with an asynchronous function as the callback. Once the callback is invoked, no other running code on this orign can hold `my_resource` until the callback returns. await navigator.locks.request('my_resource', async lock => { // The lock was granted. }); Mode Example The following example shows how to use the mode option for readers and writers. Notice that both functions use a lock ...
...nction as the callback. Once the callback is invoked, no other running code on this orign can hold `my_resource` until the callback returns. await navigator.locks.request('my_resource', async lock => { // The lock was granted. }); Mode Example The following example shows how to use the mode option for readers and writers. Notice that both functions use a lock called my_resource. ...
...And 4 more matches
MediaDevices.getDisplayMedia() - Web APIs
The MediaDevices interface's getDisplayMedia
() method prompts the user to select and grant permission to capture the contents of a display or portion thereof (such as a window) as a MediaStream. The resulting stream can then be recorded using the MediaStream Recording API or transmitted as part of a WebRTC session. See Using the Screen Capture API for more details and an example. Syntax var promise = navigator.mediaDevices.getDisplayMedia(constraints); Parameters constraints Optional An optional MediaStreamConstraints object specifying requirements for the returned MediaStream. Since getDisplayMedia
() requires a video track, the returned stream will have one even if no video track is expressly requested by the constraints object. Return value A Promise that resolves to a MediaSt...
...ch audio source or sourcoes are supported. Check the compatibility table for details for each browser. Exceptions Rejections of the returned promise are made by passing a DOMException error object to the promise's failure handler. Possible errors are: AbortError An error or failure that doesn't match any of the other exceptions below occurred. InvalidStateError The call to getDisplayMedia
() was not made from code running due to a user action, such as an event handler. Another potential cause for this event: the document in whose context getDisplayMedia
() was called is not fully active; for example, perhaps it is not the frontmost tab. NotAllowedError Permission to access a screen area was denied by the user, or the current browsing instance is not permitted access to screen sharin...
...b, or other source of screen data, but a hardware or operating system level error or lockout occurred, preventing the sharing of the selected source. OverconstrainedError After creating the stream, applying the specified constraints fails because no compatible stream could be generated. TypeError The specified constraints include constraints which are not permitted when calling getDisplayMedia
(). ...
...And 4 more matches
MediaSession.setPositionState() - Web APIs
This can be particularly useful if your code implements a player for type of media not directly supported by the browser. Call this method on the navigator object's mediaSession object. Syntax navigator.mediaSession.setPositionState(stateDict); Parameters stateDict Optional An object conforming to the MediaPositionState dictionary, providing updated information about the playback position and speed of the document's ongoing media. If the object is empty, the existing playback state information is cleared. ...
...defined. Exceptions TypeError This error can occur in an array of circumstances: The specified MediaPositionState object's duration is missing, negative, or null. position is missing or null, or is either negative or greater than duration. The playbackRate is zero. ...
...onState object's duration is missing, negative, or null. position is missing or null, or is either negative or greater than duration. The playbackRate is zero. Example In this example, a player for a non-standard media file format, written in JavaScript, uses setInterval
() to establish a callback which fires once per second to refresh the position information by calling setPositionState
(). ...
...And 4 more matches
Node.appendChild() - Web APIs
Note that the copies made with cloneNode will not be automatically kept in sync. ...
...Note that the copies made with cloneNode will not be automatically kept in sync. ...
...isting node in the document, appendChild
() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node). This means that a node can't be in two points of the document simultaneously. So if the node already has a parent, the node is first removed, then appended at the new position. The Node.cloneNode
() method can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode will not be automatically kept in sync. If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node. ...
...And 4 more matches
PannerNode.setPosition() - Web APIs
The setPosition
() method of the PannerNode Interface defines the position of the audio source relative to the listener (represented by an AudioListener object stored in the AudioContext.listener attribute.) The three parameters x, y and z are unitless and describe the source's position in 3D space using the right-hand Cartesian coordinate system. The setPosition
() method's default value of the position is (0, 0, 0). Syntax var audioCtx = new AudioContext
(); var panner = audioCtx.createPanner
(); panner.setPosition(0,0,0); Returns Void. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and pan...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 4 more matches
PannerNode.setVelocity() - Web APIs
The setVelocity
() method of the PannerNode Interface defines the velocity vector of the audio source -- how fast it is moving and in what direction. This method was removed from the specification because of gaps in its design and implementation problems. The velocity relative to the listener is used to control the pitch change needed to conform with the Doppler effect due to the relative speed. As the vector controls both the direction of travel and its velocity, the three parameters x, y and z are expressed in meters per second. The default value of the velocity vector is (0, 0, 0). Syntax var audioCtx = new AudioContext
(); var panner = audioCtx.createPanner
(); panner.setVelocity(0,0,17); Returns Void. Example In the following example, you can see an example of how the createPan...
...s the vector controls both the direction of travel and its velocity, the three parameters x, y and z are expressed in meters per second. The default value of the velocity vector is (0, 0, 0). Syntax var audioCtx = new AudioContext
(); var panner = audioCtx.createPanner
(); panner.setVelocity(0,0,17); Returns Void. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realist...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...And 4 more matches
ParentNode.querySelector() - Web APIs
Syntax element = parentNode.querySelector(selectors); Parameters selectors A DOMString containing one or more selectors to match against. This string must be a valid compound selector list supported by the browser; if it's not, a SyntaxError exception is thrown. ...
... Syntax element = parentNode.querySelector(selectors); Parameters selectors A DOMString containing one or more selectors to match against. This string must be a valid compound selector list supported by the browser; if it's not, a SyntaxError exception is thrown. ...
... Syntax element = parentNode.querySelector(selectors); Parameters selectors A DOMString containing one or more selectors to match against. This string must be a valid compound selector list supported by the browser; if it's not, a SyntaxError exception is thrown. ...
...And 4 more matches
performance.getEntries() - Web APIs
The getEntries
() method returns a list of all PerformanceEntry objects for the page. The list's members (entries) can be created by making performance marks or measures (for example by calling the mark
() method) at explicit points in time. If you are only interested in performance entries of certain types or that have certain names, see getEntriesByType
() and getEntriesByName
(). Note: This feature is available in Web Workers. Syntax General syntax: entries = window.performance.getEntries
(); Return value entries An array of PerformanceEntry objects. The items will be in chronological order based on the entries' startTime. Example function use_PerformanceEntry_methods
() { console.log("PerformanceEntry tests ..."); if (performance.mark === undefined) { console.log("... pe...
... Return value entries An array of PerformanceEntry objects. The items will be in chronological order based on the entries' startTime. Example function use_PerformanceEntry_methods
() { console.log("PerformanceEntry tests ..."); if (performance.mark === undefined) { console.log("... ...
...tests ..."); if (performance.mark === undefined) { console.log("... ...
...And 4 more matches
PerformanceEntry.toJSON() - Web APIs
The toJSON
() method is a serializer; it returns a JSON representation of the performance entry object. Note: This feature is available in Web Workers. Syntax json = perfEntry.toJSON
(); Arguments None Return value json A JSON object that is the serialization of the PerformanceEntry object. Example The following example shows the use of the toJSON
() method. function run_PerformanceEntry
() { log("PerformanceEntry support ..."); if (performance.mark === undefined) { log("... ...
...e Return value json A JSON object that is the serialization of the PerformanceEntry object. Example The following example shows the use of the toJSON
() method. function run_PerformanceEntry
() { log("PerformanceEntry support ..."); if (performance.mark === undefined) { log("... ...
...xample The following example shows the use of the toJSON
() method. function run_PerformanceEntry
() { log("PerformanceEntry support ..."); if (performance.mark === undefined) { log("... ...
...And 4 more matches
RTCPeerConnection.getConfiguration() - Web APIs
Return value An RTCConfiguration object describing the RTCPeerConnection's current configuration. ...
... Return value An RTCConfiguration object describing the RTCPeerConnection's current configuration. ...
... Return value An RTCConfiguration object describing the RTCPeerConnection's current configuration. ...
...And 4 more matches
RTCPeerConnection.getStats() - Web APIs
Syntax promise = rtcPeerConnection.getStats(selector) Parameters selector Optional A MediaStreamTrack for which to gather statistics. If this is null (the default value), statistics will be gathered for the entire RTCPeerConnection. Return value A Promise which resolves with an RTCStatsReport object providing connection statistics. The contents of the report depend on the selector as well as other details of the connection. ...
...rt depend on the selector as well as other details of the connection. Exceptions This method does not throw exceptions; instead, it rejects the returned promise with one of the following errors: InvalidAccessError There is no RTCRtpSender or RTCRtpReceiver whose track matches the specified selector, or selector matches more than one sender or receiver. ...
...instead, it rejects the returned promise with one of the following errors: InvalidAccessError There is no RTCRtpSender or RTCRtpReceiver whose track matches the specified selector, or selector matches more than one sender or receiver. Obsolete syntax Previously, getStats
() used success and failure callbacks to report the results to you, instead of using a promise. This version of getStats
() is obsolete; in addition, the data it returns is entirely different from the current specification, and the form of that data was never documented. This form of getStats
() has been or will soon be removed from most browsers; you should not use it, and should update existing code to use the new promise-based version. Check the Browser compatibility table to verify the state of this method. promis...
...And 4 more matches
RTCRtpSender.replaceTrack() - Web APIs
See the example Switching cameras below. Syntax trackReplacedPromise = sender.replaceTrack(newTrack); Parameters newTrack Optional A MediaStreamTrack specifying the track with which to replace the RTCRtpSender's current source track. ...
...See the example Switching cameras below. Syntax trackReplacedPromise = sender.replaceTrack(newTrack); Parameters newTrack Optional A MediaStreamTrack specifying the track with which to replace the RTCRtpSender's current source track. ...
...See the example Switching cameras below. Syntax trackReplacedPromise = sender.replaceTrack(newTrack); Parameters newTrack Optional A MediaStreamTrack specifying the track with which to replace the RTCRtpSender's current source track. ...
...And 4 more matches
SourceBuffer.abort() - Web APIs
The MSE API is fully asynchronous, but this step seems to suggest a synchronous (blocking) operation, which doesn't make sense. ...
...The MSE API is fully asynchronous, but this step seems to suggest a synchronous (blocking) operation, which doesn't make sense. ...
...The MSE API is fully asynchronous, but this step seems to suggest a synchronous (blocking) operation, which doesn't make sense. ...
...And 4 more matches
SubtleCrypto.exportKey() - Web APIs
Syntax const result = crypto.subtle.exportKey(format, key); Parameters format is a string value describing the data format in which the key should be exported. It can be one of the following: raw: Raw format. pkcs8: PKCS #8 format. spki: SubjectPublicKeyInfo format. ...
... Syntax const result = crypto.subtle.exportKey(format, key); Parameters format is a string value describing the data format in which the key should be exported. It can be one of the following: raw: Raw format. pkcs8: PKCS #8 format. spki: SubjectPublicKeyInfo format. ...
...y: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. To export a key, the key must have CryptoKey.extractable set to true. Keys can be exported in several formats: see Supported formats in the SubtleCrypto.importKey
() page for details. Keys are not exported in an encrypted format: to encrypt keys when exporting them use the SubtleCrypto.wrapKey
() API instead. Syntax const result = crypto.subtle.exportKey(format, key); Parameters format is a string value describing the data format in which the key should be exported. It can be one of the following: raw: Raw format. pkcs8: PKCS #8 format. spki: SubjectPublicKeyInfo format. jwk: JSON Web Key format. key is the CryptoKey to export. Return value result is a P...
...And 4 more matches
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
In WebGL, values that apply to a specific vertex are stored in attributes. These are only available to the JavaScript code and the vertex shader. Attributes are referenced by an index number into the list of attributes maintained by the GPU. Some vertex attribute indices may have predefined purposes, depending on the platform and/or the GPU. Others are assigned by the WebGL layer when you create the attributes. ...
... Attributes are referenced by an index number into the list of attributes maintained by the GPU. Some vertex attribute indices may have predefined purposes, depending on the platform and/or the GPU. Others are assigned by the WebGL layer when you create the attributes. Either way, since attributes cannot be used unless enabled, and are disabled by default, you need to call enableVertexAttribArray
() to enable individual attributes so that they can be used. Once that's been done, other methods can be used to access the attribute, including vertexAttribPointer
(), vertexAttrib*
(), and getVertexAttrib
(). Syntax void gl.enableVertexAttribArray(index); Parameters index A GLuint specifying the index number that uniquely identifies the vertex attribute to enable. If you know the name of the ...
...e, other methods can be used to access the attribute, including vertexAttribPointer
(), vertexAttrib*
(), and getVertexAttrib
(). Syntax void gl.enableVertexAttribArray(index); Parameters index A GLuint specifying the index number that uniquely identifies the vertex attribute to enable. If you know the name of the attribute but not its index, you can get the index by calling getAttribLocation
(). Return value undefined. Errors To check for errors after calling enableVertexAttribArray
(), call getError
(). WebGLRenderingContext.INVALID_VALUE The specified index is invalid; that is, it's greater than or equal to the maximum number of entries permitted in the context's vertex attribute list, as indicated by the value of WebGLRenderingContext.MAX_VERTEX_ATTRIBS. Example This code -...
...And 4 more matches
WebGLRenderingContext.getUniformLocation() - Web APIs
Part of the WebGL API, the WebGLRenderingContext method getUniformLocation
() returns the location of a specific uniform variable which is part of a given WebGLProgram. The uniform variable is returned as a WebGLUniformLocation object, which is an opaque identifier used to specify where in the GPU's memory that uniform variable is located. Once you have the uniform's location, you can access the uniform itself using one of the other uniform access methods, passing in the uniform location as one of the inputs: getUniform
() Returns the value of the uniform at the given location. ...
...GLUniformLocation object, which is an opaque identifier used to specify where in the GPU's memory that uniform variable is located. Once you have the uniform's location, you can access the uniform itself using one of the other uniform access methods, passing in the uniform location as one of the inputs: getUniform
() Returns the value of the uniform at the given location. uniform[1234][fi][v]
() Sets the uniform's value to the specified value, which may be a single floating point or integer number, or a 2-4 component vector specified either as a list of values or as a Float32Array or Int32Array. uniformMatrix[234][fv]
() Sets the uniform's value to the specified matrix, possibly with transposition. The value is represented as a sequence of GLfloat values or as a Float32Array. The uni...
...dentify the location in the GPU's memory at which the uniform variable is located. With this value in hand, you can call other WebGL methods to access the value of the uniform variable. The WebGLUniformLocation type is compatible with the GLint type when specifying the index or location of a uniform attribute. ...
...And 4 more matches
XRSystem: requestSession() - Web APIs
While only one immersive VR session can be active at a time, multiple inline sessions can be in progress at once. Syntax var sessionPromise = xr.requestSession(sessionMode, sessionInit) Parameters sessionMode A DOMString whose value is one of those included in the XRSessionMode enum. The supported modes are: immersive-ar The session's output will be given exclusive access to the immersive device, but the rendered content will be blended with the real-world environment. ...
...does not support the specified sessionMode; this can also be thrown if any of the required options are unsupported. SecurityError Permission to enter the specified XR mode is denied. This can happen for a number of reasons, which are covered in more detail in Permissions and security in WebXR Device API. Examples Creating an immersive VR session The following example calls requestSession
() requesting an "immersive-vr" session. If the Promise resolves, it sets up a session and initiates the animation loop. navigator.xr.requestSession("immersive-vr") .then((xrSession) => { xrSession.addEventListener('end', onXRSessionEnded); // Do necessary session setup here. // Begin the session's animation loop. xrSession.requestAnimationFrame(onXRAnimationFrame); }).catch(function(error)...
...on setup here. // Begin the session's animation loop. ...
...And 4 more matches
XRWebGLLayer.getNativeFramebufferScaleFactor() static method - Web APIs
See the Usage notes and Examples for details. If the scaling factor is 1.0, then the frame buffer pixels and the native display pixels are the same size. ...
...See the Usage notes and Examples for details. If the scaling factor is 1.0, then the frame buffer pixels and the native display pixels are the same size. ...
...de by side each at a resolution of 1280x1440 pixels). Consider a frame buffer which at full size looks like this: If, on this device, it's determined that due to GPU limitations the browser needs to reduce image quality in order to improve performance to an acceptable level, it might choose to halve the resolution. In this case, the value returned by XRWebGLLayer.getNativeFramebufferScaleFactor
() will be 2.0. This method of dividing the frame buffer between views is shown in the following diagram. Now the width and height of the frame buffer are 50% what they were before, resulting in a total frame buffer size of 1280 by 720 pixels, with each eye's half of the buffer being 640x720 pixels. Now we can see the coordinates of each of the viewports representing these two views: Since eac...
...And 4 more matches
:not() - CSS: Cascading Style Sheets
The list must not contain another negation selector or a pseudo-element. The ability to list more than one selector is experimental and not yet widely supported. ...
...The list must not contain another negation selector or a pseudo-element. The ability to list more than one selector is experimental and not yet widely supported. ...
...The list must not contain another negation selector or a pseudo-element. The ability to list more than one selector is experimental and not yet widely supported. ...
...And 4 more matches
image-set() - CSS: Cascading Style Sheets
The image-set
() CSS function notation is a method of letting the browser pick the most appropriate CSS image from a given set, primarily for high pixel density screens. Resolution and bandwidth differ by device and network access. The image-set
() function delivers the most appropriate image resolution for a user's device, providing a set of image options -- each with an associated resolution declaration -- from which the browser picks the most appropriate for the device and settings. Resolution can be used as a proxy for filesize -- a user agent on a slow mobile connection with a high-resolution screen may prefer to receive lower-resolution images rather than waiting for a higher resolution image to load. ...
...roviding a set of image options -- each with an associated resolution declaration -- from which the browser picks the most appropriate for the device and settings. Resolution can be used as a proxy for filesize -- a user agent on a slow mobile connection with a high-resolution screen may prefer to receive lower-resolution images rather than waiting for a higher resolution image to load. ...
...he most appropriate for the device and settings. Resolution can be used as a proxy for filesize -- a user agent on a slow mobile connection with a high-resolution screen may prefer to receive lower-resolution images rather than waiting for a higher resolution image to load. image-set
() allows the author to provide options rather than determining what each individual user needs. Syntax image-set
() = image-set( <image-set-option># ) where <image-set-option> = [ <image> | <string> ] <resolution> and <string> is an <url> Values Most commonly you'll see an url
() <string> value, but the <image> can be any image type except for an image set. The image-set
() function can not be nested inside another image-set
() function. <resolution> units include x or dppx, for dots per pixel unit, dpi...
...And 4 more matches
matrix() - CSS: Cascading Style Sheets
The constant values are implied and not passed as parameters; the other parameters are described in the column-major order. Note: Until Firefox 16, Gecko accepted a <length> value for tx and ty. matrix(a, b, c, d, tx, ty) Values a b c d Are <number>s describing the linear transformation. tx ty Are <number>s describing the translation to apply. ...
...r transformation. tx ty Are <number>s describing the translation to apply. ...
...rmation. tx ty Are <number>s describing the translation to apply. ...
...And 4 more matches
Array.prototype.flat() - JavaScript
The flat
() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. 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 newArray = arr.flat([depth]); Parameters depth Optional The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. Return value A new array with the sub-array elements concatenated into it. ...
...interactive-examples and send us a pull request. Syntax var newArray = arr.flat([depth]); Parameters depth Optional The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. Return value A new array with the sub-array elements concatenated into it. ...
... 3, 4] // or with decomposition syntax const flattened = arr => [].concat(...arr); reduce + concat + isArray + recursivity const arr = [1, 2, [3, 4, [5, 6]]]; // to enable deep level flatten use recursion with reduce and concat function flatDeep(arr, d = 1) { return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? ...
...And 4 more matches
Function.prototype.apply() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax func.apply(thisArg, [ argsArray]) Parameters thisArg The value of this provided for the call to func. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed. This argument is required. ...
...undefined if no arguments should be provided to the function. Starting with ECMAScript 5 these arguments can be a generic array-like object instead of an array. See below for browser compatibility information. Return value The result of calling the function with the specified this value and arguments. Description Note: While the syntax of this function is almost identical to that of call
(), the fundamental difference is that call
() accepts an argument list, while apply
() accepts a single array of arguments. Note: When the first argument is undefined or null a similar outcome can be achieved using the array spread syntax. You can assign a different this object when calling an existing function. this refers to the current object (the calling object). With apply, you can write a ...
...first argument is undefined or null a similar outcome can be achieved using the array spread syntax. You can assign a different this object when calling an existing function. this refers to the current object (the calling object). With apply, you can write a method once, and then inherit it in another object, without having to rewrite the method for the new object. apply is very similar to call
(), except for the type of arguments it supports. You use an arguments array instead of a list of arguments (parameters). With apply, you can also use an array literal, for example, func.apply(this, ['eat', 'bananas']), or an Array object, for example, func.apply(this, new Array('eat', 'bananas')). You can also use arguments for the argsArray parameter. arguments is a local variable of a function. ...
...And 4 more matches
Object.assign() - JavaScript
It returns the target object. 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 Object.assign(target, ...sources) Parameters target The target object -- what to apply the sources' properties to, which is returned after it is modified. sources The source object(s) -- objects containing the properties you want to apply. Return value The target object. Description Properties in the target object are overwritten by properties in the sources if they have the same key. ...
...object -- what to apply the sources' properties to, which is returned after it is modified. sources The source object(s) -- objects containing the properties you want to apply. Return value The target object. Description Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources' properties overwrite earlier ones. The Object.assign
() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property defin...
...It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions (including their enumerability) into prototypes, use Object.getOwnPropertyDescriptor
() and Object.defineProperty
() instead. Both String and Symbol properties are copied. In case of an error, for example if a property is non-writable, a TypeError is raised, and the target object is changed if any properties are added before the error is raised. Note: Object.assign
() does not throw on null or undefined sources. Polyfill This polyfill doesn't support symbol properties, since ES...
...And 4 more matches
Object.prototype.isPrototypeOf() - JavaScript
In the expression "object instanceof AFunction", the object prototype chain is checked against AFunction.prototype, not against AFunction itself. Syntax prototypeObj.isPrototypeOf(object) Parameters object The object whose prototype chain will be searched. Return value A Boolean indicating whether the calling object lies in the prototype chain of the specified object. ...
...n.prototype, not against AFunction itself. Syntax prototypeObj.isPrototypeOf(object) Parameters object The object whose prototype chain will be searched. Return value A Boolean indicating whether the calling object lies in the prototype chain of the specified object. Errors thrown TypeError A TypeError is thrown if prototypeObj is undefined or null. ...
...rown TypeError A TypeError is thrown if prototypeObj is undefined or null. Description The isPrototypeOf
() method allows you to check whether or not an object exists within another object's prototype chain. ...
...And 4 more matches
Promise.any() - JavaScript
It is currently in stage 4 of the TC39 process. Syntax Promise.any(iterable); Parameters iterable An iterable object, such as an Array. Return value An already resolved Promise if the iterable passed is empty. ...
...s and, as soon as one of the promises in the iterable fulfils, returns a single promise that resolves with the value from that promise. If no promises in the iterable fulfil (if all of the given promises are rejected), then the returned promise is rejected with an AggregateError, a new subclass of Error that groups together individual errors. Essentially, this method is the opposite of Promise.all
(). Warning! The Promise.any
() method is experimental and not fully supported by all browsers and platforms. It is currently in stage 4 of the TC39 process. Syntax Promise.any(iterable); Parameters iterable An iterable object, such as an Array. Return value An already resolved Promise if the iterable passed is empty. An asynchronously resolved Promise if the iterable passed contain...
...turned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when any of the promises in the given iterable resolve, or if all the promises have rejected. Description This method is useful for returning the first promise that fulfils. It short-circuits after a promise fulfils, so it does not wait for the other promises to complete once it finds one. Unlike Promise.all
(), which returns an array of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfil but we do not care which one does. Also, unlike Promise.race
(), which returns the first settled value (either fulfillment or rejection), this method returns the first fulfilled value. This method will ignore all rej...
...And 4 more matches
handler.defineProperty() - JavaScript
The handler.defineProperty
() method is a trap for Object.defineProperty
(). 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 p = new Proxy(target, { defineProperty: function(target, property, descriptor) { } }); Parameters The following parameters are passed to the defineProperty
() method. this is bound to the handler. target The target object. property The name or Symbol of the property whose description is to be retrieved. descriptor The descriptor for the property being defined or modified. ...
... defineProperty: function(target, property, descriptor) { } }); Parameters The following parameters are passed to the defineProperty
() method. this is bound to the handler. target The target object. property The name or Symbol of the property whose description is to be retrieved. descriptor The descriptor for the property being defined or modified. Return value The defineProperty
() method must return a Boolean indicating whether or not the property has been successfully defined. Description The handler.defineProperty
() method is a trap for Object.defineProperty
(). ...
... is to be retrieved. descriptor The descriptor for the property being defined or modified. Return value The defineProperty
() method must return a Boolean indicating whether or not the property has been successfully defined. Description The handler.defineProperty
() method is a trap for Object.defineProperty
(). Interceptions This trap can intercept these operations: Object.defineProperty
() Reflect.defineProperty
() Invariants If the following invariants are violated, the proxy will throw a TypeError: A property cannot be added, if the target object is not extensible. A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. A property may not be non-configurable, if a corresponding config...
...And 4 more matches
handler.ownKeys() - JavaScript
The handler.ownKeys
() method is a trap for Reflect.ownKeys
(). 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 p = new Proxy(target, { ownKeys: function(target) { } }); Parameters The following parameter is passed to the ownKeys
() method. this is bound to the handler. target The target object. Return value The ownKeys
() method must return an enumerable object. Description The handler.ownKeys
() method is a trap for Reflect.ownKeys
(). ...
... The type of each array element is either a String or a Symbol. ...
... The type of each array element is either a String or a Symbol. The result List must contain the keys of all non-configurable own properties of the target object. ...
...And 4 more matches
String.prototype.indexOf() - JavaScript
The indexOf
() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found. 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. Note: For the Array method, see Array.prototype.indexOf
(). Syntax str.indexOf(searchValue [, fromIndex]) Parameters searchValue The string value to search for. If no string is explicitly provided, searchValue will be coerced to "undefined", and this value will be searched for in str. ...
... fromIndex Optional An integer representing the index at which to start the search. Defaults to 0. ...
... fromIndex Optional An integer representing the index at which to start the search. Defaults to 0. For fromIndex values lower than 0, or greater than str.length, the search starts at index 0 and str.length, respectively. ...
...And 4 more matches
String.prototype.split() - JavaScript
The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.split([separator[, limit]]) Parameters separator Optional The pattern describing where each split should occur. The separator can be a simple string or it can be a regular expression. ...
...is removed from the string, and the substrings are returned in an array. If separator is a regular expression with capturing parentheses, then each time separator matches, the results (including any undefined results) of the capturing parentheses are spliced into the output array. If the separator is an array, then that Array is coerced to a String and used as a separator. Examples Using split
() When the string is empty, split
() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned. const myString = '' const splits = myString.split
() console.log(splits) // ? [""] The following example defines a function that splits a string into an array of strings using separator. After splitting t...
...new world that has such people in it." The separator is: "undefined" The array has 1 elements: Oh brave new world that has such people in it. The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec" The separator is: "," The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec Removing spaces from a string In the following example, split
() looks for zero or more spaces, followed by a semicolon, followed by zero or more spaces--and, when found, removes the spaces and the semicolon from the string. nameList is the array returned as a result of split
(). const names = 'Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ' console.log(names) const re = /\s*(?:;|$)\s*/ const nameList = names.split(re) console.log(nameList) ...
...And 4 more matches
TypedArray.from() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax TypedArray.from(source[, mapFn[, thisArg]]) Where TypedArray is one of: Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array BigInt64Array BigUint64Array Parameters source An array-like or iterable object to convert to a typed array. mapFn Optional Map function to call on every element of the typed array. ...
...6Array Uint16Array Int32Array Uint32Array Float32Array Float64Array BigInt64Array BigUint64Array Parameters source An array-like or iterable object to convert to a typed array. mapFn Optional Map function to call on every element of the typed array. thisArg Optional Value to use as this when executing mapFn. Return value A new TypedArray instance. Description TypedArray.from
() lets you create typed arrays from: array-like objects (objects with a length property and indexed elements); or iterable objects (objects where you can get its elements, such as Map and Set). TypedArray.from
() has the optional parameter mapFn, which allows you to execute a map
() function on each element of the typed array (or subclass object) that is being created. This means that the follo...
...t its elements, such as Map and Set). TypedArray.from
() has the optional parameter mapFn, which allows you to execute a map
() function on each element of the typed array (or subclass object) that is being created. This means that the following are equivalent: TypedArray.from(obj, mapFn, thisArg) TypedArray.from(Array.prototype.map.call(obj, mapFn, thisArg)). The length property of the from
() method is 1. Differences from Array.from
() Some subtle distinctions between Array.from
() and TypedArray.from
(): If the thisArg value passed to TypedArray.from
() is not a constructor, TypedArray.from
() will throw a TypeError, where Array.from
() defaults to creating a new Array. TypedArray.from
() uses [[Put]] where Array.from
() uses [[DefineProperty]]. Hence, when working with Proxy objects, ...
...And 4 more matches
WebAssembly.Global() constructor - JavaScript
This allows dynamic linking of multiple modules. Syntax new WebAssembly.Global(descriptor, value); Parameters descriptor A GlobalDescriptor dictionary object, which contains two properties: value: A USVString representing the data type of the global. This can be one of i32, i64, f32, and f64. mutable: A boolean value that determines whether the global is mutable or not. By default, this is false. value The value the variable contains. This can be any value, as long as its type matches the variable's data type. ...
...utable or not. By default, this is false. value The value the variable contains. This can be any value, as long as its type matches the variable's data type. If no value is specified, a typed 0 value is used, as specified by the DefaultValue algorithm. Examples Creating a new Global instance The following example shows a new global instance being created using the WebAssembly.Global
() constructor. It is being defined as a mutable i32 type, with a value of 0. The value of the global is then changed, first to 42 using the Global.value property, and then to 43 using the incGlobal
() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the new value). const output = document.getElementById('output'); function assertEq(msg...
... Specifications Specification WebAssembly JavaScript InterfaceThe defin...
...And 4 more matches
encodeURI() - JavaScript
The encodeURI
() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters). 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 encodeURI(URI) Parameters URI A complete URI. Return value A new string representing the provided string encoded as a URI. Description The encodeURI
() function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the...
...ed as a URI. Description The encodeURI
() function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI "scheme" can possibly contain. Note how certain characters are used to signify special meaning: http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor Hence encodeURI
() does not encode characters that are necessary to formulate a complete URI. Also, encodeURI
() does not encode a few additional characters, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See RFC2396) encodeURI
() escapes all characters except: Not Escaped: A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) # Examples encodeURI vs encode...
...: @ & = + $ - _ . ...
...And 4 more matches
Date.prototype.toLocaleFormat() - Archive of obsolete content
The non-standard toLocaleFormat
() method converts a date to a string using the specified formatting. Intl.DateTimeFormat is an alternative to format dates in a standards-compliant way. See also the newer version of Date.prototype.toLocaleDateString
(). This feature has been removed and will no longer work in Firefox 58+. See Warning: Date.prototype.toLocaleFormat is deprecated for more information and migration help. Syntax dateObj.toLocaleFormat(formatString) Parameters formatString A format string in the same format expected by the strftime
() function in C. Return value A string representing the given date using the specified formatting. Description The toLocaleFormat
() method provides greater software control over the formatting of the generated date and/or time. Na...
...mat string is localized properly according to the user's system settings. Be aware that the locale used is not necessarily the same as the locale of the browser. Extension and XULRunner developers should know that just loading the format string from a .dtd or .properties file using a chrome://somedomain/locale/somefile.ext URI should be avoided, as the .dtd/.properties file and the toLocaleFormat
() method does not not necessarily use the same locale, which could result in odd looking or even ambiguous or unreadable dates. Also note that the behavior of the used locale depends on the platform, and the user might customize the locale used, so using the system locale the choose the format string might in some cases not even be adequate. You might consider using some of the more general toLoca...
...user might customize the locale used, so using the system locale the choose the format string might in some cases not even be adequate. You might consider using some of the more general toLocale* methods of the Date object or doing your own custom localization of the date to be displayed using some of the get* methods of the Date object instead of using this method. ...
...And 3 more matches
Object.prototype.watch() - Archive of obsolete content
Syntax obj.watch(prop, handler) Parameters prop The name of a property of the object on which you wish to monitor changes. handler A function to call when the specified property's value changes. Return value undefined. ...
... Syntax obj.watch(prop, handler) Parameters prop The name of a property of the object on which you wish to monitor changes. handler A function to call when the specified property's value changes. Return value undefined. ...
...wval) whenever prop is set and storing the return value in that property. A watchpoint can filter (or nullify) the value assignment, by returning a modified newval (or by returning oldval). If you delete a property for which a watchpoint has been set, that watchpoint does not disappear. If you later recreate the property, the watchpoint is still in effect. To remove a watchpoint, use the unwatch
() method. By default, the watch method is inherited by every object descended from Object. The JavaScript debugger has functionality similar to that provided by this method, as well as other debugging options. For information on the debugger, see Venkman. In Firefox, handler is only called from assignments in script, not from native code. For example, window.watch('location', myHandler) will not ...
...And 3 more matches
AbortController.abort() - Web APIs
When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). ...
... When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). ...
...hod of the AbortController interface aborts a DOM request (e.g. a Fetch request) before it has completed. This is able to abort fetch requests, consumption of any response Body, and streams. Syntax controller.abort
(); Parameters None. Return value Void. Examples In the following snippet, we aim to download a video using the Fetch API. We first create a controller using the AbortController
() constructor, then grab a reference to its associated AbortSignal object using the AbortController.signal property. ...
...And 3 more matches
AnalyserNode.getByteTimeDomainData() - Web APIs
The getByteTimeDomainData
() method of the AnalyserNode Interface copies the current waveform, or time-domain, data into a Uint8Array (unsigned byte array) passed into it. 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. Syntax const audioCtx = new AudioContext
(); const analyser = audioCtx.createAnalyser
(); const dataArray = new Uint8Array(analyser.fftSize); // Uint8Array should be the same length as the fftSize analyser.getByteTimeDomainData(dataArray); // fill the Uint8Array with data returned from getByteTimeDomainData
() Parameters array The Uint8Array that the time domain data will be copied to. If the array has fewer elements than the AnalyserNode.fftSize, excess elemen...
... 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). ...
...e, 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
(); ... ...
...And 3 more matches
AnalyserNode.getFloatTimeDomainData() - Web APIs
The getFloatTimeDomainData
() method of the AnalyserNode Interface copies the current waveform, or time-domain, data into a Float32Array array passed into it. 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. Syntax var audioCtx = new AudioContext
(); var analyser = audioCtx.createAnalyser
(); var dataArray = new Float32Array(analyser.fftSize); // Float32Array needs to be the same length as the fftSize analyser.getFloatTimeDomainData(dataArray); // fill the Float32Array with data returned from getFloatTimeDomainData
() Parameters array The Float32Array that the time domain data will be copied to. If the array has fewer elements than the AnalyserNode.frequencyBinCount, excess e...
...asic 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). ...
... 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
(); ... ...
...And 3 more matches
Animation.pause() - Web APIs
The pause
() method of the Web Animations API's Animation interface suspends playback of the animation. Syntax animation.pause
(); Parameters None. Return value None. Exceptions InvalidStateError The animation's currentTime is unresolved (for example, if it's never been played or isn't currently playing) and the end time of the animation is positive infinity. Throws an InvalidStateError if the animation's currentTime is unresolved (perhaps it hasn't started playing yet) and the end time of the animation is positive infinity. ...
...ne. Exceptions InvalidStateError The animation's currentTime is unresolved (for example, if it's never been played or isn't currently playing) and the end time of the animation is positive infinity. Throws an InvalidStateError if the animation's currentTime is unresolved (perhaps it hasn't started playing yet) and the end time of the animation is positive infinity. ...
... the end time of the animation is positive infinity. Throws an InvalidStateError if the animation's currentTime is unresolved (perhaps it hasn't started playing yet) and the end time of the animation is positive infinity. ...
...And 3 more matches
AudioBuffer.getChannelData() - Web APIs
Syntax var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate); var nowBuffering = myArrayBuffer.getChannelData(channel); Parameters channel The channel property is an index representing the particular channel to get data for. An index value of 0 represents the first channel. If the channel index value is greater than of equal to AudioBuffer.numberOfChannels, an INDEX_SIZE_ERR exception will be thrown. Return value A Float32Array. ...
...nels, an INDEX_SIZE_ERR exception will be thrown. Return value A Float32Array. Example In the following example we create a two second buffer, fill it with white noise, and then play it via an AudioBufferSourceNode. The comments should clearly explain what is going on. You can also run the code live, or view the source. ...
...tton'); var pre = document.querySelector('pre'); var myScript = document.querySelector('script'); pre.innerHTML = myScript.innerHTML; // Stereo var channels = 2; // Create an empty two second stereo buffer at the // sample rate of the AudioContext var frameCount = audioCtx.sampleRate * 2.0; var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate); button.onclick = function
() { // Fill the buffer with white noise; //just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // This gives us the actual ArrayBuffer that contains the data var nowBuffering = myArrayBuffer.getChannelData(channel); for (var i = 0; i < frameCount; i++) { // Math.random
() is in [0; 1.0] // audio needs to be in [-1.0; 1.0] nowBu...
...And 3 more matches
AudioContext.createMediaElementSource() - Web APIs
The createMediaElementSource
() method of the AudioContext Interface is used to create a new MediaElementAudioSourceNode object, given an existing HTML <audio> or <video> element, the audio from which can then be played and manipulated. For more details about media element audio source nodes, check out the MediaElementAudioSourceNode reference page. Syntax var audioCtx = new AudioContext
(); var source = audioCtx.createMediaElementSource(myMediaElement); Parameters myMediaElement An HTMLMediaElement object that you want to feed into an audio processing graph to manipulate. Returns A MediaElementAudioSourceNode. ...
...ceNode reference page. Syntax var audioCtx = new AudioContext
(); var source = audioCtx.createMediaElementSource(myMediaElement); Parameters myMediaElement An HTMLMediaElement object that you want to feed into an audio processing graph to manipulate. Returns A MediaElementAudioSourceNode. Example This simple example creates a source from an <audio> element using createMediaElementSource
(), then passes the audio through a GainNode before feeding it into the AudioDestinationNode for playback. When the mouse pointer is moved, the updatePage
() function is invoked, which calculates the current gain as a ratio of mouse Y position divided by overall window height. You can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. Note: You ...
...oved, the updatePage
() function is invoked, which calculates the current gain as a ratio of mouse Y position divided by overall window height. You can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. Note: You can also view this example running live, or view the source. ...
...And 3 more matches
AudioParam.linearRampToValueAtTime() - Web APIs
The change starts at the time specified for the previous event, follows a linear ramp to the new value given in the value parameter, and reaches the new value at the time given in the endTime parameter. Syntax var AudioParam = AudioParam.linearRampToValueAtTime(value, endTime) Parameters value A floating point number representing the value the AudioParam will ramp to by the given time. endTime A double representing the exact time (in seconds) after the ramping starts that the changing of the value will stop. Returns A reference to this AudioParam object. ...
...onds) after the ramping starts that the changing of the value will stop. Returns A reference to this AudioParam object. In some browsers older implementations of this interface return void. ...
...rface return void. Example In this example, we have a media source with two control buttons (see the audio-param repo for the source code, or view the example live.) When these buttons are pressed, linearRampToValueAtTime
() is used to fade the gain value up to 1.0, and down to 0, respectively. This is pretty useful for fade in/fade out effects, although AudioParam.exponentialRampToValueAtTime
() is often said to be a bit more natural. ...
...And 3 more matches
BaseAudioContext.createBufferSource() - Web APIs
The createBufferSource
() method of the BaseAudioContext Interface is used to create a new AudioBufferSourceNode, which can be used to play audio data contained within an AudioBuffer object. AudioBuffers are created using BaseAudioContext.createBuffer or returned by BaseAudioContext.decodeAudioData when it successfully decodes an audio track. Syntax var source = baseAudioContext.createBufferSource
(); Returns An AudioBufferSourceNode. Example In this example, we create a two second buffer, fill it with white noise, and then play it via an AudioBufferSourceNode. The comments should clearly explain what is going on. Note: You can also run the code live, or view the source. ...
...source = baseAudioContext.createBufferSource
(); Returns An AudioBufferSourceNode. Example In this example, we create a two second buffer, fill it with white noise, and then play it via an AudioBufferSourceNode. The comments should clearly explain what is going on. Note: You can also run the code live, or view the source. ...
...tton'); var pre = document.querySelector('pre'); var myScript = document.querySelector('script'); pre.innerHTML = myScript.innerHTML; // Stereo var channels = 2; // Create an empty two second stereo buffer at the // sample rate of the AudioContext var frameCount = audioCtx.sampleRate * 2.0; var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate); button.onclick = function
() { // Fill the buffer with white noise; //just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // This gives us the actual ArrayBuffer that contains the data var nowBuffering = myArrayBuffer.getChannelData(channel); for (var i = 0; i < frameCount; i++) { // Math.random
() is in [0; 1.0] // audio needs to be in [-1.0; 1.0] nowBu...
...And 3 more matches
BaseAudioContext.createConvolver() - Web APIs
Example The following example shows basic usage of an AudioContext to create a convolver node. The basic premise is that you create an AudioBuffer containing a sound sample to be used as an ambience to shape the convolution (called the impulse response,) and apply that to the convolver. The example below uses a short sample of a concert hall crowd, so the reverb effect applied is really deep and echoey. ...
...as an ambience to shape the convolution (called the impulse response,) and apply that to the convolver. The example below uses a short sample of a concert hall crowd, so the reverb effect applied is really deep and echoey. For applied examples/information, check out our Voice-change-O-matic demo (see app.js for relevant code). ...
...led the impulse response,) and apply that to the convolver. The example below uses a short sample of a concert hall crowd, so the reverb effect applied is really deep and echoey. For applied examples/information, check out our Voice-change-O-matic demo (see app.js for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)
(); var convolver = audioCtx.createConvolver
(); ... ...
...And 3 more matches
BaseAudioContext.createGain() - Web APIs
Example The following example shows basic usage of an AudioContext to create a GainNode, which is then used to mute and unmute the audio when a Mute button is clicked by changing the gain property value. ...
... Example The following example shows basic usage of an AudioContext to create a GainNode, which is then used to mute and unmute the audio when a Mute button is clicked by changing the gain property value. ...
...ntext to create a GainNode, which is then used to mute and unmute the audio when a Mute button is clicked by changing the gain property value. ...
...And 3 more matches
BaseAudioContext.createScriptProcessor() - Web APIs
Note: As of the August 29 2014 Web Audio API spec publication, this feature has been marked as deprecated, and was replaced by AudioWorklet (see AudioWorkletNode). Syntax var scriptProcessor = audioCtx.createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels); Parameters bufferSize The buffer size in units of sample-frames. If specified, the bufferSize must be one of the following values: 256, 512, 1024, 2048, 4096, 8192, 16384. ...
...es of up to 32 are supported. Important: Webkit currently (version 31) requires that a valid bufferSize be passed when calling this method. Note: It is invalid for both numberOfInputChannels and numberOfOutputChannels to be zero. Returns A ScriptProcessorNode. Example The following example shows basic usage of a ScriptProcessorNode to take a track loaded via AudioContext.decodeAudioData
(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the AudioDestinationNode. For each channel and each sample frame, the scriptNode.onaudioprocess function takes the associated audioProcessingEvent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before s...
...se, before setting that result to be the output sample in each case. ...
...And 3 more matches
Cache.match() - Web APIs
If no match is found, the Promise resolves to undefined. Syntax cache.match(request, {options}).then(function(response) { // Do something with the response }); Parameters request The Request for which you are attempting to find responses in the Cache. This can be a Request object or a URL. options Optional An object that sets options for the match operation. The available options are: ignoreSearch: A Boolean that specifies whether to ignore the query string in the URL. For example, if set to true the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. It defaults to false. ...
...to false. ignoreVary: A Boolean that when set to true tells the matching operation not to perform VARY header matching -- i.e. if the URL matches you will get a match regardless of whether the Response object has a VARY header. It defaults to false. Return value A Promise that resolves to the first Response that matches the request or to undefined if no match is found. ...
... set to true tells the matching operation not to perform VARY header matching -- i.e. if the URL matches you will get a match regardless of whether the Response object has a VARY header. It defaults to false. Return value A Promise that resolves to the first Response that matches the request or to undefined if no match is found. ...
...And 3 more matches
CacheStorage.match() - Web APIs
Syntax caches.match(request, options).then(function(response) { // Do something with the response }); Parameters request The Request you want to match. This can be a Request object or a URL string. ...
... Syntax caches.match(request, options).then(function(response) { // Do something with the response }); Parameters request The Request you want to match. This can be a Request object or a URL string. ...
...ge interface checks if a given Request or url string is a key for a stored Response. This method returns a Promise for a Response, or a Promise which resolves to undefined if no match is found. You can access CacheStorage through the global caches property. Cache objects are searched in creation order. Note: caches.match
() is a convenience method. Equivalent functionality is to call cache.match
() on each cache (in the order returned by caches.keys
()) until a Response is returned. Syntax caches.match(request, options).then(function(response) { // Do something with the response }); Parameters request The Request you want to match. This can be a Request object or a URL string. options Optional An object whose properties control how matching is done in the match operation. The a...
...And 3 more matches
CanvasRenderingContext2D.arc() - Web APIs
The path starts at startAngle, ends at endAngle, and travels in the direction given by anticlockwise (defaulting to clockwise). Parameters x The horizontal coordinate of the arc's center. y The vertical coordinate of the arc's center. radius The arc's radius. Must be positive. startAngle The angle at which the arc starts in radians, measured from the positive x-axis. endAngle The angle at which the arc ends in radians, measured from the positive x-axis. ...
...at which the arc starts in radians, measured from the positive x-axis. endAngle The angle at which the arc ends in radians, measured from the positive x-axis. anticlockwise Optional An optional Boolean. If true, draws the arc counter-clockwise between the start and end angles. The default is false (clockwise). ...
...cle This example draws a complete circle with the arc
() method. HTML <canvas></canvas> JavaScript The arc is given an x-coordinate of 100, a y-coordinate of 75, and a radius of 50. To make a full circle, the arc begins at an angle of 0 radians (0?), and ends at an angle of 2? radians (360?). const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath
(); ctx.arc(100, 75, 50, 0, 2 * Math.PI); ctx.stroke
(); Result Different shapes demonstrated This example draws various shapes to show what is possible with arc
(). HTML <canvas width="150" height="200"></canvas> JavaScript const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); // Draw shapes for (let i = 0; i <= 3; i++) { for (let j = 0; j <= 2; j++) { ...
...And 3 more matches
CanvasRenderingContext2D.lineTo() - Web APIs
HTML <canvas id="canvas"></canvas> JavaScript The line begins at (30, 50) and ends at (150, 100). ...
... HTML <canvas id="canvas"></canvas> JavaScript The line begins at (30, 50) and ends at (150, 100). ...
... HTML <canvas id="canvas"></canvas> JavaScript The line begins at (30, 50) and ends at (150, 100). ...
...And 3 more matches
CanvasRenderingContext2D.putImageData() - Web APIs
Syntax void ctx.putImageData(imageData, dx, dy); void ctx.putImageData(imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight); Parameters imageData An ImageData object containing the array of pixel values. ...
... Syntax void ctx.putImageData(imageData, dx, dy); void ctx.putImageData(imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight); Parameters imageData An ImageData object containing the array of pixel values. ...
... Syntax void ctx.putImageData(imageData, dx, dy); void ctx.putImageData(imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight); Parameters imageData An ImageData object containing the array of pixel values. ...
...And 3 more matches
CanvasRenderingContext2D.setLineDash() - Web APIs
It uses an array of values that specify alternating lengths of lines and gaps which describe the pattern. Note: To return to using solid lines, set the line dash list to an empty array. Syntax ctx.setLineDash(segments); Parameters segments An Array of numbers that specify distances to alternately draw a line and a gap (in coordinate space units). If the number of elements in the array is odd, the elements of the array get copied and concatenated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. If the array is empty, the line dash list is cleared and line strokes return to being solid. Return value undefined. ...
...nately draw a line and a gap (in coordinate space units). If the number of elements in the array is odd, the elements of the array get copied and concatenated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. If the array is empty, the line dash list is cleared and line strokes return to being solid. Return value undefined. ...
.... If the array is empty, the line dash list is cleared and line strokes return to being solid. Return value undefined. Examples Basic example This example uses the setLineDash
() method to draw a dashed line above a solid line. ...
...And 3 more matches
CanvasRenderingContext2D.stroke() - Web APIs
The CanvasRenderingContext2D.stroke
() method of the Canvas 2D API strokes (outlines) the current or given path with the current stroke style. Strokes are aligned to the center of a path; in other words, half of the stroke is drawn on the inner side, and half on the outer side. The stroke is drawn using the non-zero winding rule, which means that path intersections will still get filled. Syntax void ctx.stroke
(); void ctx.stroke(path); Parameters path A Path2D path to stroke. Examples A simple stroked rectangle This example creates a rectangle using the rect
() method, and then draws it to the canvas using stroke
(). HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 10, 150, 100);...
...In some cases, however, this may be the desired effect. ...
...In some cases, however, this may be the desired effect. ...
...And 3 more matches
ChildNode.after() - Web APIs
DOMString objects are inserted as equivalent Text nodes. Syntax [Throws, Unscopable] void ChildNode.after((Node or DOMString)... nodes); Parameters nodes A set of Node or DOMString objects to insert. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...Child(child); child.after("Text"); console.log(parent.outerHTML); // "<div><p></p>Text</div>" Inserting an element and text var parent = document.createElement("div"); var child = document.createElement("p"); parent.appendChild(child); var span = document.createElement("span"); child.after(span, "Text"); console.log(parent.outerHTML); // "<div><p></p><span></span>Text</div>" ChildNode.after
() is unscopable The after
() method is not scoped into the with statement. See Symbol.unscopables for more information. 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 (ar...
...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 (item.hasOwnProperty('after')) { return; } Object.defineProperty(item, 'after', { configurable: true, enumerable: true, writable: true, value: function after
() { var argArr = Array.prototype.slice.call(arguments), docFrag = document.createDocumentFragment
(); argArr.forEach(function (argItem) { var isNode = argItem instanceof Node; docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); }); this.parentNode.insertBefore(docFrag, this.nextSibling); } }); }...
...And 3 more matches
ChildNode.remove() - Web APIs
The ChildNode.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. ...
...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. ...
...s 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. ...
...And 3 more matches
DataTransferItemList.remove() - Web APIs
The DataTransferItemList.remove
() method removes the DataTransferItem at the specified index from the list. If the index is less than zero or greater than one less than the length of the list, the list will not be changed. Syntax DataTransferItemList.remove(index); Parameters index The zero-based index number of the item in the drag data list to remove. If the index doesn't correspond to an existing item in the list, the list is left unchanged. Return value undefined. Exceptions InvalidStateError The drag data store is not in read/write mode, so the item can't be removed. Example This example shows the use of the remove
() method. JavaScript function dragstart_handler(ev) { console.log("dragStart"); // Add this element's id to the drag payload so the drop handler w...
... drag payload so the drop handler will // know which element to add to its tree var dataList = ev.dataTransfer.items; dataList.add(ev.target.id, "text/plain"); // Add some other items to the drag payload dataList.add("<p>... ...
... data[i].getAsString(function (s){ console.log("... Drop: HTML = " + s); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI data[i].getAsString(function (s){ console.log("... ...
...And 3 more matches
Document.exitFullscreen() - Web APIs
Example This example causes the current document to toggle in and out of a full-screen presentation whenever the mouse button is clicked within it. ...
... Example This example causes the current document to toggle in and out of a full-screen presentation whenever the mouse button is clicked within it. ...
... Example This example causes the current document to toggle in and out of a full-screen presentation whenever the mouse button is clicked within it. ...
...And 3 more matches
Document.getElementsByTagNameNS() - Web APIs
hat when the node on which getElementsByTagName is invoked is not the document node, in fact the element.getElementsByTagNameNS method is used. To use the following example, just copy/paste it into a new file saved with the .xhtml extension. ...
...h the .xhtml extension. ...
...tml", "p"); var num = allParas.length; alert("There are " + num + " <p> elements in this document"); } function div1ParaElems
() { var div1 = document.getElementById("div1") var div1Paras = div1.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p"); var num = div1Paras.length; alert("There are " + num + " <p> elements in div1 element"); } function div2ParaElems
() { var div2 = document.getElementById("div2") var div2Paras = div2.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p"); var num = div2Paras.length; alert("There are " + num + " <p> elements in div2 element"); } </script> </head> <body style="border: solid green 3px"> <p>Some outer text</p> <p>Some outer text</p> <div id="div1" style="border: solid blue 3px"> <p>Som...
...And 3 more matches
Document.hasFocus() - Web APIs
The hasFocus
() method of the Document interface returns a Boolean value indicating whether the document or any element inside the document has focus. This method can be used to determine whether the active element in a document has focus. When viewing a document, an element with focus is always the active element in the document, but an active element does not necessarily have focus. For example, an active element within a popup window that is not the foreground doesn't have focus. Syntax var focused = document.hasFocus
(); Return value false if the active element in the document has no focus; true if the active element in the document has focus. Example This example checks whether the document has focus every 300 milliseconds. ...
...ocus. For example, an active element within a popup window that is not the foreground doesn't have focus. Syntax var focused = document.hasFocus
(); Return value false if the active element in the document has no focus; true if the active element in the document has focus. Example This example checks whether the document has focus every 300 milliseconds. To test the functionality of hasFocus
(), click on the button to open a new window, and try switching between the two pages. ...
...value false if the active element in the document has no focus; true if the active element in the document has focus. Example This example checks whether the document has focus every 300 milliseconds. To test the functionality of hasFocus
(), click on the button to open a new window, and try switching between the two pages. ...
...And 3 more matches
Element.insertAdjacentElement() - Web APIs
Syntax targetElement.insertAdjacentElement(position, element); Parameters position A DOMString representing the position relative to the targetElement; must match (case-insensitively) one of the following strings: 'beforebegin': Before the targetElement itself. 'afterbegin': Just inside the targetElement, before its first child. 'beforeend': Just inside the targetElement, after its last child. 'afterend': After the targetElement itself. element The element to be inserted into the tree. Return value The element that was inserted, or null, if the insertion failed. ...
...ified is not a recognised value. TypeError The element specified is not a valid element. Visualization of position names <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend --> Note: The beforebegin and afterend positions work only if the node is in a tree and has an element parent. ...
...nt. Visualization of position names <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend --> Note: The beforebegin and afterend positions work only if the node is in a tree and has an element parent. ...
...And 3 more matches
EventTarget.dispatchEvent() - Web APIs
Dispatches an Event at the specified EventTarget, (synchronously) invoking the affected EventListeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent
(). Syntax cancelled = !target.dispatchEvent(event) Parameter event is the Event object to be dispatched. target is used to initialize the Event.target and determine which event listeners to invoke. ...
... Exceptions Exceptions thrown by event handlers are reported as uncaught exceptions. ...
... cancelled = !target.dispatchEvent(event) Parameter event is the Event object to be dispatched. target is used to initialize the Event.target and determine which event listeners to invoke. Return Value The return value is false if event is cancelable and at least one of the event handlers which received event called Event.preventDefault
(). Otherwise it returns true. The dispatchEvent
() method throws UNSPECIFIED_EVENT_TYPE_ERR if the event's type was not specified by initializing the event before the method was called, or if the event's type is null or an empty string. Exceptions Exceptions thrown by event handlers are reported as uncaught exceptions. The event handlers run on a nested callstack; they block the caller until they complete, but exceptions do not propagate to the...
...And 3 more matches
FileSystemDirectoryEntry.createReader() - Web APIs
The FileSystemDirectoryEntry interface's method createReader
() returns a FileSystemDirectoryReader object which can be used to read the entries in the directory. Syntax directoryReader = FileSystemDirectoryEntry.createReader
(); Parameters None. Return value A FileSystemDirectoryReader object which can be used to read the directory's entries. Example This example creates a method called readDirectory
(), which fetches all of the entries in the specified FileSystemDirectoryEntry and returns them in an array. ...
...temDirectoryEntry.createReader
(); Parameters None. Return value A FileSystemDirectoryReader object which can be used to read the directory's entries. Example This example creates a method called readDirectory
(), which fetches all of the entries in the specified FileSystemDirectoryEntry and returns them in an array. ...
... Return value A FileSystemDirectoryReader object which can be used to read the directory's entries. Example This example creates a method called readDirectory
(), which fetches all of the entries in the specified FileSystemDirectoryEntry and returns them in an array. ...
...And 3 more matches
FileSystemDirectoryEntry.getDirectory() - Web APIs
Syntax FileSystemDirectoryEntry.getDirectory([path][, options][, successCallback][, errorCallback]); Parameters path Optional A USVString representing an absolute path or a path relative to the directory on which the method is called, describing which directory entry to return. Absolute paths may not be able to be used, for security reasons. ...
...urity reasons. FileError.TYPE_MISMATCH_ERR The path specified is not a directory; it's probably a file, but might be an unsupported file descriptor such as a pipe; this depends on the user agent to some extent. FileSystemFlags The options parameter is an object which is based on the FileSystemFlags dictionary; it provides flags which make it possible to adjust the behavior of the getDirectory
() method. 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 not exist prior to issuing the call. Instead, it must be possible for it to be created newly at call time. The default...
...e. Values and results The table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. Option values File/directory condition Result create exclusive false n/a[1] Path exists and matches the desired type (depending on whether the function called is getFile
() or getDirectory
() The successCallback is called with a FileSystemFileEntry if getFile
() was called or a FileSystemDirectoryEntry if getDirectory
() was called. false n/a[1] Path exists but doesn't match the desired type The errorCallback is called with an appropriate error code (if the callback was provided). true false Path exists The existing file or direct...
...And 3 more matches
FileSystemDirectoryEntry.getFile() - Web APIs
Syntax FileSystemDirectoryEntry.getFile([path][, options][, successCallback][, errorCallback]); Parameters path Optional A USVString specifying the path, relative to the directory on which the method is called, describing which file's entry to return. options Optional An object based on the FileSystemFlags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file already exists. These options are currently not useful in Web contexts. ...
...r security reasons. FileError.TYPE_MISMATCH_ERR The path specified is not a file; it's probably a directory, but might be an unsupported file descriptor such as a pipe; this depends on the user agent to some extent. FileSystemFlags The options parameter is an object which is based on the FileSystemFlags dictionary; it provides flags which make it possible to adjust the behavior of the getFile
() method. 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 not exist prior to issuing the call. Instead, it must be possible for it to be created newly at call time. The default...
...e. Values and results The table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. Option values File/directory condition Result create exclusive false n/a[1] Path exists and matches the desired type (depending on whether the function called is getFile
() or getDirectory
() The successCallback is called with a FileSystemFileEntry if getFile
() was called or a FileSystemDirectoryEntry if getDirectory
() was called. false n/a[1] Path exists but doesn't match the desired type The errorCallback is called with an appropriate error code (if the callback was provided). true false Path exists The existing file or direct...
...And 3 more matches
HTMLCanvasElement.mozFetchAsStream() - Web APIs
However, this non-standard and internal method has been removed. Syntax void canvas.mozFetchAsStream(callback, type); Parameters callback An nsIInputStreamCallback. type Optional A DOMString indicating the image format. The default type is image/png. Return value None. Examples Save to disk with mozFetchAsStream (Chrome context only) This technique also converts it to ico, however it will not work in Windows XP as WinXP cannot convert from PNG to ICO. It saves to the desktop it uses FileUtils.jsm. ...
...ng. Return value None. Examples Save to disk with mozFetchAsStream (Chrome context only) This technique also converts it to ico, however it will not work in Windows XP as WinXP cannot convert from PNG to ICO. It saves to the desktop it uses FileUtils.jsm. ...
...hrome context only) This technique also converts it to ico, however it will not work in Windows XP as WinXP cannot convert from PNG to ICO. It saves to the desktop it uses FileUtils.jsm. ...
...And 3 more matches
HTMLCanvasElement.toDataURL() - Web APIs
The returned image is in a resolution of 96 dpi. If the height or width of the canvas is 0 or larger than the maximum canvas size, the string "data:," is returned. If the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported. Chrome also supports the image/webp type. Syntax canvas.toDataURL(type, encoderOptions); Parameters type Optional A DOMString indicating the image format. The default format type is image/png. ...
...s bitmap is not origin clean; at least some of its contents have or may have been loaded from a site other than the one from which the document itself was loaded. ...
...; var lowQuality = canvas.toDataURL('image/jpeg', 0.1); Example: Dynamically change images You can use this technique in coordination with mouse events in order to dynamically change images (gray-scale vs. ...
...And 3 more matches
HTMLDialogElement.close() - Web APIs
The close
() method of the HTMLDialogElement interface closes the dialog. An optional DOMString may be passed as an argument, updating the returnValue of the the dialog. Syntax dialogInstance.close(returnValue); Parameters returnValue Optional A DOMString representing an updated value for the HTMLDialogElement.returnValue of the dialog. Return value Void. Examples The following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showModal
() method. From there you can click the Cancel button to close the dialog (via the HTMLDialogElement.close
() method), or submit the form via the submit button. <!-- Simple pop-up dialog box, containing a form --> <dialog id="favDialog"> <form method="dialog"> <section> <p...
...ption>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function
() { var updateButton = document.getElementById('updateDetails'); var cancelButton = document.getElementById('cancel'); var dialog = document.getElementById('favDialog'); dialog.returnValue = 'favAnimal'; function openCheck(dialog) { if(dialog.open) { console.log('Dialog open'); } else { console.log('Dialog closed'); } ...
... Specifications Spec...
...And 3 more matches
HTMLTableElement.insertRow() - Web APIs
Syntax var newRow = HTMLTableElement.insertRow(index); HTMLTableElement is a reference to an HTML <table> element. Parameters index Optional The row index of the new row. ...
... Syntax var newRow = HTMLTableElement.insertRow(index); HTMLTableElement is a reference to an HTML <table> element. Parameters index Optional The row index of the new row. ...
...If a table has multiple <tbody> elements, by default, the new row is inserted into the last <tbody>. To insert the row into a specific <tbody>: let specific_tbody = document.getElementById(tbody_id); let row = specific_tbody.insertRow(index) Note: insertRow
() inserts the row directly into the table. The row does not need to be appended separately as would be the case if Document.createElement
() had been used to create the new <tr> element. Syntax var newRow = HTMLTableElement.insertRow(index); HTMLTableElement is a reference to an HTML <table> element. Parameters index Optional The row index of the new row. If index is -1 or equal to the number of rows, the row is appended as the last row. If index is greater than the number of rows, an IndexSizeError exception will result. If ...
...And 3 more matches
HTMLTableRowElement.insertCell() - Web APIs
Syntax var newCell = HTMLTableRowElement.insertCell(index); HTMLTableRowElement is a reference to an HTML <tr> element. Parameters index Optional index is the cell index of the new cell. If index is -1 or equal to the number of cells, the cell is appended as the last cell in the row. ...
... Syntax var newCell = HTMLTableRowElement.insertCell(index); HTMLTableRowElement is a reference to an HTML <tr> element. Parameters index Optional index is the cell index of the new cell. If index is -1 or equal to the number of cells, the cell is appended as the last cell in the row. ...
... Syntax var newCell = HTMLTableRowElement.insertCell(index); HTMLTableRowElement is a reference to an HTML <tr> element. Parameters index Optional index is the cell index of the new cell. If index is -1 or equal to the number of cells, the cell is appended as the last cell in the row. ...
...And 3 more matches
Headers.get() - Web APIs
If the requested header doesn't exist in the Headers object, it returns null. For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names. Syntax myHeaders.get(name); Parameters name The name of the HTTP header whose values you want to retrieve from the Headers object. If the given name is not the name of an HTTP header, this method throws a TypeError. The name is case-insensitive. Returns A ByteString sequence representing the values of the retrieved header or null if this header is not set. ...
...The name of the HTTP header whose values you want to retrieve from the Headers object. If the given name is not the name of an HTTP header, this method throws a TypeError. The name is case-insensitive. Returns A ByteString sequence representing the values of the retrieved header or null if this header is not set. ...
...ethod throws a TypeError. The name is case-insensitive. Returns A ByteString sequence representing the values of the retrieved header or null if this header is not set. ...
...And 3 more matches
History.pushState() - Web APIs
Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object. The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. ...
...opy of the history entry's state object. The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState
(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage. title Most browsers currently ignore this parameter, although they may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving. url Op...
...ost browsers currently ignore this parameter, although they may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving. url Optional The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState
(), but it might attempt to load the URL later, for instance after the user restarts the browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState
() will throw an exception. If this parameter isn't specified, it's set to the document's current URL. Description In a...
...And 3 more matches
IDBCursor.advance() - Web APIs
Note: This feature is available in Web Workers. Syntax cursor.advance(count); Parameters count The number of times to move the cursor forward. Exceptions This method may raise a DOMException of one of the following types: Exception Description TransactionInactiveError This IDBCursor's transaction is inactive. TypeError The value passed into the count parameter was zero or a negative number. InvalidStateError The cursor is currently being iterated or has iterated past its end. ...
...ber. InvalidStateError The cursor is currently being iterated or has iterated past its end. Example In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through the records in the object store. Here we use cursor.advance(2) to jump 2 places forward each time, meaning that only every other result will be displayed. ...
...layed. advance
() works in a similar way to IDBCursor.continue, except that it allows you to jump multiple records at a time, not just always go onto the next record. Note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. ...
...And 3 more matches
IDBCursor.continuePrimaryKey() - Web APIs
This method is only valid for cursors coming from an index. Using it for cursors coming from an object store will throw an error. ...
...nterface advances the cursor to the to the item whose key matches the key parameter as well as whose primary key matches the primary key parameter. A typical use case, is to resume the iteration where a previous cursor has been closed, without having to compare the keys one by one. Calling this method more than once before new cursor data has been loaded - for example, calling continuePrimaryKey
() twice from the same onsuccess handler - results in an InvalidStateError being thrown on the second call because the cursor's got value flag has been unset. This method is only valid for cursors coming from an index. Using it for cursors coming from an object store will throw an error. Note: This feature is available in Web Workers. Syntax cursor.continuePrimaryKey(key, primaryKey); Parameter...
...this cursor's direction is prev or prevunique. InvalidStateError The cursor is currently being iterated or has iterated past its end. InvalidAccessError The cursor's direction is not prev or next. ...
...And 3 more matches
IDBObjectStore.deleteIndex() - Web APIs
Note that this method must be called only from a VersionChange transaction mode callback. Note that this method synchronously modifies the IDBObjectStore.indexNames property. Note: This feature is available in Web Workers. Syntax objectStore.deleteIndex(indexName); Parameters indexName The name of the existing index to remove. Return value undefined Exceptions This method may raise a DOMException of one of the following types: Exception Description InvalidStateError Occurs if the method was not called from a versionchange transaction mode callback. ...
...ex with the given name (case-sensitive) in the database. Example In the following example you can see the IDBOpenDBRequest.onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded. IDBObjectStore.createIndex is used to create new indexes on the object store, after which we delete the unneeded old indexes with deleteIndex
(). For a full working example, see our To-do Notifications app (view example live.) var db; // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); // these two event handlers act on the database being opened successfully, or not DBOpenRequest.onerror = function(event) { note.innerHTML += '<li>Error loading database.</li>'; }; DBOpenRequest.onsuccess = function(...
...handlers act on the database being opened successfully, or not DBOpenRequest.onerror = function(event) { note.innerHTML += '<li>Error loading database.</li>'; }; DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...And 3 more matches
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. ...
...king example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...xample live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...And 3 more matches
ImageCapture.getPhotoSettings() - Web APIs
imageHeight: The desired image height as an integer. The user agent selects the closest width value to this setting if it only supports discrete heights. imageWidth: The desired image width as an integer. The user agent selects the closest width value to this setting if it only supports discrete widths. ...
...ights. imageWidth: The desired image width as an integer. The user agent selects the closest width value to this setting if it only supports discrete widths. redEyeReduction: A boolean indicating whether the red-eye reduction should be used if it is available. Example The following example, extracted from Chrome's Image Capture / Photo Resolution Sample, uses the results from getPhotoSettings
() to modify the size of an input range. This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. const input = document.querySelector('input[type="range"]'); var imageCapture; navigator.mediaDevices.getUserMedia({video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream; const track = me...
...n input range. This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. ...
...And 3 more matches
MediaRecorder.start() - Web APIs
A Blob is created and the data is collected in it until the time slice period elapses or the source media ends. ...
...A Blob is created and the data is collected in it until the time slice period elapses or the source media ends. ...
...A Blob is created and the data is collected in it until the time slice period elapses or the source media ends. ...
...And 3 more matches
MediaStreamTrackAudioSourceNode() - Web APIs
Syntax audioTrackNode = new MediaStreamTrackAudioSourceNode(context, options); Parameters context An AudioContext representing the audio context you want the node to be associated with. ...
... Syntax audioTrackNode = new MediaStreamTrackAudioSourceNode(context, options); Parameters context An AudioContext representing the audio context you want the node to be associated with. ...
...is node's output. Return value A new MediaStreamTrackAudioSourceNode object representing the audio node whose media is obtained from the specified media track. Exceptions NotSupportedError The specified context is not an AudioContext. InvalidStateError The specified MediaStreamTrack isn't an audio track (that is, its kind property isn't audio. ...
...And 3 more matches
MutationObserver.observe() - Web APIs
Syntax mutationObserver.observe(target, options) Parameters target A DOM Node (which may be an Element) within the DOM tree to watch for changes, or to be the root of a subtree of nodes to be watched. ...
... Syntax mutationObserver.observe(target, options) Parameters target A DOM Node (which may be an Element) within the DOM tree to watch for changes, or to be the root of a subtree of nodes to be watched. options A MutationObserverInit object providing options that describe which DOM mutations should be reported to mutationObserver's callback. Return value undefined. ...
... all false.) The value of options.attributes is false (indicating that attribute changes are not to be monitored), but attributeOldValue is true and/or attributeFilter is present. The characterDataOldValue option is true but MutationObserverInit.characterData is false (indicating that character changes are not to be monitored). Usage notes Reusing MutationObservers You can call observe
() multiple times on the same MutationObserver to watch for changes to different parts of the DOM tree and/or different types of changes. There are some caveats to note: If you call observe
() on a node that's already being observed by the same MutationObserver, all existing observers are automatically removed from all targets being observed before the new observer is activated. If the same Mutat...
...And 3 more matches
Path2D.addPath() - Web APIs
The Path2D.addPath
() method of the Canvas 2D API adds one Path2D object to another Path2D object. Syntax void path.addPath(path [, transform]); Parameters path A Path2D path to add. transform Optional A DOMMatrix to be used as the transformation matrix for the path that is added. (Technically a DOMMatrixInit object). Examples Adding a path to an existing path This example adds one path to another. HTML <canvas id="canvas"></canvas> JavaScript First, we create two separate Path2D objects, each of which contains a rectangle made using the rect
() method. We then create a matrix using document.createElementNS
() and createSVGMatrix
(). We then add the second path to the first using addPath
(), also applying the matrix to move the second path to the right. Finally, we draw the fir...
...aScript First, we create two separate Path2D objects, each of which contains a rectangle made using the rect
() method. We then create a matrix using document.createElementNS
() and createSVGMatrix
(). We then add the second path to the first using addPath
(), also applying the matrix to move the second path to the right. Finally, we draw the first path (which now contains both rectangles) using fill
(). ...
...ument.createElementNS
() and createSVGMatrix
(). We then add the second path to the first using addPath
(), also applying the matrix to move the second path to the right. Finally, we draw the first path (which now contains both rectangles) using fill
(). ...
...And 3 more matches
performance.measure() - Web APIs
The measure's performance entry will have the following property values: entryType - set to "measure". name - set to the "name" given when the measure was created. startTime - set to the start mark timestamp. duration - set to a DOMHighResTimeStamp that is the duration of the measure (typically, the end mark timestamp minus the start mark timestamp). ...
... The measure's performance entry will have the following property values: entryType - set to "measure". name - set to the "name" given when the measure was created. startTime - set to the start mark timestamp. duration - set to a DOMHighResTimeStamp that is the duration of the measure (typically, the end mark timestamp minus the start mark timestamp). ...
... The measure's performance entry will have the following property values: entryType - set to "measure". name - set to the "name" given when the measure was created. startTime - set to the start mark timestamp. duration - set to a DOMHighResTimeStamp that is the duration of the measure (typically, the end mark timestamp minus the start mark timestamp). ...
...And 3 more matches
performance.now() - Web APIs
It used to be the same as t0 of the main context, but this was changed. In shared or service workers, the value in the worker might be higher than that of the main context because that window can be created after those workers. ...
...It used to be the same as t0 of the main context, but this was changed. In shared or service workers, the value in the worker might be higher than that of the main context because that window can be created after those workers. ...
...d the returned value by some amount in order to be less predictable. This inherently introduces a degree of inaccuracy by limiting the resolution or precision of the timer. For example, Firefox rounds the returned time to 1 millisecond increments. The precision of the returned value is subject to change if/when the security concerns are alleviated through other means. Syntax t = performance.now
(); Example const t0 = performance.now
(); doSomething
(); const t1 = performance.now
(); console.log(`Call to doSomething took ${t1 - t0} milliseconds.`); Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by performance.now
() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond p...
...And 3 more matches
PublicKeyCredential.getClientExtensionResults() - Web APIs
Note: Extensions are optional and different browsers may recognize different extensions. ...
... Note: Extensions are optional and different browsers may recognize different extensions. ...
... Note: Extensions are optional and different browsers may recognize different extensions. ...
...And 3 more matches
RTCDataChannel.close() - Web APIs
The transport layer deals with any buffered messages; the protocol layer decides whether to send them or discard them. The underlying data transport is closed. ...
...aneous. Most of the process of closing the connection is handled asynchronously; you can detect when the channel has finished closing by watching for a close event on the data channel. The sequence of events which occurs in response to this method being called: RTCDataChannel.readyState is set to "closing". A background task is established to handle the remainder of the steps below, and close
() returns to the caller. The transport layer deals with any buffered messages; the protocol layer decides whether to send them or discard them. The underlying data transport is closed. The RTCDataChannel.readyState property is set to "closed". If the transport was closed with an error, the RTCDataChannel is sent a NetworkError event. A close event is sent to the channel. In Firefox, the RTC...
... or discard them. The underlying data transport is closed. The RTCDataChannel.readyState property is set to "closed". If the transport was closed with an error, the RTCDataChannel is sent a NetworkError event. A close event is sent to the channel. In Firefox, the RTCDataChannel interface was implemented under the name DataChannel until Firefox 24, so this method was called DataChannel.close
(). ...
...And 3 more matches
RTCPeerConnection.createAnswer() - Web APIs
The answer contains information about any media already attached to the session, codecs and options supported by the browser, and any ICE candidates already gathered. The answer is delivered to the returned Promise, and should then be sent to the source of the offer to continue the negotiation process. Syntax aPromise = RTCPeerConnection.createAnswer([options]); RTCPeerConnection.createAnswer(successCallback, failureCallback[, options]); Parameters options Optional An object which contains options which customize the answer; this is based on the RTCAnswerOptions dictionary. ...
...rameters options Optional An object which contains options which customize the answer; this is based on the RTCAnswerOptions dictionary. Deprecated parameters In older code and documentation, you may see a callback-based version of this function. This has been deprecated and its use is strongly discouraged. You should update any existing code to use the Promise-based version of createAnswer
() instead. The parameters for this form of createAnswer
() are described below, to aid in updating existing code. successCallback An RTCSessionDescriptionCallback which will be passed a single RTCSessionDescription object describing the newly-created answer. failureCallback An RTCPeerConnectionErrorCallback which will be passed a single DOMException object explaining why the request to cr...
...p in mind that this is part of the signaling process, the transport layer for which is an implementation detail that's entirely up to you. In this case, a WebSocket connection is used to send a JSON message with a type field with the value "video-answer" to the other peer, carrying the answer to the device which sent the offer to connect. The contents of the object being passed to the sendToServer
() function, along with everything else in the promise fulfillment handler, depend entirely on your design pc.createAnswer
().then(function(answer) { return pc.setLocalDescription(answer); }) .then(function
() { // Send the answer to the remote peer through the signaling server. }) .catch(handleGetUserMediaError); This asks RTCPeerConnection to create and return a new answer. In our promise ha...
...And 3 more matches
Range.getBoundingClientRect() - Web APIs
The range's content <b>starts here</b> and continues on until it <b>ends here</b>. ...
...The range's content <b>starts here</b> and continues on until it <b>ends here</b>. ...
...d returns a DOMRect object that bounds the contents of the range; this is a rectangle enclosing the union of the bounding rectangles for all the elements in the range. This method is useful for determining the viewport coordinates of the cursor or selection inside a text box. See Element.getBoundingClientRect
() for details on the returned value. Syntax boundingRect = range.getBoundingClientRect
() Example HTML <div id="highlight"></div> <p>This example positions a "highlight" rectangle behind the contents of a range. The range's content <b>starts here</b> and continues on until it <b>ends here</b>. The bounding client rectangle contains everything selected in the range.</p> CSS #highlight { background: yellow; position: absolute; z-index: -1; } p { width: 200px; } JavaScrip...
...And 3 more matches
ReadableStream.tee() - Web APIs
The tee
() method of the ReadableStream interface tees the current readable stream, returning a two-element array containing the two resulting branches as new ReadableStream instances. This is useful for allowing two readers to read a stream simultaneously, perhaps at different speeds. You might do this for example in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response body cannot be consumed more than once, you'd need two copies to do this. To cancel the stream you then need to cancel both resulting branches. Teeing a stream will generally lock it for the duration, preventing other readers from locking it. Syntax var teedStreams = readableStream.tee
(); Parameters None. Return val...
...urce stream is not a ReadableStream. Examples In the following simple example, a previously-created stream is teed, then both resulting streams (contained in two members of a generated array) are passed to a function that reads the data out of the two streams and prints each stream's chunks sequentially to a different part of the UI. See Simple tee example for the full code. ...
...am. Examples In the following simple example, a previously-created stream is teed, then both resulting streams (contained in two members of a generated array) are passed to a function that reads the data out of the two streams and prints each stream's chunks sequentially to a different part of the UI. See Simple tee example for the full code. ...
...And 3 more matches
ReadableStreamDefaultController.close() - Web APIs
The close
() method of the ReadableStreamDefaultController interface closes the associated stream. Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. If you want to completely get rid of the stream and discard any enqueued chunks, you'd use ReadableStream.cancel
() or ReadableStreamDefaultReader.cancel
(). Syntax readableStreamDefaultController.close
(); Parameters None. Return value undefined. Exceptions TypeError The source object is not a ReadableStreamDefaultController. Examples In the following simple example, a custom ReadableStream is created using a constructor (see our Simple random stream example for the full code). ...
....cancel
() or ReadableStreamDefaultReader.cancel
(). Syntax readableStreamDefaultController.close
(); Parameters None. Return value undefined. Exceptions TypeError The source object is not a ReadableStreamDefaultController. Examples In the following simple example, a custom ReadableStream is created using a constructor (see our Simple random stream example for the full code). The start
() function generates a random string of text every second and enqueues it into the stream. A cancel
() function is also provided to stop the generation if ReadableStream.cancel
() is called for any reason. When a button is pressed, the generation is stopped, the stream is closed using ReadableStreamDefaultController.close
(), and another function is run, which reads the data back out of the stream. ...
...eam. A cancel
() function is also provided to stop the generation if ReadableStream.cancel
() is called for any reason. When a button is pressed, the generation is stopped, the stream is closed using ReadableStreamDefaultController.close
(), and another function is run, which reads the data back out of the stream. ...
...And 3 more matches
ReadableStreamDefaultController.enqueue() - Web APIs
The enqueue
() method of the ReadableStreamDefaultController interface enqueues a given chunk in the associated stream. Syntax readableStreamDefaultController.enqueue(chunk); Parameters chunk The chunk to enqueue. Return value undefined. Exceptions TypeError The source object is not a ReadableStreamDefaultController. Examples In the following simple example, a custom ReadableStream is created using a constructor (see our Simple random stream example for the full code). The start
() function generates a random string of text every second and enqueues it into the stream -- see controller.enqueue(string). A cancel
() function is also provided to stop the generation if ReadableStream.cancel
() is called for any reason. When a button is pressed, the generation is stopped, the stre...
...tream example for the full code). The start
() function generates a random string of text every second and enqueues it into the stream -- see controller.enqueue(string). A cancel
() function is also provided to stop the generation if ReadableStream.cancel
() is called for any reason. When a button is pressed, the generation is stopped, the stream is closed using ReadableStreamDefaultController.close
(), and another function is run, which reads the data back out of the stream. ...
...ng). A cancel
() function is also provided to stop the generation if ReadableStream.cancel
() is called for any reason. When a button is pressed, the generation is stopped, the stream is closed using ReadableStreamDefaultController.close
(), and another function is run, which reads the data back out of the stream. ...
...And 3 more matches
ReadableStreamDefaultReader.cancel() - Web APIs
The cancel
() method of the ReadableStreamDefaultReader interface cancels the stream, signaling a loss of interest in the stream by a consumer. The supplied reason argument will be given to the underlying source, which may or may not use it. Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use ReadableStreamDefaultController.close
(). Note: If the reader is active, the cancel
() method behaves the same as that for the associated stream (ReadableStream.cancel
()). Syntax var promise = readableStreamDefaultReader.cancel(reason); Par...
... a human-readable reason for the cancellation. Return value A Promise, which fulfills with the value given in the reason parameter. Exceptions TypeError The source object is not a ReadableStreamDefaultReader, or the stream has no owner. Examples In the following simple example, a previously-created custom ReadableStream is read using a ReadableStreamDefaultReader created using getReader
(). (this code is based on our Simple random stream example). Each chunk is read sequentially and output to the UI, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the UI. When the stream is done (if (done)), we run reader.cancel
() to cancel the stream, signalling that we don't need to use it any more. ...
...d on our Simple random stream example). Each chunk is read sequentially and output to the UI, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the UI. When the stream is done (if (done)), we run reader.cancel
() to cancel the stream, signalling that we don't need to use it any more. function fetchStream
() { const reader = stream.getReader
(); let charsReceived = 0; // read
() returns a promise that resolves // when a value has been received reader.read
().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) {...
...And 3 more matches
Request() - Web APIs
Syntax var myRequest = new Request(input[, init]); Parameters input Defines the resource that you wish to fetch. This can either be: A USVString containing the direct URL of the resource you want to fetch. A Request object, effectively creating a copy. Note the following behavioural updates to retain security while making the constructor less likely to throw exceptions: If this object exists on another origin to the constructor call, the Request.referrer is stripped out. If this object has a Request.mode of navigate, the mode value is converted to same-origin. init Optional An options object containing any custom settings that you want to apply to the request. ...
...rect: The redirect mode to use: follow, error, or manual. The default is follow. referrer: A USVString specifying no-referrer, client, or a URL. The default is about:client. integrity: Contains the subresource integrity value of the request (e.g., sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=). Errors Type Description TypeError Since Firefox 43, Request
() will throw a TypeError if the URL has credentials, such as http://user:password@example.com. Example In our Fetch Request example (see Fetch Request live) we create a new Request object using the constructor, then fetch it using a GlobalFetch.fetch call. Since we are fetching an image, we run Body.blob on the response to give it the proper MIME type so it will be handled properly, then cr...
...then fetch it using a GlobalFetch.fetch call. Since we are fetching an image, we run Body.blob on the response to give it the proper MIME type so it will be handled properly, then create an Object URL of it and display it in an <img> element. ...
...And 3 more matches
Selection.addRange() - Web APIs
The Selection.addRange
() method adds a Range to a Selection. Syntax selection.addRange(range); Parameters range A Range object that will be added to the Selection. Example Currently only Firefox supports multiple selection ranges, other browsers will not add new ranges to the selection if it already contains one. ...
... Currently only Firefox supports multiple selection ranges, other browsers will not add new ranges to the selection if it already contains one. ...
...selection ranges, other browsers will not add new ranges to the selection if it already contains one. ...
...And 3 more matches
SharedWorker() - Web APIs
This script must obey the same-origin policy. Note: there is disagreement among browser manufacturers about whether a data URI is of the same origin or not. Although Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 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. ...
...the document is not allowed to start workers, for example if the URL has an invalid syntax or if the same-origin policy is violated. A NetworkError is raised if the MIME type of the worker script is incorrect. It should always be text/javascript. A SyntaxError is raised if aURL cannot be parsed. ...
...y is violated. A NetworkError is raised if the MIME type of the worker script is incorrect. It should always be text/javascript. A SyntaxError is raised if aURL cannot be parsed. ...
...And 3 more matches
SpeechRecognition.abort() - Web APIs
The abort
() method of the Web Speech API stops the speech recognition service from listening to incoming audio, and doesn't attempt to return a SpeechRecognitionResult. Syntax mySpeechRecognition.abort
(); Returns Void. Parameters None. ...
...e | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new SpeechRecognition
(); var speechRecognitionList = new SpeechGrammarList
(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; var diagnostic = document.querySelector('.output'); var bg = document.querySelector('html'); document.body.onclick = function
() { recognition.start
(); console.log('Ready to receive a color command.'); } abortBtn.onclick = function
() { recogn...
... Draft ...
...And 3 more matches
SpeechRecognition.start() - Web APIs
The start
() method of the Web Speech API starts the speech recognition service listening to incoming audio with intent to recognize grammars associated with the current SpeechRecognition. Syntax mySpeechRecognition.start
(); Parameters None. Return value Void. ...
...e | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new SpeechRecognition
(); var speechRecognitionList = new SpeechGrammarList
(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; var diagnostic = document.querySelector('.output'); var bg = document.querySelector('html'); document.body.onclick = function
() { recognition.start
(); console.log('Ready to receive a color command.'); } abortBtn.onclick = function
() { recogn...
... Draft ...
...And 3 more matches
SpeechRecognition.stop() - Web APIs
The stop
() method of the Web Speech API stops the speech recognition service from listening to incoming audio, and attempts to return a SpeechRecognitionResult using the audio captured so far. Syntax mySpeechRecognition.stop
(); Returns Void. Parameters None. ...
...e | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new SpeechRecognition
(); var speechRecognitionList = new SpeechGrammarList
(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; var diagnostic = document.querySelector('.output'); var bg = document.querySelector('html'); document.body.onclick = function
() { recognition.start
(); console.log('Ready to receive a color command.'); } abortBtn.onclick = function
() { recogn...
... Draft ...
...And 3 more matches
URLSearchParams.set() - Web APIs
The set
() method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it. Note: This feature is available in Web Workers. Syntax URLSearchParams.set(name, value) Parameters name The name of the parameter to set. value The value of the parameter to set. Return value Void. Examples Let's start with a simple example: let url = new URL('https://example.com?foo=1&bar=2'); let params = new URLSearchParams(url.search.slice(1)); //Add a third parameter. ...
...e in Web Workers. Syntax URLSearchParams.set(name, value) Parameters name The name of the parameter to set. value The value of the parameter to set. Return value Void. Examples Let's start with a simple example: let url = new URL('https://example.com?foo=1&bar=2'); let params = new URLSearchParams(url.search.slice(1)); //Add a third parameter. params.set('baz', 3); params.toString
(); // "foo=1&bar=2&baz=3" Below is a real-life example demonstrating how to create a URL and set some search parameters. You can copy and paste the example in a code environment like Codepen, JSFiddle, or the multi-line JavaScript interpreter in Firefox. line #41: Comment out this line to stop dumping the search parameters to the console (debug). line #43: Dumps the generated object and i...
...e search parameters to the console (debug). line #43: Dumps the generated object and it's string representation to the console (info). line #44: Tries to automatically open a new window/tab with the generated URL (when uncommented). ...
...And 3 more matches
Window.getSelection() - Web APIs
The Window.getSelection
() method returns a Selection object representing the range of text selected by the user or the current position of the caret. Syntax selection = window.getSelection
(); Return value A Selection object. When cast to string, either by appending an empty string ("") or using Selection.toString
(), this object returns the text selected. When called on an <iframe> that is not displayed (eg. where display: none is set) Firefox will return null, whereas other browsers will return a Selection object with Selection.type set to None. ...
...Selection
(); Return value A Selection object. When cast to string, either by appending an empty string ("") or using Selection.toString
(), this object returns the text selected. When called on an <iframe> that is not displayed (eg. where display: none is set) Firefox will return null, whereas other browsers will return a Selection object with Selection.type set to None. Examples function foo
() { var selObj = window.getSelection
(); alert(selObj); var selRange = selObj.getRangeAt(0); // do stuff with the range } Notes String representation of the Selection object In JavaScript, when an object is passed to a function expecting a string (like window.alert
() or document.write
()), the object's toString
() method is called and the returned value is passed to the function. Th...
...e Selection object In JavaScript, when an object is passed to a function expecting a string (like window.alert
() or document.write
()), the object's toString
() method is called and the returned value is passed to the function. This can make the object appear to be a string when used with other functions when it is really an object with properties and methods. In the above example, selObj.toString
() is automatically called when it is passed to window.alert
(). ...
...And 3 more matches
Window.openDialog() - Web APIs
If you want the call to block until the user has closed the dialog, supply modal as a windowFeatures parameter. ...
...le differently. The optional parameters, if present, are bundled up in a JavaScript Array object and added to the newly created window as a property named window.arguments. They may be referenced in the JavaScript of the window at any time, including during the execution of a load handler. These parameters may be used, then, to pass arguments to and from the dialog window. The call to openDialog
() returns immediately. If you want the call to block until the user has closed the dialog, supply modal as a windowFeatures parameter. Note that this also means the user won't be able to interact with the opener window until he closes the modal dialog. Syntax newWindow = openDialog(url, name, features, arg1, arg2, ...) newWindow The opened window url The URL to be loaded in the newly opene...
...e user has closed the dialog, supply modal as a windowFeatures parameter. Note that this also means the user won't be able to interact with the opener window until he closes the modal dialog. Syntax newWindow = openDialog(url, name, features, arg1, arg2, ...) newWindow The opened window url The URL to be loaded in the newly opened window. name The window name (optional). See window.open
() description for detailed information. features See window.open
() for details. arg1, arg2, ... The arguments to be passed to the new window (optional). Example var win = openDialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98); Notes New features all - Initially activates (or deactivates ("all=no")) all chrome (except the behavior flags chrome, dialog and modal). These can be ...
...And 3 more matches
window.postMessage() - Web APIs
The window.postMessage
() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it. Normally, scripts on different pages are allowed to access each other if and only if the pages they originate from share the same protocol, port number, and host (also known as the "same-origin policy"). window.postMessage
() provides a controlled mechanism to securely circumvent this restriction (if used properly). Broadly, one window may obtain a reference to another (e.g., via targetWindow = window.opener), and then dispatch a MessageEvent on it with targetWindow.postMessage
(). The receiving window is then free to handle this event as needed. ...
... Syntax targetWindow.postMessage(message, targetOrigin, [transfer]); targetWindow A reference to the window that will receive the message. ...
...s the literal string "*" (indicating no preference) or as a URI. If at the time the event is scheduled to be dispatched the scheme, hostname, or port of targetWindow's document does not match that provided in targetOrigin, the event will not be dispatched; only if all three match will the event be dispatched. This mechanism provides control over where messages are sent; for example, if postMessage
() was used to transmit a password, it would be absolutely critical that this argument be a URI whose origin is the same as the intended receiver of the message containing the password, to prevent interception of the password by a malicious third party. Always provide a specific targetOrigin, not *, if you know where the other window's document should be located. Failing to provide a specific target...
...And 3 more matches
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
The microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the browser's event loop. This lets your code run without interfering with any other, potentially higher priority, code that is pending, but before the browser regains control over the execution context, potentially depending on work you need to complete. You can learn more about how to use microtasks and why you might choose to do so in our microtask guide. ...
...t is pending, but before the browser regains control over the execution context, potentially depending on work you need to complete. You can learn more about how to use microtasks and why you might choose to do so 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 microtask...
...k
() 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. ...
...And 3 more matches
XMLHttpRequest.sendAsBinary() - Web APIs
The obsolete XMLHttpRequest method sendAsBinary
() is a variant of the send
() method that sends binary data. The send
() method now supports binary data and should now be used instead. This method makes it possible to read and upload any type of file and to stringify the raw data. Warning: This method is obsolete and should not be used. You should instead simply use the send
() method, which now supports binary data in various forms. Syntax XMLHttpRequest.sendAsBinary(binaryString); Parameters binaryString A DOMString which encodes the binary content to be sent. You can create the binary string using the FileReader method readAsBinaryString
(). The string is converted to binary for transfer by removing the high-order byte of each character. Return value undefined. Polyfill Sinc...
...data in various forms. Syntax XMLHttpRequest.sendAsBinary(binaryString); Parameters binaryString A DOMString which encodes the binary content to be sent. You can create the binary string using the FileReader method readAsBinaryString
(). The string is converted to binary for transfer by removing the high-order byte of each character. Return value undefined. Polyfill Since sendAsBinary
() is an experimental feature, here is a polyfill for browsers that don't support the sendAsBinary
() method but support typed arrays. ...
... string using the FileReader method readAsBinaryString
(). The string is converted to binary for transfer by removing the high-order byte of each character. Return value undefined. Polyfill Since sendAsBinary
() is an experimental feature, here is a polyfill for browsers that don't support the sendAsBinary
() method but support typed arrays. ...
...And 3 more matches
XRSession.requestAnimationFrame() - Web APIs
The XRSession method requestAnimationFrame
(), much like the Window method of the same name, schedules a callback to be executed the next time the browser is ready to paint the session's virtual environment to the XR display. The specified callback is executed once before the next repaint; if you wish for it to be executed for the following repaint, you must call requestAnimationFrame
() again. This can be done from within the callback itself. The callback takes two parameters as inputs: an XRFrame describing the state of all tracked objects for the session, and a time stamp you can use to compute any animation updates needed. You can cancel a previously scheduled animation by calling cancelAnimationFrame
(). Note: Despite the obvious similarities between these methods and the gl...
... within the callback itself. The callback takes two parameters as inputs: an XRFrame describing the state of all tracked objects for the session, and a time stamp you can use to compute any animation updates needed. You can cancel a previously scheduled animation by calling cancelAnimationFrame
(). Note: Despite the obvious similarities between these methods and the global requestAnimationFrame
() function provided by the Window interface, you must not treat these as interchangeable. There is no guarantee that the latter will work at all while an immersive XR session is underway. Syntax requestID = xrSession.requestAnimationFrame(animationFrameCallback); Parameters animationFrameCallback A function which is called before the next repaint in order to allow you to update and rende...
...s received from the WebXR device. xrFrame An XRFrame object describing the state of the objects being tracked by the session. This can be used to obtain the poses of the viewer and the scene itself, as well as other information needed to render a frame of an AR or VR scene. Return value An integer value which serves as a unique, non-zero ID or handle you may pass to cancelAnimationFrame
() if you need to remove the pending animation frame request. Example The following example requests XRSession with "inline" mode so that it can be displayed in an HTML element (without the need for a separate AR or VR device). Note: A real application should check that the device and the User Agent support WebXR API at all and then that they both support the desired session type via XR.isSessio...
...And 3 more matches
XRSystem: isSessionSupported() - Web APIs
Otherwise, the promise resolves with false. If the no devices are available or the browser doesn't have permission to use the XR device, the promise is rejected with an appropriate DOMException. Syntax var isSupportedPromise = xr.isSessionSupported(xrSessionMode) Parameters xrSessionMode A DOMString specifying the WebXR session mode for which support is to be checked. This string must be one of inline (to present the WebXR content inline within the context of an HTML document) or immersive-vr for a fully-immersive virtual experience. ...
...ch support is to be checked. This string must be one of inline (to present the WebXR content inline within the context of an HTML document) or immersive-vr for a fully-immersive virtual experience. Return value A Promise that resolves to true if the specified session mode is supported; otherwise the promise resolves to false. ...
...therwise the promise resolves to false. Exceptions Rather than throwing true exceptions, isSessionSupported
() rejects the returned promise, passing to the rejection handler a DOMException whose name is one of the following strings. SecurityError The document's origin does not have permission to use the xr-spatial-tracking feature policy. Examples In this example, we see isSessionSupported
() used to detect whether or not the device supports VR mode by checking to see if an immersive-vr session is supported. If it is, we set up a button to read "Enter XR", to call a method onButtonClicked
(), and enable the button. If no session is already underway, we request the VR session and, if successful, set up the session in a method called onSessionStarted
(), not shown. If a session is alread...
...And 3 more matches
element() - CSS: Cascading Style Sheets
The element
() CSS function defines an <image> value generated from an arbitrary HTML element. This image is live, meaning that if the HTML element is changed, the CSS properties using the resulting value are automatically updated. A particularly useful scenario for using this would be to render an image in an HTML <canvas> element, then use that as a background. On Gecko browsers, you can use the non-standard document.mozSetImageElement
() method to change the element being used as the background for a given CSS background element. Syntax element(id) where: id The ID of an element to use as the background, specified using the HTML attribute #id on the element. Examples These examples can be viewed live in builds of Firefox that support -moz-element
(). A somewhat realis...
...ly demonstrate good design practices. <div style="width:400px; height:100px; background:-moz-element(#myBackground2);"> </div> <div style="overflow:hidden; height:0;"> <button id="myBackground2" type="button">Evil button!</button> </div> Specifications Specification Status Comment CSS Images Module Level 4The definition of 'Using Elements as Images: the element
() notation' in that specification. Working Draft Deferred from CSS3 Images. 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 And...
...ges. 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. ...
...And 3 more matches
url() - CSS: Cascading Style Sheets
The url
() CSS function is used to include a file. The parameter is an absolute URL, a relative URL, or a data URI. The url
() function can be passed as a parameter of another CSS functions, like the attr
() function. Depending on the property for which it is a value, the resource sought can be an image, font, or a stylesheet. The url
() functional notation is the value for the <url> data type. /* Simple usage */ url(https://example.com/images/myImg.jpg); url(data:image/png;base64,iRxVB0...); url(myFont.woff); url(#IDofSVGpath); /* associated properties */ background-image: url("https://mdn.mozillademos.org/files/16761/star.gif"); list-style-image: url('../images/bullet.jpg'); content: url("pdficon.jpg"); cursor: url(mycursor.cur); border-image-source: url(/media/diamonds.png); src: url('fant...
... as part of a non-shorthand multiple value */ content: url(star.svg) url(star.svg) url(star.svg) url(star.svg) url(star.svg); /* at-rules */ @document url("https://www.example.com/") { ... } @import url("https://www.example.com/style.css"); @namespace url(http://www.w3.org/1999/xhtml); Relative URLs, if used, are relative to the URL of the stylesheet (not to the URL of the web page). ...
...www.w3.org/1999/xhtml); Relative URLs, if used, are relative to the URL of the stylesheet (not to the URL of the web page). The url
() function can be included as a value for background, background-image, list-style, list-style-image, content, cursor, border, border-image, border-image-source, mask, mask-image, src as part of a @font-face block, and @counter-style/symbol In CSS Level 1, the url
() functional notation described only true URLs. In CSS Level 2, the definition of url
() was extended to describe any URI, including URNs. CSS Values and Units Level 3 returned to the narrower, initial definition. Now, url
() denotes only true <url>s. Syntax Values <string> <url> A url, which is a relative or absolute address, or pointer, to the web resource to be included, or a data uri...
...And 3 more matches
Array.prototype[@@iterator]() - JavaScript
The @@iterator method is part of The iterable protocol, that defines how to synchronously iterate over a sequence of values. 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 initial value given by the values
() iterator. By default, using arr[Symbol.iterator] will return the values
() function. ...
...perty is the same function object as the initial value of the values
() property. Syntax arr[Symbol.iterator]
() Return value The initial value given by the values
() iterator. By default, using arr[Symbol.iterator] will return the values
() function. ...
...If you have a function...
...And 3 more matches
Array.prototype.findIndex() - JavaScript
Syntax arr.findIndex(callback( element[, index[, array]] )[, thisArg]) Parameters callback A function to execute on each value in the array until the function returns true, indicating that the satisfying element was found. ...
...ndex of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test. 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. See also the find
() method, which returns the value of an array element, instead of its index. Syntax arr.findIndex(callback( element[, index[, array]] )[, thisArg]) Parameters callback A function to execute on each value in the array until the function returns true, indicating that the satisfying element was found. It takes three arguments: element The current element being processed in the array...
...ex[, array]] )[, thisArg]) Parameters callback A function to execute on each value in the array until the function returns true, indicating that the satisfying element was found. It takes three arguments: element The current element being processed in the array. index Optional The index of the current element being processed in the array. ...
...And 3 more matches
Array.prototype.flatMap() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...current element being processed in the array. indexOptional The index of the current element being processed in the array. arrayOptional The array map was called upon. thisArgOptional Value to use as this when executing callback. Return value A new array with each element being the result of the callback function and flattened to a depth of 1. ...
...ap was called upon. thisArgOptional Value to use as this when executing callback. Return value A new array with each element being the result of the callback function and flattened to a depth of 1. Description See Array.prototype.map
() for a detailed description of the callback function. The flatMap method is identical to a map followed by a call to flat of depth 1. ...
...And 3 more matches
Array.prototype.includes() - JavaScript
fromIndex Optional The position in this array at which to begin searching for valueToFind. ...
...ppropriate. 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 arr.includes(valueToFind[, fromIndex]) Parameters valueToFind The value to search for. Note: When comparing strings and characters, includes
() is case-sensitive. fromIndex Optional The position in this array at which to begin searching for valueToFind. The first element to be searched is found at fromIndex for positive values of fromIndex, or at arr.length + fromIndex for negative values of fromIndex (using the absolute value of fromIndex as the number of elements from the end of the array at which to start the search). Defaults...
...ch). Defaults to 0. Return value A Boolean which is true if the value valueToFind is found within the array (or the part of the array indicated by the index fromIndex, if specified). Values of zero are all considered to be equal, regardless of sign. (That is, -0 is considered to be equal to both 0 and +0), but false is not considered to be the same as 0. Note: Technically speaking, includes
() uses the sameValueZero algorithm to determine whether the given element is found. Examples [1, 2, 3].includes(2) // true [1, 2, 3].includes(4) // false [1, 2, 3].includes(3, 3) // false [1, 2, 3].includes(3, -1) // true [1, 2, NaN].includes(NaN) // true fromIndex is greater than or equal to the array length If fromIndex is greater than or equal to the length of the array, fals...
...And 3 more matches
Array.of() - JavaScript
Array.of(7); // [7] Array.of(1, 2, 3); // [1, 2, 3] Array(7); // array of 7 empty slots Array(1, 2, 3); // [1, 2, 3] Syntax Array.of(element0[, element1[, ...[, elementN]]]) Parameters elementN Elements used to create the array. Return value A new Array instance. ...
...ray.of(7); // [7] Array.of(1, 2, 3); // [1, 2, 3] Array(7); // array of 7 empty slots Array(1, 2, 3); // [1, 2, 3] Syntax Array.of(element0[, element1[, ...[, elementN]]]) Parameters elementN Elements used to create the array. Return value A new Array instance. Description This function is part of the ECMAScript 2015 standard. ...
... // [7] Array.of(1, 2, 3); // [1, 2, 3] Array(7); // array of 7 empty slots Array(1, 2, 3); // [1, 2, 3] Syntax Array.of(element0[, element1[, ...[, elementN]]]) Parameters elementN Elements used to create the array. Return value A new Array instance. Description This function is part of the ECMAScript 2015 standard. ...
...And 3 more matches
Date.prototype.getTimezoneOffset() - JavaScript
Description The time-zone offset is the difference, in minutes, from local time to UTC. Note that this means that the offset is positive if the local timezone is behind UTC, and negative if it is ahead. ...
... Description The time-zone offset is the difference, in minutes, from local time to UTC. Note that this means that the offset is positive if the local timezone is behind UTC, and negative if it is ahead. ...
...urned. Current Locale UTC-8 UTC UTC+3 Return Value 480 0 -180 The time zone offset returned is the one that applies for the Date that it's called on. If the host system is configured for daylight saving, the offset will change depending on the date and time that the Date represents and that daylight saving applies. ...
...And 3 more matches
Date.prototype.getYear() - JavaScript
The getYear
() method returns the year in the specified date according to local time. Because getYear
() does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the getFullYear
() method. Syntax dateObj.getYear
() Return value A number representing the year of the given date, according to local time, minus 1900. Description For years greater than or equal to 2000, the value returned by getYear
() is 100 or greater. For example, if the year is 2026, getYear
() returns 126. For years between and including 1900 and 1999, the value returned by getYear
() is between 0 and 99. For example, if the year is 1976, getYear
() returns 76. For years less than 1900, the value returned by getYear
() is less than 0. ...
... or equal to 2000, the value returned by getYear
() is 100 or greater. For example, if the year is 2026, getYear
() returns 126. For years between and including 1900 and 1999, the value returned by getYear
() is between 0 and 99. For example, if the year is 1976, getYear
() returns 76. For years less than 1900, the value returned by getYear
() is less than 0. For example, if the year is 1800, getYear
() returns -100. To take into account years before and after 2000, you should use getFullYear
() instead of getYear
() so that the year is specified in full. Backward compatibility Behavior in JavaScript 1.2 and earlier The getYear
() method returns either a 2-digit or 4-digit year: For years between and including 1900 and 1999, the value returned by getYear
() is the year minus 1900. For exampl...
...e year is specified in full. Backward compatibility Behavior in JavaScript 1.2 and earlier The getYear
() method returns either a 2-digit or 4-digit year: For years between and including 1900 and 1999, the value returned by getYear
() is the year minus 1900. For example, if the year is 1976, the value returned is 76. For years less than 1900 or greater than 1999, the value returned by getYear
() is the four-digit year. For example, if the year is 1856, the value returned is 1856. If the year is 2026, the value returned is 2026. Examples Years between 1900 and 1999 The second statement assigns the value 95 to the variable year. ...
...And 3 more matches
Date.prototype.setHours() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dateObj.setHours(hoursValue[, minutesValue[, secondsValue[, msValue]]]) Versions prior to JavaScript 1.3 dateObj.setHours(hoursValue) Parameters hoursValue Ideally, an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the datetime will be incremented by the extra hours. ...
...s provided, the datetime will be incremented by the extra milliseconds. If you specify the msValue parameter, you must also specify the minutesValue and secondsValue. Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ...
...e datetime will be incremented by the extra milliseconds. If you specify the msValue parameter, you must also specify the minutesValue and secondsValue. Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ...
...And 3 more matches
Date.prototype.setUTCHours() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dateObj.setUTCHours(hoursValue[, minutesValue[, secondsValue[, msValue]]]) Parameters hoursValue An integer between 0 and 23, representing the hour. minutesValue Optional. An integer between 0 and 59, representing the minutes. secondsValue Optional. An integer between 0 and 59, representing the seconds. ...
...Optional. A number between 0 and 999, representing the milliseconds. If you specify the msValue parameter, you must also specify the minutesValue and secondsValue. Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ...
...r between 0 and 999, representing the milliseconds. If you specify the msValue parameter, you must also specify the minutesValue and secondsValue. Return value The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. ...
...And 3 more matches
Date.prototype.toISOString() - JavaScript
Polyfill This method was standardized in ECMA-262 5th edition. ...
... (YYYY-MM-DDTHH:mm:ss.sssZ or +-YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z". 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. ...
...send us a pull request. Syntax dateObj.toISOString
() Return value A string representing the given date in the ISO 8601 format according to universal time. Polyfill This method was standardized in ECMA-262 5th edition. ...
...And 3 more matches
Date.prototype.toLocaleDateString() - JavaScript
The new locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. 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. ...
...LocaleDateString([locales [, options]]) Parameters The locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. See the Intl.DateTimeFormat
() constructor for details on these parameters and how to use them. The default value for each date-time component property is undefined, but if the weekday, year, month, day properties are all undefined, then year, month, and day are assumed to be "numeric". Return value A string representing the date portion of the given Date instance according to language-specific conventions. Performance Wh...
...ies are all undefined, then year, month, and day are assumed to be "numeric". Return value A string representing the date portion of the given Date instance according to language-specific conventions. Performance When formatting large numbers of dates, it is better to create an Intl.DateTimeFormat object and use the function provided by its format property. ...
...And 3 more matches
Date.prototype.toLocaleTimeString() - JavaScript
The new locales and options arguments let applications specify the language whose formatting conventions should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. 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. ...
...oLocaleTimeString([locales[, options]]) Parameters The locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. See the Intl.DateTimeFormat
() constructor for details on these parameters and how to use them. The default value for each date-time component property is undefined, but if the hour, minute, second properties are all undefined, then hour, minute, and second are assumed to be "numeric". Return value A string representing the time portion of the given Date instance according to language-specific conventions. Performance Whe...
... are all undefined, then hour, minute, and second are assumed to be "numeric". Return value A string representing the time portion of the given Date instance according to language-specific conventions. Performance When formatting large numbers of dates, it is better to create an Intl.DateTimeFormat object and use the function provided by its format property. ...
...And 3 more matches
Intl.Locale.prototype.maximize() - JavaScript
Description Sometimes, it is convenient to be able to identify the most likely locale language identifier subtags based on an incomplete langauage ID. The Add Likely Subtags algorithm gives us this functionality. ...
... Description Sometimes, it is convenient to be able to identify the most likely locale language identifier subtags based on an incomplete langauage ID. The Add Likely Subtags algorithm gives us this functionality. ...
... langauage ID. The Add Likely Subtags algorithm gives us this functionality. For instance, given the language ID "en", the algorithm would return "en-Latn-US", since English can only be written in the Latin script, and is most likely to be used in the United States, as it is the largest English-speaking country in the world. This functionality is provided to JavaScript programmers via the maximize
() method. maximize
() only affects the main subtags that comprise the language identifier: language, script, and region subtags. Other subtags after the "-u" in the locale indentifier are called extension subtags and are not affected by the maximize
() method. Examples of these subtags include Locale.hourCycle, Locale.calendar, and Locale.numeric. Examples Using maximize let myLocale = new Intl.Lo...
...And 3 more matches
Math.random() - JavaScript
The Math.random
() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range -- which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. Math.random
() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues
() method. Syntax Math.random
() Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). Examples Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-...
...b Crypto API instead, and more precisely the window.crypto.getRandomValues
() method. Syntax Math.random
() Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). Examples Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for Math.random
() itself) aren't exact. If extremely large bounds are chosen (253 or higher), it's possible in extremely rare cases to calculate the usually-excluded upper bound. Getting a random number between 0 (inclusive) and 1 (exclusive) function getRandom
() { return Math.random
(); } Getting a random number between two values This example returns a random number between the specified values. The return...
...bound. Getting a random number between 0 (inclusive) and 1 (exclusive) function getRandom
() { return Math.random
(); } Getting a random number between two values This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max. function getRandomArbitrary(min, max) { return Math.random
() * (max - min) + min; } Getting a random integer between two values This example returns a random integer between the specified values. The value is no lower than min (or the next integer greater than min if min isn't an integer), and is less than (but not equal to) max. ...
...And 3 more matches
Math.random() - JavaScript
The Math.random
() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range -- which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. Math.random
() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues
() method. Syntax Math.random
() Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). Examples Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-...
...b Crypto API instead, and more precisely the window.crypto.getRandomValues
() method. Syntax Math.random
() Return value A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). Examples Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for Math.random
() itself) aren't exact. If extremely large bounds are chosen (253 or higher), it's possible in extremely rare cases to calculate the usually-excluded upper bound. Getting a random number between 0 (inclusive) and 1 (exclusive) function getRandom
() { return Math.random
(); } Getting a random number between two values This example returns a random number between the specified values. The return...
...bound. Getting a random number between 0 (inclusive) and 1 (exclusive) function getRandom
() { return Math.random
(); } Getting a random number between two values This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max. function getRandomArbitrary(min, max) { return Math.random
() * (max - min) + min; } Getting a random integer between two values This example returns a random integer between the specified values. The value is no lower than min (or the next integer greater than min if min isn't an integer), and is less than (but not equal to) max. ...
...And 3 more matches
Number.prototype.toSource() - JavaScript
This method is usually called internally by JavaScript and not explicitly in web code. ...
... This method is usually called internally by JavaScript and not explicitly in web code. ...
... This method is usually called internally by JavaScript and not explicitly in web code. ...
...And 3 more matches
Object.entries() - JavaScript
If there is a need for certain ordering, then the array should be sorted first, like Object.entries(obj).sort((a, b) => b[0].localeCompare(a[0]));. 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. ...
...ute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Object.entries(obj) Parameters obj The object whose own enumerable string-keyed property [key, value] pairs are to be returned. Return value An array of the given object's own enumerable string-keyed property [key, value] pairs. ...
...bject's own enumerable string-keyed property [key, value] pairs. Description Object.entries
() returns an array whose elements are arrays corresponding to the enumerable string-keyed property [key, value] pairs found directly upon object. The ordering of the properties is the same as that given by looping over the property values of the object manually. ...
...And 3 more matches
Object.prototype.hasOwnProperty() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax obj.hasOwnProperty(prop) Parameters prop The String name or Symbol of the property to test. Return value A Boolean indicating whether or not the object has the specified property as own property. Description All descendents of Object inherit the hasOwnProperty method. ...
...thod can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check for a property in the object's prototype chain. If an Object is an Array, hasOwnProperty method can check whether an index exists. Note hasOwnProperty returns true even if the value of the property is null or undefined. ...
...operty returns true even if the value of the property is null or undefined. o = new Object
(); o.propOne = null; o.hasOwnProperty('propOne'); // returns true o.propTwo = undefined; o.hasOwnProperty('propTwo'); // returns true Examples Using hasOwnProperty to test for a property's existence The following example determines whether the o object contains a property named prop: o = new Object
(); o.hasOwnProperty('prop'); // returns false o.prop = 'exists'; o.hasOwnProperty('prop'); // returns true Direct vs. ...
...And 3 more matches
Object.prototype.propertyIsEnumerable() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax obj.propertyIsEnumerable(prop) Parameters prop The name of the property to test. Return value A Boolean indicating whether the specified property is enumerable and is the object's own property. Description Every object has a propertyIsEnumerable method. ...
...-in properties: var a = ['is enumerable']; a.propertyIsEnumerable(0); // returns true a.propertyIsEnumerable('length'); // returns false Math.propertyIsEnumerable('random'); // returns false this.propertyIsEnumerable('Math'); // returns false Direct vs. ...
... a.propertyIsEnumerable('length'); // returns false Math.propertyIsEnumerable('random'); // returns false this.propertyIsEnumerable('Math'); // returns false Direct vs. ...
...And 3 more matches
handler.construct() - JavaScript
this is bound to the handler. target The target object. ...
.... 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 p = new Proxy(target, { construct: function(target, argumentsList, newTarget) { } }); Parameters The following parameters are passed to the construct
() method. this is bound to the handler. target The target object. argumentsList The list of arguments for the constructor. newTarget The constructor that was originally called, p above. Return value The construct method must return an object. Description The handler.construct
() method is a trap for the new operator. Interceptions This trap can intercept these operations: new Proxy...
...e handler. target The target object. argumentsList The list of arguments for the constructor. newTarget The constructor that was originally called, p above. Return value The construct method must return an object. Description The handler.construct
() method is a trap for the new operator. Interceptions This trap can intercept these operations: new Proxy(...args) Reflect.construct
() Invariants If the following invariants are violated, the proxy will throw a TypeError: The result must be an Object. ...
...And 3 more matches
String.prototype.charCodeAt() - JavaScript
The charCodeAt
() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index. 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. The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than 0xFFFF) then the code unit returned will be the first part of a surrogate pair for the code point. If you want the entire code point value, use codePointAt
(). Syntax str.charCodeAt(index) Parameters index An intege...
...e pair for the code point. If you want the entire code point value, use codePointAt
(). Syntax str.charCodeAt(index) Parameters index An integer greater than or equal to 0 and less than the length of the string. If index is not a number, it defaults to 0. Return value A number representing the UTF-16 code unit value of the character at the given index. If index is out of range, charCodeAt
() returns NaN. Description Unicode code points range from 0 to 1114111 (0x10FFFF). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see the JavaScript Guide.) Note: charCodeAt
() will always return a value that is less than 65536. This is because the higher code points are represented by a pair of (lower valued) "surrogate" pseudo...
...cters which are used to comprise the real character. Because of this, in order to examine (or reproduce) the full character for individual character values of 65536 or greater, for such characters, it is necessary to retrieve not only charCodeAt(i), but also charCodeAt(i+1) (as if manipulating a string with two letters), or to use codePointAt(i) instead. See examples 2 and 3 (below). charCodeAt
() returns NaN if the given index is less than 0, or if it is equal to or greater than the length of the string. Backward compatibility: In historic versions (like JavaScript 1.2) the charCodeAt
() method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from 0 to 255. The first 0 to 127 are a direct match of the ASCII chara...
...And 3 more matches
String.prototype.codePointAt() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.codePointAt(pos) Parameters pos Position of an element in str to return the code point value from. Return value A number representing the code point value of the character at the given pos. If there is no element at pos, returns undefined. Description If there is no element at the specified position, undefined is returned. If no UTF-16 surrogate pair begins at pos, the code unit at pos is returned. ...
... code point value from. Return value A number representing the code point value of the character at the given pos. If there is no element at pos, returns undefined. Description If there is no element at the specified position, undefined is returned. If no UTF-16 surrogate pair begins at pos, the code unit at pos is returned. ...
... there is no element at the specified position, undefined is returned. If no UTF-16 surrogate pair begins at pos, the code unit at pos is returned. Polyfill The following extends Strings to include the codePointAt
() function as specified in ECMAScript 2015 for browsers without native support. ...
...And 3 more matches
String.prototype.localeCompare() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. The new locales and options arguments let applications specify the language whose sort order should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale and sort order used are entirely implementation-dependent. ...
...e string against which the referenceStr is compared. locales and options These arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation-dependent. See the Intl.Collator
() constructor for details on these parameters and how to use them. Return value A negative number if referenceStr occurs before compareString; positive if the referenceStr occurs after compareString; 0 if they are equivalent. Description Returns an integer indicating whether the referenceStr comes before, after or is equivalent to the compareString. Negative when the referenceStr occurs b...
...een browser versions) because the W3C specification only mandates negative and positive values. Some browsers may return -2 or 2, or even some other negative or positive value. Performance When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare property. ...
...And 3 more matches
String.prototype.matchAll() - JavaScript
The matchAll
() method returns an iterator of all results matching a string against a regular expression, including capturing groups. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.matchAll(regexp) Parameters regexp A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). The RegExp object must have the /g flag, otherwise a TypeError will be thrown. Return value An iterator (which is not a restartable iterable). ...
...e-examples and send us a pull request. Syntax str.matchAll(regexp) Parameters regexp A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). The RegExp object must have the /g flag, otherwise a TypeError will be thrown. Return value An iterator (which is not a restartable iterable). ...
...send us a pull request. Syntax str.matchAll(regexp) Parameters regexp A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). The RegExp object must have the /g flag, otherwise a TypeError will be thrown. Return value An iterator (which is not a restartable iterable). ...
...And 3 more matches
String.prototype.normalize() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.normalize([form]) Parameters form Optional One of "NFC", "NFD", "NFKC", or "NFKD", specifying the Unicode Normalization Form. If omitted or undefined, "NFC" is used. These values have the following meanings: "NFC" Canonical Decomposition, followed by Canonical Composition. "NFD" Canonical Decomposition. "NFKC" Compatibility Decomposition, followed by Canonical Composition. "NFKD" Compatibility Decomposition. ...
...ce the code points are different, string comparison will not treat them as equal. And since the number of code points in each version is different, they even have different lengths. let string1 = '\u00F1'; // n let string2 = '\u006E\u0303'; // n console.log(string1 === string2); // false console.log(string1.length); // 1 console.log(string2.length); // 2 The normalize
() method helps solve this problem by converting a string into a normalized form common for all sequences of code points that represent the same characters. There are two main normalization forms, one based on canonical equivalence and the other based on compatibility. Canonical equivalence normalization In Unicode, two sequences of code points have canonical equivalence if they represent the same...
... main normalization forms, one based on canonical equivalence and the other based on compatibility. Canonical equivalence normalization In Unicode, two sequences of code points have canonical equivalence if they represent the same abstract characters, and should always have the same visual appearance and behavior (for example, they should always be sorted in the same way). You can use normalize
() using the "NFD" or "NFC" arguments to produce a form of the string that will be the same for all canonically equivalent strings. In the example below we normalize two representations of the character "n": let string1 = '\u00F1'; // n let string2 = '\u006E\u0303'; // n string1 = string1.normalize('NFD'); string2 = string2.normalize('NFD'); console.log(string1 === string2); // true...
...And 3 more matches
String.prototype.slice() - JavaScript
endIndex Optional The zero-based index before which to end extraction. ...
...roject, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.slice(beginIndex[, endIndex]) Parameters beginIndex The zero-based index at which to begin extraction. If negative, it is treated as str.length + beginIndex. (For example, if beginIndex is -3 it is treated as str.length - 3.) If beginIndex is greater than or equal to str.length, slice
() returns an empty string. endIndex Optional The zero-based index before which to end extraction. The character at this index will not be included. If endIndex is omitted, slice
() extracts to the end of the string. If negative, it is treated as str.length + endIndex. (For example, if endIndex is -3 it is treated as str.length - 3.) Return value A new string containing the extracted sec...
...ptional The zero-based index before which to end extraction. The character at this index will not be included. If endIndex is omitted, slice
() extracts to the end of the string. If negative, it is treated as str.length + endIndex. (For example, if endIndex is -3 it is treated as str.length - 3.) Return value A new string containing the extracted section of the string. Description slice
() extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string. slice
() extracts up to but not including endIndex. str.slice(1, 4) extracts the second character through the fourth character (characters indexed 1, 2, and 3). As an example, str.slice(2, -1) extracts the third character through the second to last character in the string...
...And 3 more matches
String.prototype.sup() - JavaScript
The sup
() method creates a <sup> HTML element that causes a string to be displayed as superscript. Syntax str.sup
() Return value A string containing a <sup> HTML element. Description The sup
() method embeds a string in a <sup> tag: "<sup>str</sup>". ...
... The sup
() method creates a <sup> HTML element that causes a string to be displayed as superscript. Syntax str.sup
() Return value A string containing a <sup> HTML element. Description The sup
() method embeds a string in a <sup> tag: "<sup>str</sup>". ...
... The sup
() method creates a <sup> HTML element that causes a string to be displayed as superscript. Syntax str.sup
() Return value A string containing a <sup> HTML element. Description The sup
() method embeds a string in a <sup> tag: "<sup>str</sup>". ...
...And 3 more matches
String.prototype.toSource() - JavaScript
This method is usually called internally by JavaScript and not explicitly in web code. ...
... This method is usually called internally by JavaScript and not explicitly in web code. ...
... This method is usually called internally by JavaScript and not explicitly in web code. ...
...And 3 more matches
WebAssembly.Instance() constructor - JavaScript
new WebAssembly.Instance(module, importObject); Parameters module The WebAssembly.Module object to be instantiated. importObject Optional An object containing the values to be imported into the newly-created Instance, such as functions or WebAssembly.Memory objects. ...
... new WebAssembly.Instance(module, importObject); Parameters module The WebAssembly.Module object to be instantiated. importObject Optional An object containing the values to be imported into the newly-created Instance, such as functions or WebAssembly.Memory objects. ...
... WebAssembly.Module object to be instantiated. importObject Optional An object containing the values to be imported into the newly-created Instance, such as functions or WebAssembly.Memory objects. There must be one matching property for each declared import of module or else a WebAssembly.LinkError is thrown. ...
...And 3 more matches
AudioContext.suspend() - Web APIs
}); Returns A Promise that resolves with void. The promise is rejected if the context has already been closed. ...
...on of time in the audio context, temporarily halting audio hardware access and reducing CPU/battery usage in the process -- this is useful if you want an application to power down the audio hardware when it will not be using an audio context for a while. This method will cause an INVALID_STATE_ERR exception to be thrown if called on an OfflineAudioContext. ...
...dio context, temporarily halting audio hardware access and reducing CPU/battery usage in the process -- this is useful if you want an application to power down the audio hardware when it will not be using an audio context for a while. This method will cause an INVALID_STATE_ERR exception to be thrown if called on an OfflineAudioContext. Syntax var audioCtx = new AudioContext
(); audioCtx.suspend
().then(function
() { ... }); Returns A Promise that resolves with void. The promise is rejected if the context has already been closed. Example The following snippet is taken from our AudioContext states demo (see it running live.) When the suspend/resume button is clicked, the AudioContext.state is queried -- if it is running, suspend
() is called; if it is suspended, resume
() is called. In eac...
...And 2 more matches
AudioParam.exponentialRampToValueAtTime() - Web APIs
The change starts at the time specified for the previous event, follows an exponential ramp to the new value given in the value parameter, and reaches the new value at the time given in the endTime parameter. Note: Exponential ramps are considered more useful when changing frequencies or playback rates than linear ramps because of the way the human ear works. Syntax var AudioParam = AudioParam.exponentialRampToValueAtTime(value, endTime) Parameters value A floating point number representing the value the AudioParam will ramp to by the given time. ...
...s) after the ramping starts that the changing of the value will stop. Returns A reference to this AudioParam object. In some browsers older implementations of this interface return void. ...
...ontrol buttons (see the audio-param repo for the source code, or view the example live.) When these buttons are pressed, exponentialRampToValueAtTime
() is used to fade the gain value up to 1.0, and down to 0, respectively. ...
...And 2 more matches
AudioParam.setTargetAtTime() - Web APIs
This is useful for decay or release portions of ADSR envelopes. Syntax var paramRef = param.setTargetAtTime(target, startTime, timeConstant); Parameters target The value the parameter will start to transition towards at the given start time. startTime The time that the exponential transition will begin, in the same time coordinate system as AudioContext.currentTime. If it is less than or equal to AudioContext.currentTime, the parameter will start changing immediately. timeConstant The time-constant value, given in seconds, of an exponential approach to the target value. The larger this value is, the slower the transition will be. ...
...rget completely, but after each timestep of length timeConstant, the value will have approached target by another 1-e-1?63.2%1 - e^{-1} \approx 63.2%. For the complete formula (which uses a first-order linear continuous time-invariant system), check the Web Audio specification. If you absolutely need to reach the target value by a specific time, you can use AudioParam.exponentialRampToValueAtTime
(). However, for mathematical reasons, that method does not work if the current value or the target value is 0. Choosing a good timeConstant As mentioned above, the value changes exponentially, with each timeConstant bringing you another 63.2% toward the target value. You don't have to worry about reaching the target value; once you are close enough, any further changes will be imperceptible to a ...
...63.2% 2 * timeConstant 86.5% 3 * timeConstant 95.0% 4 * timeConstant 98.2% 5 * timeConstant 99.3% n * timeConstant 1-e-n1 - e^{-n} Examples In this example, we have a media source with two control buttons (see the webaudio-examples repo for the source code, or view the example live.) When these buttons are pressed, setTargetAtTime
() is used to fade the gain value up to 1.0, and down to 0, respectively, with the effect starting after 1 second, and the length of time the effect lasts being controlled by the timeConstant. // create audio context var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext
(); // set basic variables for example var myAudio = document.querySelector('audio'...
...And 2 more matches
AudioParam.setValueAtTime() - Web APIs
The new value is given in the value parameter. Syntax var AudioParam = AudioParam.setValueAtTime(value, startTime) Parameters value A floating point number representing the value the AudioParam will change to at the given time. startTime A double representing the time (in seconds) after the AudioContext was first created that the change in value will happen. A TypeError is thrown if this value is negative. Returns A reference to this AudioParam object. In some browsers older implementations of this interface return void. ...
... Returns A reference to this AudioParam object. In some browsers older implementations of this interface return void. Examples This simple example features a media element source with two control buttons (see our webaudio-examples repo for the source code, or view the example live). ...
...les repo for the source code, or view the example live). ...
...And 2 more matches
AudioParam.setValueCurveAtTime() - Web APIs
The curve is a linear interpolation between the sequence of values defined in an array of floating-point values, which are scaled to fit into the given interval starting at startTime and a specific duration. Syntax var paramRef = param.setValueCurveAtTime(values, startTime, duration); Parameters values An array of floating-point numbers representing the value curve the AudioParam will change through along the specified duration. Every value in the array must be a finite number; if any value is NaN, Infinity, or -Infinity, a TypeError exception is thrown. ...
...o match the last value in the set of values specified in the values parameter. Note: Some early implementations of the Web Audio API did not ensure this to be the case, causing unexpected results. ...
...this example, we have a media source with a single button (see the webaudio-examples repo for the source code, or view the example live.) When this button is pressed, setValueCurveAtTime
() is used to change the gain value between the values contained in the waveArray array: // create audio context var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext
(); // set basic variables for example var myAudio = document.querySelector('audio'); var pre = document.querySelector('pre'); var myScript = document.querySelector('script'); pre.innerHTML = myScript.innerHTML; var valueCurve = document.querySelector('.value-curve'); // Create a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it var source = audioCtx.createMediaElementSource(myAud...
...And 2 more matches
BaseAudioContext.createChannelMerger() - Web APIs
Syntax baseAudioContext.createChannelMerger(numberOfInputs); Parameters numberOfInputs The number of channels in the input audio streams, which the output stream will contain; the default is 6 if this parameter is not specified. Returns A ChannelMergerNode. Example The following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. ...
...Example The following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. To use them, you need to use the second and third parameters of the AudioNode.connect(AudioNode) method, which allow you to specify both the index of the channel to connect from and the index of the channel to connect to. ...
...usic), and process the left and right channel differently. To use them, you need to use the second and third parameters of the AudioNode.connect(AudioNode) method, which allow you to specify both the index of the channel to connect from and the index of the channel to connect to. ...
...And 2 more matches
BaseAudioContext.createChannelSplitter() - Web APIs
Syntax baseAudioContext.createChannelSplitter(numberOfOutputs); Parameters numberOfOutputs The number of channels in the input audio stream that you want to output separately; the default is 6 if this parameter is not specified. Returns A ChannelSplitterNode. Example The following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. ...
...ample The following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. To use them, you need to use the second and third parameters of the AudioNode.connect(AudioNode) method, which allow you to specify the index of the channel to connect from and the index of the channel to connect to. ...
... of music), and process the left and right channel differently. To use them, you need to use the second and third parameters of the AudioNode.connect(AudioNode) method, which allow you to specify the index of the channel to connect from and the index of the channel to connect to. ...
...And 2 more matches
BaseAudioContext.createDelay() - Web APIs
Syntax var delayNode = audioCtx.createDelay(maxDelayTime); Parameters maxDelayTime Optional The maximum amount of time, in seconds, that the audio signal can be delayed by. Must be less than 180 seconds, and defaults to 1 second if not specified. Returns A DelayNode. The default DelayNode.delayTime is 0 seconds. Example We have created a simple example that allows you to play three different samples on a constant loop -- see create-delay (you can also view the source code). ...
...op -- see create-delay (you can also view the source code). If you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time. ...
...ps will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time. var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext
(); var synthDelay = audioCtx.createDelay(5.0); ... ...
...And 2 more matches
Body.text() - Web APIs
The text
() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString object (text). The response is always decoded using UTF-8. Syntax response.text
().then(function (text) { // do something with the text response }); Parameters None. Return value A Promise that resolves with a USVString. Example In our fetch text example (run fetch text live), we have an <article> element and three links (stored in the myLinks array.) First, we loop through all of these and give each one an onclick event handler so that the getData
() function is run -- with the link's data-page identifier passed to it as an argument -- when one of the links is clicked. ...
...at resolves with a USVString. Example In our fetch text example (run fetch text live), we have an <article> element and three links (stored in the myLinks array.) First, we loop through all of these and give each one an onclick event handler so that the getData
() function is run -- with the link's data-page identifier passed to it as an argument -- when one of the links is clicked. When getData
() is run, we create a new request using the Request
() constructor, then use it to fetch a specific .txt file. When the fetch is successful, we read a USVString (text) object out of the response using text
(), then set the innerHTML of the <article> element equal to the text object. let myArticle = document.querySelector('article'); let myLinks = document.querySelectorAll('ul a'); for(let i = 0; i ...
...h a specific .txt file. When the fetch is successful, we read a USVString (text) object out of the response using text
(), then set the innerHTML of the <article> element equal to the text object. ...
...And 2 more matches
CSS.escape() - Web APIs
The CSS.escape
() static method returns a CSSOMString containing the escaped string passed as parameter, mostly for use as part of a CSS selector. Syntax escapedStr = CSS.escape(str); Parameters str The CSSOMString to be escaped. ...
... The CSS.escape
() static method returns a CSSOMString containing the escaped string passed as parameter, mostly for use as part of a CSS selector. Syntax escapedStr = CSS.escape(str); Parameters str The CSSOMString to be escaped. ...
...scaped. ...
...And 2 more matches
CSSStyleDeclaration.setProperty() - Web APIs
Syntax style.setProperty(propertyName, value, priority); Parameters propertyName is a DOMString representing the CSS property name (hyphen case) to be modified. value Optional is a DOMString containing the new property value. If not specified, treated as the empty string. Note: value must not contain "!important" -- that should be set using the priority parameter. priority Optional is a DOMString allowing the "important" CSS priority to be set. If not specified, treated as the empty string. ...
...eet.cssRules; for each one, we check whether its CSSStyleRule.selectorText property is equal to the selector .box p, which indicates it is the one we want. If so, we store a reference to this CSSStyleRule object in a variable. We then use three functions to generate random values for the properties in question, and update the rule with these values. ...
...ht: 150px; line-height: 150px; background: red; border: 5px solid purple; color: white; transition: all 1s; } JavaScript const borderBtn = document.querySelector('.border'); const bgColorBtn = document.querySelector('.bgcolor'); const colorBtn = document.querySelector('.color'); const box = document.querySelector('.box'); function random(min,max) { const num = Math.floor(Math.random
()*(max-min)) + min; return num; } function randomColor
() { return 'rgb(' + random(0,255) + ', ' + random(0,255) + ', ' + random(0,255) + ')'; } const stylesheet = document.styleSheets[1]; let boxParaRule; for(let i = 0; i < stylesheet.cssRules.length; i++) { if(stylesheet.cssRules[i].selectorText === '.box p') { boxParaRule = stylesheet.cssRules[i]; } } function setRandomBorder
() {...
...And 2 more matches
Cache.add() - Web APIs
This can be a Request object or a URL. Return value A Promise that resolves with undefined. ...
...This can be a Request object or a URL. Return value A Promise that resolves with undefined. ...
...This can be a Request object or a URL. Return value A Promise that resolves with undefined. ...
...And 2 more matches
Cache.addAll() - Web APIs
You can specify the Request object instead of the URL. Return value A Promise that resolves with undefined. ...
...You can specify the Request object instead of the URL. Return value A Promise that resolves with undefined. ...
...You can specify the Request object instead of the URL. Return value A Promise that resolves with undefined. ...
...And 2 more matches
CanvasRenderingContext2D.addHitRegion() - Web APIs
Canvas hit regions make hit detection easy. They let you route events to DOM elements, and make it possible for users to explore the canvas without seeing it. Syntax void ctx.addHitRegion(options); Options The options argument is optional. When provided, it is an Object which can contain the following properties: path A Path2D object describing the area of the hit region. If not provided, the current path is used. fillRule The algorithm by which to determine if a point is inside or outside the hit region. Possible values: nonzero: The non-zero winding rule. Default rule. evenodd: The even-odd winding rule. ...
...canvas) to which events are to be routed. Defaults to null. label A text label for accessibility tools to use as a description of the region, if there is no control. Defaults to null. role An ARIA role for accessibility tools to determine how to represent this region, if there is no control. Defaults to null. ...
...ere is no control. Defaults to null. Examples Using the addHitRegion method This example demonstrates the addHitRegion
() method. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); canvas.addEventListener('mousemove', function(event) { if(event.region) { alert('ouch, my eye :('); } }); ctx.beginPath
(); ctx.arc(100, 100, 75, 0, 2 * Math.PI); ctx.lineWidth = 5; ctx.stroke
(); // Eyes ctx.beginPath
(); ctx.arc(70, 80, 10, 0, 2 * Math.PI); ctx.arc(130, 80, 10, 0, 2 * Math.PI); ctx.fill
(); ctx.addHitRegion({id: "eyes"}); // Mouth ctx.beginPath
(); ctx.arc(100, 110, 50, 0, Math.PI); ctx.stroke
(); Edit the code below to see your changes update live in the canvas. (If you don't see the full smiley, c...
...And 2 more matches
CanvasRenderingContext2D.bezierCurveTo() - Web APIs
Syntax void ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); Parameters cp1x The x-axis coordinate of the first control point. cp1y The y-axis coordinate of the first control point. cp2x The x-axis coordinate of the second control point. cp2y The y-axis coordinate of the second control point. x The x-axis coordinate of the end point. y The y-axis coordinate of the end point. ...
...cubic Bezier curve is drawn. ...
...ext const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Define the points as {x, y} let start = { x: 50, y: 20 }; let cp1 = { x: 230, y: 30 }; let cp2 = { x: 150, y: 80 }; let end = { x: 250, y: 100 }; // Cubic Bezier curve ctx.beginPath
(); ctx.moveTo(start.x, start.y); ctx.bezierCurveTo(cp1.x, cp1.y, cp2.x, cp2.y, end.x, end.y); ctx.stroke
(); // Start and end points ctx.fillStyle = 'blue'; ctx.beginPath
(); ctx.arc(start.x, start.y, 5, 0, 2 * Math.PI); // Start point ctx.arc(end.x, end.y, 5, 0, 2 * Math.PI); // End point ctx.fill
(); // Control points ctx.fillStyle = 'red'; ctx.beginPath
(); ctx.arc(cp1.x, cp1.y, 5, 0, 2 * Math.PI); // Control point one ctx.arc(cp2.x, cp2.y, 5, 0, 2 * Math.PI); // Control point two ctx.fill
();...
...And 2 more matches
CanvasRenderingContext2D.ellipse() - Web APIs
The path starts at startAngle and ends at endAngle, and travels in the direction given by anticlockwise (defaulting to clockwise). Parameters x The x-axis (horizontal) coordinate of the ellipse's center. y The y-axis (vertical) coordinate of the ellipse's center. radiusX The ellipse's major-axis radius. Must be non-negative. radiusY The ellipse's minor-axis radius. Must be non-negative. ...
... Drawing a full ellipse This example draws an ellipse at an angle of ?/4 radians (45?). To make a full ellipse, the arc begins at an angle of 0 radians (0?), and ends at an angle of 2? radians (360?). HTML <canvas id="canvas" width="200" height="200"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Draw the ellipse ctx.beginPath
(); ctx.ellipse(100, 100, 50, 75, Math.PI / 4, 0, 2 * Math.PI); ctx.stroke
(); // Draw the ellipse's line of reflection ctx.beginPath
(); ctx.setLineDash([5, 5]); ctx.moveTo(0, 200); ctx.lineTo(200, 0); ctx.stroke
(); Result Various elliptical arcs This example creates three elliptical paths with varying properties. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getEl...
...e's line of reflection ctx.beginPath
(); ctx.setLineDash([5, 5]); ctx.moveTo(0, 200); ctx.lineTo(200, 0); ctx.stroke
(); Result Various elliptical arcs This example creates three elliptical paths with varying properties. ...
...And 2 more matches
CanvasRenderingContext2D.quadraticCurveTo() - Web APIs
Syntax void ctx.quadraticCurveTo(cpx, cpy, x, y); Parameters cpx The x-axis coordinate of the control point. cpy The y-axis coordinate of the control point. x The x-axis coordinate of the end point. y The y-axis coordinate of the end point. Examples How quadraticCurveTo works This example shows how a quadratic Bezier curve is drawn. ...
...is coordinate of the control point. x The x-axis coordinate of the end point. y The y-axis coordinate of the end point. Examples How quadraticCurveTo works This example shows how a quadratic Bezier curve is drawn. ...
...oint. y The y-axis coordinate of the end point. Examples How quadraticCurveTo works This example shows how a quadratic Bezier curve is drawn. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Quadratic Bezier curve ctx.beginPath
(); ctx.moveTo(50, 20); ctx.quadraticCurveTo(230, 30, 50, 100); ctx.stroke
(); // Start and end points ctx.fillStyle = 'blue'; ctx.beginPath
(); ctx.arc(50, 20, 5, 0, 2 * Math.PI); // Start point ctx.arc(50, 100, 5, 0, 2 * Math.PI); // End point ctx.fill
(); // Control point ctx.fillStyle = 'red'; ctx.beginPath
(); ctx.arc(230, 30, 5, 0, 2 * Math.PI); ctx.fill
(); Result In this example, the control point is red and the start and end points are blue. A simple quadra...
...And 2 more matches
CanvasRenderingContext2D.resetTransform() - Web APIs
The CanvasRenderingContext2D.resetTransform
() method of the Canvas 2D API resets the current transform to the identity matrix. Syntax void ctx.resetTransform
(); Examples Resetting the matrix This example draws a rotated rectangle after modifying the matrix, and then resets the matrix using the resetTransform
() method. HTML <canvas id="canvas"></canvas> JavaScript The rotate
() method rotates the transformation matrix by 45?. The fillRect
() method draws a filled rectangle, adjusted according to that matrix. ...
...In this example, the first two shapes are drawn with a skew transformation, and the last two are drawn with the identity (regular) transformation. ...
...ng to that matrix. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Draw a rotated rectangle ctx.rotate(45 * Math.PI / 180); ctx.fillRect(60, 0, 100, 30); // Reset transformation matrix to the identity matrix ctx.resetTransform
(); Result Continuing with a regular matrix Whenever you're done drawing transformed shapes, you should call resetTransform
() before rendering anything else. In this example, the first two shapes are drawn with a skew transformation, and the last two are drawn with the identity (regular) transformation. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Skewed rectangles ctx.transform(1, 0, 1.7, 1, 0, 0); ctx.fillStyle = 'gray'; c...
...And 2 more matches
CanvasRenderingContext2D.save() - Web APIs
The CanvasRenderingContext2D.save
() method of the Canvas 2D API saves the entire state of the canvas by pushing the current state onto a stack. The drawing state The drawing state that gets saved onto a stack consists of: The current transformation matrix. The current clipping region. The current dash list. The current values of the following attributes: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled. ...
...e current transformation matrix. The current clipping region. The current dash list. The current values of the following attributes: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled. ...
... current dash list. The current values of the following attributes: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled. ...
...And 2 more matches
CanvasRenderingContext2D.strokeRect() - Web APIs
Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. ...
... Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. ...
... Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. ...
...And 2 more matches
ChildNode.replaceWith() - Web APIs
The ChildNode.replaceWith
() method replaces this ChildNode in the children list of its parent with a set of Node or DOMString objects. DOMString objects are inserted as equivalent Text nodes. Syntax [Throws, Unscopable] void ChildNode.replaceWith((Node or DOMString)... nodes); Parameters nodes A set of Node or DOMString objects to replace. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...its parent with a set of Node or DOMString objects. DOMString objects are inserted as equivalent Text nodes. Syntax [Throws, Unscopable] void ChildNode.replaceWith((Node or DOMString)... nodes); Parameters nodes A set of Node or DOMString objects to replace. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. Examples Using replaceWith
() var parent = document.createElement("div"); var child = document.createElement("p"); parent.appendChild(child); var span = document.createElement("span"); child.replaceWith(span); console.log(parent.outerHTML); // "<div><span></span></div>" ChildNode.replaceWith
() is unscopable The replaceWith
() method is not scoped into the with statement. See Symbol.unscopables for more information. with...
...= 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. ...
...And 2 more matches
CustomEvent.initCustomEvent() - Web APIs
The page on Creating and triggering events gives more information about the way to use those. ...
...The page on Creating and triggering events gives more information about the way to use those. ...
...The page on Creating and triggering events gives more information about the way to use those. ...
...And 2 more matches
DOMImplementation.createHTMLDocument() - Web APIs
The DOMImplementation.createHTMLDocument
() method creates a new HTML Document. Syntax const newDoc = document.implementation.createHTMLDocument(title) Parameters title Optional (except in IE) A DOMString containing the title to give the new HTML document. Example This example creates a new HTML document and inserts it into an <iframe> in the current document. ...
... new HTML Document. Syntax const newDoc = document.implementation.createHTMLDocument(title) Parameters title Optional (except in IE) A DOMString containing the title to give the new HTML document. Example This example creates a new HTML document and inserts it into an <iframe> in the current document. ...
... the title to give the new HTML document. Example This example creates a new HTML document and inserts it into an <iframe> in the current document. ...
...And 2 more matches
DataTransferItemList.add() - Web APIs
The item may be a File or a string of a given type. If the item is successfully added to the list, the newly-created DataTransferItem object is returned. Syntax DataTransferItem = DataTransferItemList.add(data, type); DataTransferItem = DataTransferItemList.add(file); Parameters data A string representing the drag item's data. type A string of the drag item's type. Some example types are text/html and text/plain. file A File object. No type needs to be given in this case. Return value A DataTransferItem containing the specified data. ...
... the specified data. If the drag item couldn't be created (for example, if the associated DataTransfer object has no data store), null is returned. Exceptions NotSupportedError A string data parameter was provided, and the list already contains an item whose kind is "Plain Unicode string" and whose type is equal to the specified type parameter. Example This example shows the use of the add
() method. HTML <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div> CSS div { margin: 0em; padding: 2em; } #source { ...
... drag payload so the drop handler will // know which element to add to its tree var dataList = ev.dataTransfer.items; dataList.add(ev.target.id, "text/plain"); // Add some other items to the drag payload dataList.add("<p>... ...
...And 2 more matches
Document.createElementNS() - Web APIs
Syntax var element = document.createElementNS(namespaceURI, qualifiedName[, options]); Parameters namespaceURI A string that specifies the namespace URI to associate with the element. The namespaceURI property of the created element is initialized with the value of namespaceURI. See Valid Namespace URIs. qualifiedName A string that specifies the type of element to be created. The nodeName property of the created element is initialized with the value of qualifiedName. ...
...mespaceURI. See Valid Namespace URIs. qualifiedName A string that specifies the type of element to be created. The nodeName property of the created element is initialized with the value of qualifiedName. optionsOptional An optional ElementCreationOptions object containing a single property named is, whose value is the tag name for a custom element previously defined using customElements.define
(). For backwards compatibility with previous versions of the Custom Elements specification, some browsers will allow you to pass a string here instead of an object, where the string's value is the custom element's tag name. See Extending native HTML elements for more information on how to use this parameter. The new element will be given an is attribute whose value is the custom element's tag name...
...mespace and appends it to the vbox element. ...
...And 2 more matches
Document.createProcessingInstruction() - Web APIs
The new node usually will be inserted into an XML document in order to accomplish anything with it, such as with node.insertBefore. Syntax piNode = document.createProcessingInstruction(target, data) Parameters piNode is the resulting ProcessingInstruction node. target is a string containing the first part of the processing instruction (i.e., <?target ... ?>) data is a string containing any information the processing instruction should carry, after the target. The data is up to you, but it can't contain ?>, since that closes the processing instruction. ...
...ceptions DOM_INVALID_CHARACTER Throws if either of the following are true: The processing instruction target is invalid -- it should be a valid XML name that doesn't contain "xml", "XML", or any case combination of the two, other than standardized ones such as <?xml-stylesheet ?>. The closing processing instruction sequence (?>) is part of the data. ...
...tion of the two, other than standardized ones such as <?xml-stylesheet ?>. The closing processing instruction sequence (?>) is part of the data. Example var doc = new DOMParser
().parseFromString('<foo />', 'application/xml'); var pi = doc.createProcessingInstruction('xml-stylesheet', 'href="mycss.css" type="text/css"'); doc.insertBefore(pi, doc.firstChild); console.log(new XMLSerializer
().serializeToString(doc)); // Displays: <?xml-stylesheet href="mycss.css" type="text/css"?><foo/> Specifications Specification Status Comment DOMThe definition of 'createProcessingInstruction
()' in that specification. Living Standard No change DOM4The definition of 'createProcessingInstruction
()' in that specification. Obsolete Added more explicit...
...And 2 more matches
Document.querySelectorAll() - Web APIs
Syntax elementList = parentNode.querySelectorAll(selectors); Parameters selectors A DOMString containing one or more selectors to match against. This string must be a valid CSS selector string; if it's not, a SyntaxError exception is thrown. See Locating DOM elements using selectors for more information about using selectors to identify elements. Multiple selectors may be specified by separating them using commas. ...
...If the array is empty (that is, its length property is 0), then no matches were found. Otherwise, you can simply use standard array notation to access the contents of the list. You can use any common looping statement, such as: var highlightedItems = userList.querySelectorAll(".highlighted"); highlightedItems.forEach(function(userItem) { deleteUser(userItem); }); User notes querySelectorAll
() behaves differently than most common JavaScript DOM libraries, which might lead to unexpected results. HTML Consider this HTML, with its three nested <div> blocks. <div class="outer"> <div class="select"> <div class="inner"> </div> </div> </div> JavaScript var select = document.querySelector('.select'); var inner = select.querySelectorAll('.outer .inner'); inner.length; // 1, not...
...lect = document.querySelector('.select'); var inner = select.querySelectorAll('.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 ...
...And 2 more matches
DocumentOrShadowRoot.elementFromPoint() - Web APIs
If the element at the specified point belongs to another document (for example, the document of an <iframe>), that document's parent element is returned (the <iframe> itself). If the element at the given point is anonymous or XBL generated content, such as a textbox's scroll bars, then the first non-anonymous ancestor element (for example, the textbox) is returned. Elements with pointer-events set to none will be ignored, and the element below it will be returned. ...
...w it will be returned. If the method is run on another document (like an <iframe>'s subdocument), the coordinates are relative to the document where the method is being called. If the specified point is outside the visible bounds of the document or either coordinate is negative, the result is null. If you need to find the specific position inside the element, use Document.caretPositionFromPoint
(). Syntax const element = document.elementFromPoint(x, y) Parameters x The horizontal coordinate of a point, relative to the left edge of the current viewport. y The vertical coordinate of a point, relative to the top edge of the current viewport. Return value The topmost Element object located at the specified coordinates. Example This example creates two buttons which let you set th...
...o the top edge of the current viewport. Return value The topmost Element object located at the specified coordinates. Example This example creates two buttons which let you set the current color of the paragraph element located under the coordinates (2, 2). JavaScript function changeColor(newColor) { elem = document.elementFromPoint(2, 2); elem.style.color = newColor; } The changeColor
() method simply obtains the element located at the specified point, then sets that element's current foreground color property to the color specified by the newColor parameter. HTML <p id="para1">Some text here</p> <button onclick="changeColor('blue');">Blue</button> <button onclick="changeColor('red');">Red</button> The HTML provides the paragraph whose color will be affected, as well as two b...
...And 2 more matches
DocumentOrShadowRoot.elementsFromPoint() - Web APIs
Syntax const elements = document.elementsFromPoint(x, y); Parameters x The horizontal coordinate of a point. y The vertical coordinate of a point. Return value An array of element objects. ...
... Syntax const elements = document.elementsFromPoint(x, y); Parameters x The horizontal coordinate of a point. y The vertical coordinate of a point. Return value An array of element objects. ...
... Working Draft ...
...And 2 more matches
Element.computedStyleMap() - Web APIs
The computedStyleMap
() method of the Element interface returns a StylePropertyMapReadOnly interface which provides a read-only representation of a CSS declaration block that is an alternative to CSSStyleDeclaration. Syntax var stylePropertyMapReadOnly = Element.computedStyleMap
() Parameters None. Return value A StylePropertyMapReadOnly interface. Examples We start with some simple HTML: a paragraph with a link, and a definition list to which we will add all the CSS Property / Value pairs. <p> <a href="https://example.com">Link</a> </p> <dl id="regurgitation"></dl> We add a little bit of CSS a { --colour: red; color: var(--colour); } We add JavaScript to grab our link and return back a definition list of all the CSS property values using computedStyleMap
(). // get the ...
...f CSS a { --colour: red; color: var(--colour); } We add JavaScript to grab our link and return back a definition list of all the CSS property values using computedStyleMap
(). ...
...We add JavaScript to grab our link and return back a definition list of all the CSS property values using computedStyleMap
(). ...
...And 2 more matches
Element.getAttributeNS() - Web APIs
If the named attribute does not exist, the value returned will either be null or "" (the empty string); see Notes for details. Syntax attrVal = element.getAttributeNS(namespace, name) Parameters namespace The namespace in which to look for the specified attribute. name The name of the attribute to look for. Return value The string value of the specified attribute. If the attribute doesn't exist, the result is null. Note: Earlier versions of the DOM specification had this method described as returning an empty string for non-existent attributes, but it was not typically implemented this way since null makes more sense. ...
...ke="#444" stroke-width="2" fill="none" test:foo="Foo value"/> </svg> <script type="text/javascript"> var ns = 'http://www.example.com/2014/test'; var circle = document.getElementById( 'target' ); console.log('Attribute value: ' + circle.getAttribute('test:foo')); </script> </body> </html> Notes Namespaces are only supported in XML documents. HTML5 documents have to use getAttribute
() instead. getAttributeNS
() differs from getAttribute
() in that it allows you to further specify the requested attribute as being part of a particular namespace, as in the example above, where the attribute is part of the fictional "specialspace" namespace on Mozilla. Prior to the DOM4 specification, this method was specified to return an empty string rather than null for non-existent attributes.
... part of the fictional "specialspace" namespace on Mozilla. Prior to the DOM4 specification, this method was specified to return an empty string rather than null for non-existent attributes. However, most browsers instead returned null. Starting with DOM4, the specification now says to return null. However, some older browsers return an empty string. For that reason, you should use hasAttributeNS
() to check for an attribute's existence prior to calling getAttributeNS
() if it is possible that the requested attribute does not exist on the specified element. DOM methods dealing with element's attributes: Not namespace-aware, most commonly used methods Namespace-aware variants (DOM Level 2) DOM Level 1 methods for dealing with Attr nodes directly (seldom used) DOM Level 2 namespace-aware me...
...And 2 more matches
Element.getElementsByTagName() - Web APIs
The Element.getElementsByTagName
() method returns a live HTMLCollection of elements with the given tag name. All descendants of the specified element are searched, but not the element itself. The returned list is live, which means it updates itself with the DOM tree automatically. Therefore, there is no need to call Element.getElementsByTagName
() with the same element and arguments repeatedly if the DOM changes in between calls. When called on an HTML element in an HTML document, getElementsByTagName lower-cases the argument before searching for it. This is undesirable when trying to match camel-cased SVG elements (such as <linearGradient>) in an HTML document. Instead, use Element.getElementsByTagNameNS
(), which preserves the capitalization of the tag name. Element.getElementsByTagName i...
...ed on an HTML element in an HTML document, getElementsByTagName lower-cases the argument before searching for it. This is undesirable when trying to match camel-cased SVG elements (such as <linearGradient>) in an HTML document. Instead, use Element.getElementsByTagNameNS
(), which preserves the capitalization of the tag name. Element.getElementsByTagName is similar to Document.getElementsByTagName
(), except that it only searches for elements that are descendants of the specified element. Syntax elements = element.getElementsByTagName(tagName) elements is a live HTMLCollection of elements with a matching tag name, in the order they appear. If no elements are found, the HTMLCollection is empty. element is the element from where the search starts. Only the element's descendants are includ...
... Obsolete No change from Document Object Model (DOM) Level 2 Core Specification Document Object Model (DOM) Level 2 Core SpecificationThe definit...
...And 2 more matches
Element.hasAttributes() - Web APIs
Living Standard Moved from the Node interface to the more specialized Element interface. ...
... Living Standard Moved from the Node interface to the more specialized Element interface. ...
... Living Standard Moved from the Node interface to the more specialized Element interface. ...
...And 2 more matches
Element.insertAdjacentText() - Web APIs
Syntax element.insertAdjacentText(position, element); Parameters position A DOMString representing the position relative to the element; must be one of the following strings: 'beforebegin': Before the element itself. 'afterbegin': Just inside the element, before its first child. 'beforeend': Just inside the element, after its last child. 'afterend': After the element itself. element A DOMString representing the text to be inserted into the tree. Return value Void. Exceptions Exception Explanation SyntaxError The position specified is not a recognised value. ...
...ception Explanation SyntaxError The position specified is not a recognised value. Visualization of position names <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend --> Note: The beforebegin and afterend positions work only if the node is in a tree and has an element parent. Example beforeBtn.addEventListener('click', function
() { para.insertAdjacentText('afterbegin',textInput.value); }); afterBtn.addEventListener('click', function
() { para.insertAdjacentText('beforeend',textInput.value); }); Have a look at our insertAdjacentText.html demo on GitHub (see the source code too.) Here we have a simple paragraph. You can enter some text into the form element, then press the Insert before and Insert after buttons to inse...
...addEventListener('click', function
() { para.insertAdjacentText('beforeend',textInput.value); }); Have a look at our insertAdjacentText.html demo on GitHub (see the source code too.) Here we have a simple paragraph. You can enter some text into the form element, then press the Insert before and Insert after buttons to insert it before or after the existing paragraph text using insertAdjacentText
(). Note that the existing text node is not added to -- further text nodes are created containing the new additions. ...
...And 2 more matches
Element.querySelectorAll() - Web APIs
Syntax elementList = parentNode.querySelectorAll(selectors); Parameters selectors A DOMString containing one or more selectors to match against. This string must be a valid CSS selector string; if it's not, a SyntaxError exception is thrown. See Locating DOM elements using selectors for more information about using selectors to identify elements. Multiple selectors may be specified by separating them using commas. ...
...ist. You can use any common looping statement, such as: var highlightedItems = userList.querySelectorAll(".highlighted"); highlightedItems.forEach(function(userItem) { deleteUser(userItem); }); Note: NodeList is not a genuine array, that is to say it doesn't have the array methods like slice, some, map etc. To convert it into an array, try Array.from(nodeList). User notes querySelectorAll
() behaves differently than most common JavaScript DOM libraries, which might lead to unexpected results. HTML Consider this HTML, with its three nested <div> blocks. <div class="outer"> <div class="select"> <div class="inner"> </div> </div> </div> JavaScript var select = document.querySelector('.select'); var inner = select.querySelectorAll('.outer .inner'); inner.length; // 1, not...
...ocument.querySelector('.select'); var inner = select.querySelectorAll('.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 DO...
...And 2 more matches
Event.composedPath() - Web APIs
Return value An array of EventTarget objects representing the objects on which an event listener will be invoked. Examples In our composed-composed-path example (see it live), we define two trivial custom elements, <open-shadow> and <closed-shadow>, both of which take the contents of their text attribute and insert them into the element's shadow DOM as the text content of a <p> element. ...
...of which take the contents of their text attribute and insert them into the element's shadow DOM as the text content of a <p> element. The only difference between the two is that their shadow roots are attached with their modes set to open and closed respectively. ...
...e contents of their text attribute and insert them into the element's shadow DOM as the text content of a <p> element. The only difference between the two is that their shadow roots are attached with their modes set to open and closed respectively. ...
...And 2 more matches
ExtendableEvent.waitUntil() - Web APIs
The ExtendableEvent.waitUntil
() method tells the event dispatcher that work is ongoing. It can also be used to detect whether that work was successful. In service workers, waitUntil
() tells the browser that work is ongoing until the promise settles, and it shouldn't terminate the service worker if it wants that work to complete. The install events in service workers use waitUntil
() to hold the service worker in the installing phase until tasks complete. If the promise passed to waitUntil
() rejects, the install is considered a failure, and the installing service worker is discarded. This is primarily used to ensure that a service worker is not considered installed until all of the core caches it depends on are successfully populated. ...
... service worker in the installing phase until tasks complete. If the promise passed to waitUntil
() rejects, the install is considered a failure, and the installing service worker is discarded. This is primarily used to ensure that a service worker is not considered installed until all of the core caches it depends on are successfully populated. The activate events in service workers use waitUntil
() to buffer functional events such as fetch and push until the promise passed to waitUntil
() settles. This gives the service worker time to update database schemas and delete outdated caches, so other events can rely on a completely upgraded state. ...
...d installed until all of the core caches it depends on are successfully populated. The activate events in service workers use waitUntil
() to buffer functional events such as fetch and push until the promise passed to waitUntil
() settles. This gives the service worker time to update database schemas and delete outdated caches, so other events can rely on a completely upgraded state. The waitUntil
() method must be initially called within the event callback, but after that it can be called multiple times, until all the promises passed to it settle. Note: The behaviour described in the above paragraph was fixed in Firefox 43 (see bug 1180274). ...
...And 2 more matches
FetchEvent.respondWith() - Web APIs
In most cases you can provide any response that the receiver understands. For example, if an <img> initiates the request, the response body needs to be image data. For security reasons, there are a few global rules: You can only return Response objects of type "opaque" if the fetchEvent.request object's mode is "no-cors". This prevents the leaking of private data. You can only return Response objects of type "opaqueredirect" if the fetchEvent.request object's mode is "manual". You cannot return Response objects of type "cors" if the fetchEvent.request object's mode is "same-origin". ...
...is prevents the leaking of private data. You can only return Response objects of type "opaqueredirect" if the fetchEvent.request object's mode is "manual". You cannot return Response objects of type "cors" if the fetchEvent.request object's mode is "same-origin". Specifying the final URL of a resource From Firefox 59 onwards, when a service worker provides a Response to FetchEvent.respondWith
(), the Response.url value will be propagated to the intercepted network request as the final resolved URL. If the Response.url value is the empty string, then the FetchEvent.request.url is used as the final URL. In the past the FetchEvent.request.url was used as the final URL in all cases. The provided Response.url was effectively ignored. This means, for example, if a service worker intercepts...
...rl value is the empty string, then the FetchEvent.request.url is used as the final URL. In the past the FetchEvent.request.url was used as the final URL in all cases. The provided Response.url was effectively ignored. This means, for example, if a service worker intercepts a stylesheet or worker script, then the provided Response.url will be used to resolve any relative @import or importScripts
() subresource loads (bug 1222008). For most types of network request this change has no impact because you can't observe the final URL. There are a few, though, where it does matter: If a fetch
() is intercepted, then you can observe the final URL on the result's Response.url. If a worker script is intercepted, then the final URL is used to set self.location and used as the base URL for relati...
...And 2 more matches
FileSystemFileEntry.createWriter() - Web APIs
The FileSystemFileEntry interface's method createWriter
() returns a FileWriter object which can be used to write data into the file represented by the directory entry. Syntax FileSystemFileEntry.createWriter(successCallback[, errorCallback]); Parameters successCallback A callback function which is called when the FileWriter has been created successfully; the FileWriter is passed into the callback as the only parameter. errorCallback Optional If provided, this must be a method which is caled when an error occurs while trying to create the FileWriter. This callback receives as input a FileError object describing the error. Return value undefined. ...
...Writer has been created successfully; the FileWriter is passed into the callback as the only parameter. errorCallback Optional If provided, this must be a method which is caled when an error occurs while trying to create the FileWriter. This callback receives as input a FileError object describing the error. Return value undefined. ...
...This blob is then output to the FileWriter object to be written to the file. This API has no official W3C or WHATWG specification. Browser compatibility The compatibility table on this page is generated from structured data. ...
...And 2 more matches
FileSystemFileEntry.file() - Web APIs
The FileSystemFileEntry interface's method file
() returns a File object which can be used to read data from the file represented by the directory entry. Syntax FileSystemFileEntry.file(successCallback[, errorCallback]); Parameters successCallback A callback function which is called when the File has been created successfully; the File is passed into the callback as the only parameter. errorCallback Optional If provided, this must be a method which is called when an error occurs while trying to create the File. This callback receives as input a FileError object describing the error. Editor's note: We need to find out what kinds of errors can occur and document them. Return value undefined. ...
...lback as the only parameter. errorCallback Optional If provided, this must be a method which is called when an error occurs while trying to create the File. This callback receives as input a FileError object describing the error. Editor's note: We need to find out what kinds of errors can occur and document them. Return value undefined. ...
...turn value undefined. Example This example establishes a method, readFile
(), reads a text file and calls a specified callback function with the received text (in a String object) once the read is completed. If an error occurs, a specified (optional) error callback is called. function readFile(entry, successCallback, errorCallback) { entry.file(function(file) { let reader = new FileReader
(); reader.onload = function
() { successCallback(reader.result); }; reader.onerror = function
() { errorCallback(reader.error); } reader.readAsText(file); }, errorCallback); } This function calls file
(), specifying as its success callback a method which proceeds to use a FileReader to read the file as text. The FileReader's load event handler is set up to delive...
...And 2 more matches
Audio() - Web APIs
Syntax audioObj = new Audio(url); Parameters url Optional An optional DOMString containing the URL of an audio file to be associated with the new audio element. Return value A new HTMLAudioElement object, configured to be used for playing back the audio from the file specified by url.The new object's preload property is set to auto and its src property is set to the specified URL or null if no URL is given. If a URL is specified, the browser begins to asynchronously load the media resource before returning the new object. ...
...g back the audio from the file specified by url.The new object's preload property is set to auto and its src property is set to the specified URL or null if no URL is given. If a URL is specified, the browser begins to asynchronously load the media resource before returning the new object. Usage notes You can also use other element-creation methods, such as the document object's createElement
() method, to construct a new HTMLAudioElement. Determining when playback can begin There are three ways you can tell when enough of the audio file has loaded to allow playback to begin: Check the value of the readyState property. If it's HTMLMediaElement.HAVE_FUTURE_DATA, there's enough data available to begin playback and play for at least a short time. If it's HTMLMediaElement.HAVE_ENOUGH_DA...
...enough audio available to begin playback, although interruptions may occur). Listen for the canplaythrough event. It is sent when it's estimated that the audio should be able to play to the end without interruption. ...
...And 2 more matches
HTMLImageElement.decode() - Web APIs
Return value A Promise which is resolved once the image data is ready to be used. Exceptions EncodingError A DOMException indicating that an error occurred while decoding the image. ...
...OM. This can be used to initiate loading of the image prior to attaching it to an element in the DOM (or adding it to the DOM as a new element), so that the image can be rendered immediately upon being added to the DOM. This, in turn, prevents the rendering of the next frame after adding the image to the DOM from causing a delay while the image loads. ...
... the next frame after adding the image to the DOM from causing a delay while the image loads. Syntax var promise = HTMLImageElement.decode
(); Parameters None. Return value A Promise which is resolved once the image data is ready to be used. Exceptions EncodingError A DOMException indicating that an error occurred while decoding the image. Usage notes One potential use case for decode
(): when loading very large images (for example, in an online photo album), you can present a low resolution thumbnail image initially and then replace that image with the full-resolution image by instantiating a new HTMLImageElement, setting its source to the full-resolution image's URL, then using decode
() to get a promise which is resolved once the full-resolution image is ready for use. At that ...
...And 2 more matches
Headers.append() - Web APIs
For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names. Syntax myHeaders.append(name, value); Parameters name The name of the HTTP header you want to add to the Headers object. value The value of the HTTP header you want to add. Returns Void. ...
...be controlled by the user agent. These headers include the forbidden header names and forbidden response header names. Syntax myHeaders.append(name, value); Parameters name The name of the HTTP header you want to add to the Headers object. value The value of the HTTP header you want to add. Returns Void. ...
...n header names and forbidden response header names. Syntax myHeaders.append(name, value); Parameters name The name of the HTTP header you want to add to the Headers object. value The value of the HTTP header you want to add. Returns Void. ...
...And 2 more matches
IDBDatabase.transaction() - Web APIs
urrently experimental, and can only be used if the dom.indexedDB.experimental pref is set to true in about:config. details Optional Dictionary of other settings, supported only by Chrome: Return value An IDBTransaction object. Exceptions This method may raise a DOMException of one of the following types: Exception Description InvalidStateError The close
() method has previously been called on this IDBDatabase instance. NotFoundError An object store specified in in the storeNames parameter has been deleted or removed. TypeError The value for the mode parameter is invalid. InvalidAccessError The function was called with an empty list of store names. Example In this example we open a database conne...
... called on this IDBDatabase instance. NotFoundError An object store specified in in the storeNames parameter has been deleted or removed. TypeError The value for the mode parameter is invalid. InvalidAccessError The function was called with an empty list of store names. Example In this example we open a database connection, then use transaction
() to open a transaction on the database. For a complete example, see our To-do Notifications app (view example live.) var db; // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. // This is used a l...
... see our To-do Notifications app (view example live.) var db; // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...And 2 more matches
IDBFactory.deleteDatabase() - Web APIs
Note: This feature is available in Web Workers. ...
...nDBRequest object immediately, and performs the deletion operation asynchronously. If the database is successfully deleted, then a success event is fired on the request object returned from this method, with its result set to undefined. If an error occurs while the database is being deleted, then an error event is fired on the request object that is returned from this method. When deleteDatabase
() is called, any other open connections to this particular database will get a versionchange event. Note: This feature is available in Web Workers. Syntax For the current standard: var request = indexedDB.deleteDatabase(name); For the experimental version with options (see below): var request = indexedDB.deleteDatabase(name, options); Parameters name The name of the database you want to ...
...kers. Syntax For the current standard: var request = indexedDB.deleteDatabase(name); For the experimental version with options (see below): var request = indexedDB.deleteDatabase(name, options); Parameters name The name of the database you want to delete. Note that attempting to delete a database that doesn't exist does not throw an exception, in contrast to IDBDatabase.deleteObjectStore
(), which does throw an exception if the named object store does not exist. optionsNon-standard In Gecko, since version 26, you can include a non-standard optional storage parameter that specifies whether you want to delete a permanent (the default value) IndexedDB, or an indexedDB in temporary storage (aka shared pool.) Return value A IDBOpenDBRequest on which subsequent events related to this...
...And 2 more matches
IDBIndex.get() - Web APIs
If a value is found, then a structured clone of it is created and set as the result of the request object: this returns the record the key is associated with. Note: This feature is available in Web Workers. Syntax var request = myIndex.get(key); Parameters key Optional A key or IDBKeyRange that identifies the record to be retrieved. If this value is null or missing, the browser will use an unbound key range. Return value An IDBRequest object on which subsequent events related to this operation are fired. ...
..., not the primary key. myIndex.get('Bungle') is then used to retrieve the record with an lName of Bungle, and the result of that request is logged to the console when its success callback returns. Finally, we iterate through each record, and insert the data into an HTML table. ...
...or a complete working example, see our IDBIndex-example demo repo (View the example live.) function displayDataByIndex
() { tableEntry.innerHTML = ''; var transaction = db.transaction(['contactsList'], 'readonly'); var objectStore = transaction.objectStore('contactsList'); var myIndex = objectStore.index('lName'); var getRequest = myIndex.get('Bungle'); getRequest.onsuccess = function
() { console.log(getRequest.result); } myIndex.openCursor
().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tableRow = document.createElement('tr'); tableRow.innerHTML = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lName + '</td>' + '<td>' + cursor.value.fName + '</td>'...
...And 2 more matches
IDBIndex.getKey() - Web APIs
If a primary key is found, it is set as the result of the request object. Note that this doesn't return the whole record as IDBIndex.get does. Note: This feature is available in Web Workers. Syntax var request = myIndex.getKey(key); Parameters key Optional A key or IDBKeyRange that identifies a record to be retrieved. If this value is null or missing, the browser will use an unbound key range. Return value An IDBRequest object on which subsequent events related to this operation are fired. ...
... myIndex.getKey('Bungle') is then used to retrieve the primary key of the record with an lName of Bungle, and the result of that request is logged to the console when its success callback returns. Finally, we iterate through each record, and insert the data into an HTML table. ...
...lete working example, see our IDBIndex-example demo repo (View the example live.) function displayDataByIndex
() { tableEntry.innerHTML = ''; var transaction = db.transaction(['contactsList'], 'readonly'); var objectStore = transaction.objectStore('contactsList'); var myIndex = objectStore.index('lName'); var getKeyRequest = myIndex.getKey('Bungle'); getKeyRequest.onsuccess = function
() { console.log(getKeyRequest.result); } myIndex.openCursor
().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tableRow = document.createElement('tr'); tableRow.innerHTML = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lName + '</td>' + '<td>' + cursor.value.fName + '</t...
...And 2 more matches
IDBObjectStore.clear() - Web APIs
The clear
() method of the IDBObjectStore interface creates and immediately returns an IDBRequest object, and clears this object store in a separate thread. This is for deleting all the current data out of an object store. Clearing an object store consists of removing all records from the object store and removing all records in indexes that reference the object store. To remove only some of the records in a store, use IDBObjectStore.delete passing a key or IDBKeyRange. Note: This feature is available in Web Workers. Syntax var request = objectStore.clear
(); Returns An IDBRequest object on which subsequent events related to this operation are fired. Exceptions This method may raise a DOMException of one of the following types: Exception Description ReadOnl...
...lowing types: Exception Description ReadOnlyError The transaction associated with this operation is in read-only mode. TransactionInactiveError This IDBObjectStore's transaction is inactive. Example In the following code snippet, we open a read/write transaction on our database and clear all the current data out of the object store using clear
(). For a full working example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. // This is used a lot below db = DBOpenRequest.result; //...
...ions app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...And 2 more matches
IDBObjectStore.createIndex() - Web APIs
It creates a new field/column defining a new data point for each database record to contain. Bear in mind that IndexedDB indexes can contain any JavaScript data type; IndexedDB uses the structured clone algorithm to serialize stored objects, which allows for storage of simple and complex objects. Note that this method must be called only from a VersionChange transaction mode callback. Note: This feature is available in Web Workers. Syntax var myIDBIndex = objectStore.createIndex(indexName, keyPath); var myIDBIndex = objectStore.createIndex(indexName, keyPath, objectParameters); Parameters indexName The name of the index to create. ...
...ve (e.g. has been deleted or removed.) In Firefox previous to version 41, an InvalidStateError was raised in this case as well, which was misleading; this has now been fixed (see bug 1176165.) Example In the following example you can see the IDBOpenDBRequest.onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded. createIndex
() is used to create new indexes on the object store. For a full working example, see our To-do Notifications app (view example live.) var db; // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); // Two event handlers for opening the database. DBOpenRequest.onerror = function(event) { note.innerHTML += '<li>Error loading database.</li>'; }; DBOpenRequest.onsuc...
... 4); // Two event handlers for opening the database. DBOpenRequest.onerror = function(event) { note.innerHTML += '<li>Error loading database.</li>'; }; DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. // This is used a lot below. db = request.result; // Run the displayData
() function to populate the task list with // all the to-do list data already in the IDB displayData
(); }; // This handler fires when a new database is created and indicates // either that one has not been created before, or a new version // was submitted with window.indexedDB.open
(). (See above.) // It is only implemented in recent browsers. DBOpenRequest.onupgradeneeded = function(event) { ...
...And 2 more matches
IDBObjectStore.index() - Web APIs
Note: This feature is available in Web Workers. Syntax var index = objectStore.index(name); Parameters name The name of the index to open. Return value An IDBIndex object for accessing the index. Exceptions This method may raise a DOMException of one of the following types: Exception Description InvalidStateError The source object store has been deleted, or the transaction for the object store has finished. NotFoundError There is no index with the given name (case-sensitive) in the database. ...
...openCursor -- this works the same as opening a cursor directly on an ObjectStore using IDBObjectStore.openCursor except that the returned records are sorted based on the index, not the primary key. Finally, we iterate through each record, and insert the data into an HTML table. ...
... each record, and insert the data into an HTML table. ...
...And 2 more matches
IDBTransaction.commit() - Web APIs
Return value Void. Exceptions Exception Description InvalidStateError The transaction state is not active. ...
... Return value Void. Exceptions Exception Description InvalidStateError The transaction state is not active. ...
... Return value Void. Exceptions Exception Description InvalidStateError The transaction state is not active. ...
...And 2 more matches
ImageCapture.grabFrame() - Web APIs
The grabFrame
() method of the ImageCapture interface takes a snapshot of the live video in a MediaStreamTrack and returns a Promise that resolves with a ImageBitmap containing the snapshot. Syntax const bitmapPromise = imageCapture.grabFrame
() Return value A Promise that resolves to an ImageBitmap object. Example This example is extracted from this Simple Image Capture demo. It shows how to use the Promise returned by grabFrame
() to copy the returned frame to a <canvas> element. For simplicy it does not show how to instantiate the ImageCapture object. ...
...s extracted from this Simple Image Capture demo. It shows how to use the Promise returned by grabFrame
() to copy the returned frame to a <canvas> element. For simplicy it does not show how to instantiate the ImageCapture object. ...
...Image Capture demo. It shows how to use the Promise returned by grabFrame
() to copy the returned frame to a <canvas> element. For simplicy it does not show how to instantiate the ImageCapture object. ...
...And 2 more matches
MediaStreamAudioSourceNode() - Web APIs
Syntax audioSourceNode = new MediaStreamAudioSourceNode(context, options); Parameters context An AudioContext representing the audio context you want the node to be associated with. ...
... Syntax audioSourceNode = new MediaStreamAudioSourceNode(context, options); Parameters context An AudioContext representing the audio context you want the node to be associated with. ...
...de to have: mediaStream A required property which specifies the MediaStream from which to obtain audio for the node. Return value A new MediaStreamAudioSourceNode object representing the audio node whose media is obtained from the specified source stream. Exceptions InvalidStateError The specified MediaStream doesn't have any audio tracks. ...
...And 2 more matches
Node.cloneNode() - Web APIs
deep Optional* If true, then node and its whole subtree--including text that may be in child Text nodes--is also copied. If false, only node will be cloned. Any text that node contains is not cloned, either (since text is contained by one or more child Text nodes). deep has no effect on empty elements (such as the <img> and <input> elements). ...
... deep Optional* If true, then node and its whole subtree--including text that may be in child Text nodes--is also copied. If false, only node will be cloned. Any text that node contains is not cloned, either (since text is contained by one or more child Text nodes). deep has no effect on empty elements (such as the <img> and <input> elements). ...
...gument. Starting with Gecko 29.0 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26)), a shallow clone is defaulted instead of a deep clone. Example let p = document.getElementById("para1") let p_prime = p.cloneNode(true) Notes Cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners. It does not copy event listeners added using addEventListener
() or those assigned to element properties (e.g., node.onclick = someFunction). Additionally, for a <canvas> element, the painted image is not copied. Warning: cloneNode
() may lead to duplicate element IDs in a document! If the original node has an id attribute, and the clone will be placed in the same document, then you should modify the clone's ID to be unique. Name attributes may need to be m...
...And 2 more matches
Node.getRootNode() - Web APIs
The getRootNode
() method of the Node interface returns the context object's root, which optionally includes the shadow root if it is available. Syntax var root = node.getRootNode(options); Parameters options Optional An object that sets options for getting the root node. The available options are: composed: A Boolean that indicates whether the shadow root should be returned (false, the default), or a root node beyond shadow root (true). Returns An object inheriting from Node. This will differ in exact form depending on where you called getRootNode
(); for example: Calling it on an element inside a standard web page will return an HTMLDocument object representing the entire page. Calling it on an element inside a shadow DOM will return the associated ShadowRoot. Exampl...
...ill differ in exact form depending on where you called getRootNode
(); for example: Calling it on an element inside a standard web page will return an HTMLDocument object representing the entire page. Calling it on an element inside a shadow DOM will return the associated ShadowRoot. Examples The first simple example returns a reference to the HTML/document node: rootNode = node.getRootNode
(); This more complex example shows the difference between returning a normal root, and a root incuding the shadow root. ...
...nside a shadow DOM will return the associated ShadowRoot. Examples The first simple example returns a reference to the HTML/document node: rootNode = node.getRootNode
(); This more complex example shows the difference between returning a normal root, and a root incuding the shadow root. ...
...And 2 more matches
NodeFilter.acceptNode() - Web APIs
The NodeFilter.acceptNode
() method returns an unsigned short that will be used to tell if a given Node must be accepted or not by the NodeIterator or TreeWalker iteration algorithm. This method is expected to be written by the user of a NodeFilter. Possible return values are: Constant Description NodeFilter.FILTER_ACCEPT Value returned by the NodeFilter.acceptNode
() method when a node should be accepted. NodeFilter.FILTER_REJECT Value to be returned by the NodeFilter.acceptNode
() method when a node should be rejected. The children of rejected nodes are not visited by the NodeIterator or TreeWalker object; this value is treated as "skip this node and all its children". ...
...The children of skipped nodes are still considered. This is treated as "skip this node but not its children". ...
.... The function should return NodeFilter.FILTER_ACCEPT, which causes the TreeWalker to return the node, NodeFilter.FILTER_REJECT, which causes the TreeWalker to ignore the entire subtree, or NodeFilter.FILTER_SKIP. The browser doesn't provide any object implementing this method. It is the user who is expected to write an object implementing the NodeFilter interface, tailoring the acceptNode
() method to its needs, and using it with some TreeWalker or NodeIterator objects. Syntax result = nodeFilter.acceptNode(node) Parameters node Is a Node being the object to check against the filter. Example var nodeIterator = document.createNodeIterator( // Node to use as root document.getElementById('someId'), // Only consider nodes that are text nodes (nodeType 3) NodeFilter.SH...
...And 2 more matches
ParentNode.prepend() - Web APIs
DOMString objects are inserted as equivalent Text nodes. Syntax ParentNode.prepend(...nodesToPrepend); Parameters nodesToPrepend One or more nodes to insert before the first child node currently in the ParentNode. Each node can be specified as either a Node object or as a string; strings are inserted as new Text nodes. Return value undefined. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...t var parent = document.createElement("div"); parent.append("Some text"); parent.prepend("Headline: "); console.log(parent.textContent); // "Headline: Some text" Appending an element and text var parent = document.createElement("div"); var p = document.createElement("p"); parent.prepend("Some text", p); console.log(parent.childNodes); // NodeList [ #text "Some text", <p> ] ParentNode.prepend
() is unscopable The prepend
() method is not scoped into the with statement. See Symbol.unscopables for more information. 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
()/...
...copable The prepend
() method is not scoped into the with statement. See Symbol.unscopables for more information. ...
...And 2 more matches
ParentNode.replaceChildren() - Web APIs
The ParentNode.replaceChildren
() method replaces the existing children of a Node with a specified new set of children. These can be DOMString or Node objects. Syntax // [Throws, Unscopable] ParentNode.replaceChildren(...nodesOrDOMStrings) // returns undefined Parameters nodesOrDOMStrings A set of Node or DOMString objects to replace the ParentNode's existing children with. If no replacement objects are specified, then the ParentNode is emptied of all child nodes. Exceptions HierarchyRequestError: The constraints of the node tree are violated. Examples Emptying a node replaceChildren
() provides a very convenient mechanism for emptying a node of all its children. ...
...th. If no replacement objects are specified, then the ParentNode is emptied of all child nodes. Exceptions HierarchyRequestError: The constraints of the node tree are violated. Examples Emptying a node replaceChildren
() provides a very convenient mechanism for emptying a node of all its children. You simply call it on the parent node without any argument specified: myNode.replaceChildren
(); Transferring nodes between parents replaceChildren
() enables you to easily transfer nodes between parents, without having to resort to verbose looping code. For example, say we have a simple application allowing you to choose what food you want for your party. This HTML might look something like this: <h2>Party food option list</h2> <main> <div> <label for="no">No thanks!</label> ...
... when the "yes" button is pressed, and transfer any selected options in the "yes" list over to the "no" list when the "no" button is pressed. To do this, we give each of the buttons a click event handler, which collects together the selected options you want to transfer in one constant, and the existing options in the list you are transferring to in another constant. ...
...And 2 more matches
PaymentRequest.abort() - Web APIs
The PaymentRequest.abort
() method of the PaymentRequest interface causes the user agent to end the payment request and to remove any user interface that might be shown. Syntax PaymentRequest.abort
(); Returns Void. Parameters None Examples The following example sets up a timeout to clear the payment request that might have been abandoned or neglected. ...
... user agent to end the payment request and to remove any user interface that might be shown. Syntax PaymentRequest.abort
(); Returns Void. Parameters None Examples The following example sets up a timeout to clear the payment request that might have been abandoned or neglected. ...
...interface that might be shown. Syntax PaymentRequest.abort
(); Returns Void. Parameters None Examples The following example sets up a timeout to clear the payment request that might have been abandoned or neglected. var request = new PaymentRequest(supportedInstruments, details, options); var paymentTimeout = window.setTimeout(
() => { window.clearTimeout(paymentTimeout); request.abort
().then(
() => { print('Payment timed out after 20 minutes.'); }).catch(
() => { print('Unable to abort, because the user is currently in the process ' + 'of paying.'); }); }, 20 * 60 * 1000); /* 20 minutes */ Specifications Specification Status Comment Payment Request APIThe definition of 'abort
()' in that specification. Candidate Recommendation ...
...And 2 more matches
performance.clearMeasures() - Web APIs
The clearMeasures
() method removes the named measure from the browser's performance entry buffer. If the method is called with no arguments, all performance entries with an entry type of "measure" will be removed from the performance entry buffer. Note: This feature is available in Web Workers. Syntax performance.clearMeasures
(); performance.clearMeasures(name); Arguments name Optional A DOMString representing the name of the timestamp. If this argument is omitted, all performance entries with an entry type of "measure" will be removed. Return value void Example The following example shows both uses of the clearMeasures
() method. // Create a small helper to show how many PerformanceMeasure entries there are. ...
...me); Arguments name Optional A DOMString representing the name of the timestamp. If this argument is omitted, all performance entries with an entry type of "measure" will be removed. Return value void Example The following example shows both uses of the clearMeasures
() method. // Create a small helper to show how many PerformanceMeasure entries there are. function logMeasureCount
() { console.log( "Found this many entries: " + performance.getEntriesByType("measure").length ); } // Create a bunch of measures. performance.measure("from navigation"); performance.mark("a"); performance.measure("from mark a", "a"); performance.measure("from navigation"); performance.measure("from mark a", "a"); performance.mark("b"); performance.measure("between a and b", "a", "b"); log...
....log( "Found this many entries: " + performance.getEntriesByType("measure").length ); } // Create a bunch of measures. ...
...And 2 more matches
PerformanceObserver.observe() - Web APIs
The performance entry types are specified as an array of DOMString objects, each naming one entry type; the type names are documented in Performance entry type names in PerformanceEntry.entryType. When a matching performance entry is recorded, the performance observer's callback function--set when creating the PerformanceObserver--is invoked. Syntax observer.observe(options); Parameters options A PerformanceObserverInit dictionary with the following possible members: entryTypes: An array of DOMString objects, each specifying one performance entry type to observe. May not be used together with the "type" or "buffered" options. ...
...fered: A Boolean flag to indicate whether buffered entries should be queued into the observer's buffer. Must be used only with the "type" option. See PerformanceEntry.entryType for a list of valid performance entry type names. Unrecognized types are ignored, though the browser may output a warning message to the console to help developers debug their code. ...
... browser may output a warning message to the console to help developers debug their code. If no valid types are found, observe
() has no effect. Examples This example creates and configures two PerformanceObservers; one watches for "mark" and "frame" events, and the other watches for "measure" events. ...
...And 2 more matches
PushManager.getSubscription() - Web APIs
} ); Parameters None. Returns A Promise that resolves to a PushSubscription object or null. Example This code snippet is taken from a push messaging and notification sample. ...
...} ); Parameters None. Returns A Promise that resolves to a PushSubscription object or null. Example This code snippet is taken from a push messaging and notification sample. ...
...ubscription object or null. Example This code snippet is taken from a push messaging and notification sample. (No live demo is available.) // We need the service worker registration to check for a subscription navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { // Do we already have a push message subscription? serviceWorkerRegistration.pushManager.getSubscription
() .then(function(subscription) { // Enable any UI which subscribes / unsubscribes from // push messages. var pushButton = document.querySelector('.js-push-button'); pushButton.disabled = false; if (!subscription) { // We aren't subscribed to push, so set UI // to allow the user to enable push return; } // ...
...And 2 more matches
RTCIceTransport.getRemoteCandidates() - Web APIs
Return value An array containing one RTCIceCandidate object for each candidate that has been received so far from the remote peer during the current ICE candidate gathering session. ...
... Return value An array containing one RTCIceCandidate object for each candidate that has been received so far from the remote peer during the current ICE candidate gathering session. ...
...ch contains one RTCIceCandidate for each of the candidates that have been received from the remote peer so far during the current ICE gathering session. Each time your signaling code calls RTCPeerConnection.addIceCandidate
() to add a received candidate to the ICE session, the ICE agent places it in the list returned by this function. Syntax remoteCandidates = RTCIceTransport.getRemoteCandidates
(); Parameters None. Return value An array containing one RTCIceCandidate object for each candidate that has been received so far from the remote peer during the current ICE candidate gathering session. It's important to keep in mind that there's no way to correlate these remote candidates with compatible local candidates. To find the best match found so far, call RTCIceTransport.getSelectedCan...
...And 2 more matches
RTCPeerConnection.restartIce() - Web APIs
The WebRTC API's RTCPeerConnection interface offers the restartIce
() method to allow a web application to easily request that ICE candidate gathering be redone on both ends of the connection. This simplifies the process by allowing the same method to be used by either the caller or the receiver to trigger an ICE restart. After restartIce
() returns, the offer returned by the next call to createOffer
() is automatically configured to trigger ICE restart on both the local peer (once the local peer has been set) and on the remote peer, once the offer is sent across your signaling mechanism and the remote peer has set its description as well. ...
...d by either the caller or the receiver to trigger an ICE restart. After restartIce
() returns, the offer returned by the next call to createOffer
() is automatically configured to trigger ICE restart on both the local peer (once the local peer has been set) and on the remote peer, once the offer is sent across your signaling mechanism and the remote peer has set its description as well. restartIce
() causes the negotiationneeded event to be fired on the RTCPeerConnection to inform the application that it should perform negotiation using its signaling channel. If negotiation fails to complete--either due to rollback or because incoming offers are in the process of being negotiated--the RTCPeerConnection will remember that you requested ICE restart. The next time the connection's signalingStat...
...omplete--either due to rollback or because incoming offers are in the process of being negotiated--the RTCPeerConnection will remember that you requested ICE restart. The next time the connection's signalingState changes to stable, the connection will fire the negotiationneeded event. This process continues until an ICE restart has been successfully completed. Syntax rtcPeerConnection.restartIce
(); Parameters None. Return value undefined. Usage notes After calling restartIce
(), the next offer created using createOffer
() will initiate ICE restart once sent to the remote peer over your signaling mechanism. Restarting ICE essentially resets ICE so that it creates all new candidates using new credentials. Existing media transmissions continue uninterrupted during this process. For detai...
...And 2 more matches
RTCPeerConnection.setConfiguration() - Web APIs
The RTCPeerConnection.setConfiguration
() method sets the current configuration of the RTCPeerConnection based on the values included in the specified RTCConfiguration object. This lets you change the ICE servers used by the connection and which transport policies to use. The most common use case for this method (and even then, probably not a very common use case) is to replace the set of ICE servers to be used. Two potential scenarios in which this might be done: The RTCPeerConnection was instantiated without specifying any ICE servers. If, for example, the RTCPeerConnection
() constructor was called with no parameters, you would have to then call setConfiguration
() to add ICE servers before ICE negotiation could begin. Renegotiation of the connection is needed, and a different set of...
... You cannot change the identity information for a connection once it's already been set. Syntax RTCPeerConnection.setConfiguration(configuration); Parameters configuration An RTCConfiguration object which provides the options to be set. ...
...From there, we handle the process as usual, ...
...And 2 more matches
Range.compareNode() - Web APIs
Obsolete since Gecko 1.9 (Firefox 3)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. The Range.compareNode
() returns a constant indicating the position of the Node. The possible values are: NODE_BEFORE (0) Node starts before the Range NODE_AFTER (1) Node ends after the Range NODE_BEFORE_AND_AFTER (2) Node starts before and ends after the Range NODE_INSIDE (3) Node starts after and ends before the Range, i.e. the Node is completely selected by the Range. ...
...nge NODE_BEFORE_AND_AFTER (2) Node starts before and ends after the Range NODE_INSIDE (3) Node starts after and ends before the Range, i.e. the Node is completely selected by the Range. ...
...selected by the Range. Warning: This method has been removed from Gecko 1.9 (Firefox 3) and will not exist in future versions of Firefox, which was the only browser implementing it; you should switch to Range.compareBoundaryPoints
() as soon as possible. ...
...And 2 more matches
Range.setStart() - Web APIs
If the startNode is a Node of type Text, Comment, or CDataSection, then startOffset is the number of characters from the start of startNode. For other Node types, startOffset is the number of child nodes between the start of the startNode. Setting the start point below (lower in the document) the end point will result in a collapsed range with the start and end points both set to the specified start position. Syntax range.setStart(startNode, startOffset); Parameters startNode The Node where the Range should start. startOffset An integer greater than or equal to zero representing the offset for the start of the Range from the start of startNode. ...
...with the start and end points both set to the specified start position. Syntax range.setStart(startNode, startOffset); Parameters startNode The Node where the Range should start. startOffset An integer greater than or equal to zero representing the offset for the start of the Range from the start of startNode. Examples Highlight part of an element This example uses the Range.setStart
() and Range.setEnd
() methods to add part of an address to a range. The selected range is then highlighted using Range.surroundContents
(). The address contains nine nodes: five text nodes, and four <br> elements. HTML <p id="address">Wyatt Earp<br> 101 E. Main St.<br> Dodge City, KS<br> 67801<br> USA</p> <hr> <p>Nodes in the original address:</p> <ol id="log"></ol> JavaScript const address = ...
...ument.getElementById('log'); // Log info address.childNodes.forEach(node => { const li = document.createElement('li'); li.textContent = `${node.nodeName}, ${node.nodeValue}`; log.appendChild(li); }); // Highlight the street and city const startOffset = 2; // Start at third node: 101 E. Main St. const endOffset = 5; // End at fifth node: Dodge City, KS const range = document.createRange
(); range.setStart(address, startOffset); range.setEnd(address, endOffset); const mark = document.createElement('mark'); range.surroundContents(mark); Result Get characters from a text node This example uses the Range.setStart
() and Range.setEnd
() methods to define the contents of a range. The resulting range contains the first through fifth characters within a text node. HTML <p id="content...
...And 2 more matches
ReadableStream.getReader() - Web APIs
While the stream is locked, no other reader can be acquired until this one is released. Syntax var reader = readableStream.getReader({mode}); Parameters {mode} Optional An object containing a property mode, which takes as its value a DOMString specifying the type of reader to create. Values can be: "byob", which results in a ReadableStreamBYOBReader being created that can read readable byte streams (i.e. can handle "bring your own buffer" reading). undefined (or not specified at all -- this is the default), which results in a ReadableStreamDefaultReader being created that can read individual chunks from a stream. ...
...eader or ReadableStreamBYOBReader object instance, depending on the mode value. Exceptions RangeError The provided mode value is not "byob" or undefined. TypeError The stream you are trying to create a reader for is not a ReadableStream. Examples In the following simple example, a previously-created custom ReadableStream is read using a ReadableStreamDefaultReader created using getReader
(). ...
... a previously-created custom ReadableStream is read using a ReadableStreamDefaultReader created using getReader
(). (see our Simple random stream example for the full code). Each chunk is read sequentially and output to the UI, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the UI. function fetchStream
() { const reader = stream.getReader
(); let charsReceived = 0; // read
() returns a promise that resolves // when a value has been received reader.read
().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) {...
...And 2 more matches
Selection.setBaseAndExtent() - Web APIs
Syntax sel.setBaseAndExtent(anchorNode,anchorOffset,focusNode,focusOffset) Parameters anchorNode The node at the start of the selection. anchorOffset The number of child nodes from the start of the anchor node that should be excluded from the selection. So for example, if the value is 0 the whole node is included. If the value is 1, the whole node minus the first child node is included. And so on. focusNode The node at the end of the selection. focusOffset The number of child nodes from the start of the focus node that should be included in the selection. ...
...h one containing a single word. The first one is set as the anchorNode and the second is set as the focusNode. We also have an additional paragraph that sits in between the two nodes. Next, we have two form inputs that allow you to set the anchorOffset and focusOffset -- they both have a default value of 0. We also have a button that when pressed invokes a function that runs the setBaseAndExtent
() method with the specified offsets, and copies the selection into the output paragraph at the very bottom of the HTML. <h1>setBaseAndExtent example</h1> <div> <p class="one"><span>Fish</span><span>Dog</span><span>Cat</span><span>Bird</span></p> <p>MIDDLE</p> <p class="two"><span>Car</span><span>Bike</span><span>Boat</span><span>Plane</span></p> </div> <div> <p> <label for="aOffset">A...
... Note: You can find this example on GitHub...
...And 2 more matches
ServiceWorkerRegistration.update() - Web APIs
Return value A Promise that resolves with a ServiceWorkerRegistration object. ...
...orkerRegistration interface attempts to update the service worker. It fetches the worker's script URL, and if the new worker is not byte-by-byte identical to the current worker, it installs the new worker. The fetch of the worker bypasses any browser caches if the previous fetch occurred over 24 hours ago. Note: This feature is available in Web Workers. Syntax serviceWorkerRegistration.update
(); Parameters None. Return value A Promise that resolves with a ServiceWorkerRegistration object. Example The following simple example registers a service worker example then adds an event handler to a button so you can explicitly update the service worker whenever desired: if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw-test/sw.js', {scope: 'sw-test'}).then(funct...
... Working Draft Initial definition. ...
...And 2 more matches
SpeechSynthesis.getVoices() - Web APIs
The getVoices
() method of the SpeechSynthesis interface returns a list of SpeechSynthesisVoice objects representing all the available voices on the current device. Syntax speechSynthesisInstance.getVoices
(); Parameters None. Return value A list (array) of SpeechSynthesisVoice objects. Note: The spec wrongly lists this method as returning as a SpeechSynthesisVoiceList object, but this was in fact removed from the spec. ...
...SynthesisVoice objects representing all the available voices on the current device. Syntax speechSynthesisInstance.getVoices
(); Parameters None. Return value A list (array) of SpeechSynthesisVoice objects. Note: The spec wrongly lists this method as returning as a SpeechSynthesisVoiceList object, but this was in fact removed from the spec. ...
...nstance.getVoices
(); Parameters None. Return value A list (array) of SpeechSynthesisVoice objects. Note: The spec wrongly lists this method as returning as a SpeechSynthesisVoiceList object, but this was in fact removed from the spec. ...
...And 2 more matches
SubtleCrypto.digest() - Web APIs
A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. It takes as its arguments an identifier for the digest algorithm to use and the data to digest. It returns a Promise which will be fulfilled with the digest. Syntax const digest = crypto.subtle.digest(algorithm, data); Parameters algorithm is a DOMString defining the hash function to use. Supported values are: SHA-1 (but don't use this in cryptographic applications) SHA-256 SHA-384 SHA-512. ...
...-4, section 6.2, and produces an output 256 bits long. SHA-384 This algorithm is specified in FIPS 180-4, section 6.5, and produces an output 384 bits long. SHA-512 This algorithm is specified in FIPS 180-4, section 6.4, and produces an output 512 bits long. ...
...ash message authentication code (HMAC), you need to use the SubtleCrypto.sign
() instead. Examples Basic example This example encodes a message, then calculates its SHA-256 digest and logs the digest length: const text = 'An obscure body in the S-K System, your majesty. The inhabitants refer to it as the planet Earth.'; async function digestMessage(message) { const encoder = new TextEncoder
(); const data = encoder.encode(message); const hash = await crypto.subtle.digest('SHA-256', data); return hash; } const digestBuffer = await digestMessage(text); console.log(digestBuffer.byteLength); Converting a digest to a hex string The digest is returned as an ArrayBuffer, but for comparison and display digests are often represented as hex strings. This example calculates a digest, th...
...And 2 more matches
TextDecoder.prototype.decode() - Web APIs
Set to true if processing the data in chunks, and false for the final chunk or if the data is not chunked. It defaults to false. ...
...Set to true if processing the data in chunks, and false for the final chunk or if the data is not chunked. It defaults to false. ...
...tDecoder object. Syntax b1 = decoder.decode(buffer, options); b2 = decoder.decode(buffer); b3 = decoder.decode
(); Parameters buffer Optional Is either an ArrayBuffer or an ArrayBufferView containing the text to decode. options Optional Is a TextDecodeOptions dictionary with the property: stream A Boolean flag indicating that additional data will follow in subsequent calls to decode
(). Set to true if processing the data in chunks, and false for the final chunk or if the data is not chunked. It defaults to false. Example This example encodes and decodes the euro symbol, EUR. ...
...And 2 more matches
UIEvent.initUIEvent() - Web APIs
The page on Creating and triggering events gives more information about the way to use these. Syntax event.initUIEvent(type, canBubble, cancelable, view, detail) Parameters type Is a DOMString defining the type of event. canBubble Is a Boolean deciding whether the event should bubble up through the event chain or not. ...
...The page on Creating and triggering events gives more information about the way to use these. Syntax event.initUIEvent(type, canBubble, cancelable, view, detail) Parameters type Is a DOMString defining the type of event. ...
... Obsolete Initial definition. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to c...
...And 2 more matches
WebGLRenderingContext.disable() - Web APIs
gl.DITHER Deactivates dithering of color components before they get written to the color buffer. ...
... gl.DITHER Deactivates dithering of color components before they get written to the color buffer. ...
... context. Syntax void gl.disable(cap); Parameters cap A GLenum specifying which WebGL capability to disable. Possible values: Constant Description gl.BLEND Deactivates blending of the computed fragment color values. See WebGLRenderingContext.blendFunc
(). gl.CULL_FACE Deactivates culling of polygons. See WebGLRenderingContext.cullFace
(). gl.DEPTH_TEST Deactivates depth comparisons and updates to the depth buffer. See WebGLRenderingContext.depthFunc
(). gl.DITHER Deactivates dithering of color components before they get written to the color buffer. gl.POLYGON_OFFSET_FILL Deactivates adding an offset to depth values of polygon's fragments. See WebGLRenderingContext.polygonOffset
(). ...
...And 2 more matches
WebGLRenderingContext.enable() - Web APIs
gl.DITHER Activates dithering of color components before they get written to the color buffer. ...
... gl.DITHER Activates dithering of color components before they get written to the color buffer. ...
...r this context. Syntax void gl.enable(cap); Parameters cap A GLenum specifying which WebGL capability to enable. Possible values: Constant Description gl.BLEND Activates blending of the computed fragment color values. See WebGLRenderingContext.blendFunc
(). gl.CULL_FACE Activates culling of polygons. See WebGLRenderingContext.cullFace
(). gl.DEPTH_TEST Activates depth comparisons and updates to the depth buffer. See WebGLRenderingContext.depthFunc
(). gl.DITHER Activates dithering of color components before they get written to the color buffer. gl.POLYGON_OFFSET_FILL Activates adding an offset to depth values of polygon's fragments. See WebGLRenderingContext.polygonOffset
(). ...
...And 2 more matches
WebGLRenderingContext.isEnabled() - Web APIs
The WebGLRenderingContext.isEnabled
() method of the WebGL API tests whether a specific WebGL capability is enabled or not for this context. By default, all capabilities except gl.DITHER are disabled. Syntax GLboolean gl.isEnabled(cap); Parameters cap A GLenum specifying which WebGL capability to test. Possible values: Constant Description gl.BLEND Blending of the computed fragment color values. See WebGLRenderingContext.blendFunc
(). gl.CULL_FACE Culling of polygons. See WebGLRenderingContext.cullFace
(). gl.DEPTH_TEST Depth comparisons and updates to the depth buffer. See WebGLRenderingContext.depthFunc
(). gl.DITHER Dithering of color components before they get written to the color buffer. ...
...gons. See WebGLRenderingContext.cullFace
(). gl.DEPTH_TEST Depth comparisons and updates to the depth buffer. See WebGLRenderingContext.depthFunc
(). gl.DITHER Dithering of color components before they get written to the color buffer. gl.POLYGON_OFFSET_FILL Adding an offset to depth values of polygon's fragments. See WebGLRenderingContext.polygonOffset
(). gl.SAMPLE_ALPHA_TO_COVERAGE Computation of a temporary coverage value determined by the alpha value. gl.SAMPLE_COVERAGE ANDing the fragment's coverage with the temporary coverage value. See WebGLRenderingContext.sampleCoverage
(). gl.SCISSOR_TEST Scissor test that discards fragments that are outside of the scissor rectangle. See WebGLRenderingContex...
... gl.SAMPLE_ALPHA_TO_COVERAGE Computation of a temporary coverage value determined by the alpha value. gl.SAMPLE_COVERAGE ANDing the fragment's coverage with the temporary coverage value. See WebGLRenderingContext.sampleCoverage
(). gl.SCISSOR_TEST Scissor test that discards fragments that are outside of the scissor rectangle. See WebGLRenderingContext.scissor
(). gl.STENCIL_TEST Stencil testing and updates to the stencil buffer. See WebGLRenderingContext.stencilFunc
(). When using a WebGL 2 context, the following values are available additionally: Constant Description gl.RASTERIZER_DISCARD Primitives are discarded immediately before the rasterization stage, but after the optional transform ...
...And 2 more matches
Window.prompt() - Web APIs
The Window.prompt
() displays a dialog with an optional message prompting the user to input some text. Syntax result = window.prompt(message, default); Parameters message Optional A string of text to display to the user. Can be omitted if there is nothing to show in the prompt window. default Optional A string containing the default value displayed in the text input field. Note that in Internet Explorer 7 and 8, if you do not provide this parameter, the string "undefined" is the default value. Return value A string containing the text entered by the user, or null. ...
... nothing to show in the prompt window. default Optional A string containing the default value displayed in the text input field. Note that in Internet Explorer 7 and 8, if you do not provide this parameter, the string "undefined" is the default value. Return value A string containing the text entered by the user, or null. ...
...ld. Note that in Internet Explorer 7 and 8, if you do not provide this parameter, the string "undefined" is the default value. Return value A string containing the text entered by the user, or null. ...
...And 2 more matches
Window.requestAnimationFrame() - Web APIs
The window.requestAnimationFrame
() method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint. Note: Your callback routine must itself call requestAnimationFrame
() if you want to animate another frame at the next repaint. You should call this method whenever you're ready to update your animation onscreen. This will request that your animation function be called before the browser performs the next repaint. The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation. ...
... another frame at the next repaint. You should call this method whenever you're ready to update your animation onscreen. This will request that your animation function be called before the browser performs the next repaint. The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation. ...
...This timestamp is a decimal number, in milliseconds, but with a minimal precision of 1ms (1000 us). ...
...And 2 more matches
WindowOrWorkerGlobalScope.btoa() - Web APIs
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. ...
...ue An ASCII string containing the Base64 representation of stringToEncode. Exceptions InvalidCharacterError The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. Example const encodedData = window.btoa('Hello, world'); // encode a string const decodedData = window.atob(encodedData); // decode the string Unicode strings The btoa
() function takes a JavaScript string as a parameter. In JavaScript strings are represented using the UTF-16 character encoding: in this encoding, strings are represented as a sequence of 16-bit (2 byte) units. Every ASCII character fits into the first byte of one of these units, but many other characters don't. Base64, by design, expects binary data as its input. In terms of JavaScript strings, th...
...e UTF-16 character encoding: in this encoding, strings are represented as a sequence of 16-bit (2 byte) units. Every ASCII character fits into the first byte of one of these units, but many other characters don't. Base64, by design, expects binary data as its input. In terms of JavaScript strings, this means strings in which each character occupies only one byte. ...
...And 2 more matches
Worker.prototype.postMessage() - Web APIs
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. ...
... it becomes unusable (neutered) in the context it was sent from and becomes available only to the worker it was sent to. Transferable objects are instances of classes like ArrayBuffer, MessagePort or ImageBitmap objects that can be transferred. null is not an acceptable value for transfer. Returns Void. ...
...nsferable objects are instances of classes like ArrayBuffer, MessagePort or ImageBitmap objects that can be transferred. null is not an acceptable value for transfer. Returns Void. Example The following code snippet shows the creation of a Worker object using the Worker
() constructor. When either of two form inputs (first and second) have their values changed, change events invoke postMessage
() to send the value of both inputs to the current worker. ...
...And 2 more matches
XMLHttpRequest.setRequestHeader() - Web APIs
For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names. ...
... For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names. ...
... For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names. ...
...And 2 more matches
XRSession.cancelAnimationFrame() - Web APIs
The cancelAnimationFrame
() method of the XRSession interface cancels an animation frame which was previously requested by calling requestAnimationFrame. Syntax xrSession.cancelAnimationFrame(handle); Parameters handle The unique value returned by the call to requestAnimationFrame
() that previously scheduled the animation callback. Return value None. Usage notes This function has no effect if the specified handle cannot be found. Example In the example below we see code which starts up a WebXR session if immersive VR mode is supported. Once started, the session schedules its first frame to be rendered by calling requestAnimationFrame
(). ...
...Since each frame callback schedules the next one, removing the callback terminates updating of the WebXR scene. ...
...alled to suspend the WebVR session, in essence, by canceling any pending animation frame callback. Since each frame callback schedules the next one, removing the callback terminates updating of the WebXR scene. ...
...And 2 more matches
:has() - CSS: Cascading Style Sheets
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-...
...This limitation has been removed because no browser implemented it that way. Instead, browse...
...ken> ] <attr-modifier>? ']'where <attr-matcher> = [ '~' | | | '^' | '$' | '*' ]? '='<attr-modifier> = i | s Description The :has
() pseudo-class takes a relative selector list as an argument. In earlier revisions of the CSS Selectors Level 4 specification, :has had a limitation that it couldn't be used within stylesheets. Instead, it could only be used with functions like document.querySelector
(); this was due to performance concerns. This limitation has been removed because no browser implemented it that way. Instead, browsers currently only support the use of :has
() within stylesheets. Examples Matching <a> elements that directly contain an <img> The following selector matches only <a> elements that directly contain an <img> child: a:has(> img) Matching <h1> elements that are foll...
...And 2 more matches
counter() - CSS: Cascading Style Sheets
Check the Browser compatibility table carefully before using this in production. ...
... Check the Browser compatibility table carefully before using this in production. ...
...ction returns a string representing the current value of the named counter, if there is one. It is generally used with pseudo-elements, but can be used, theoretically, anywhere a <string> value is supported. /* Simple usage */ counter(countername); /* changing the counter display */ counter(countername, upper-roman) A counter has no visible effect by itself. The counter
() function (and counters
() function) is what makes it useful by returning developer defined strings (or images). Note: The counter
() function can be used with any CSS property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse. Check the Browser compatibility table carefully before using this in production. Syntax Values <custom-ident> A name ident...
...And 2 more matches
env() - CSS: Cascading Style Sheets
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. ...
...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. ...
...in Media query rules). As the spec evolves, it may also be usable in other places such as selectors. ...
...And 2 more matches
Array.prototype.pop() - JavaScript
Description The pop method removes the last element from an array and returns that value to the caller. pop is intentionally generic; this method can be called or applied to objects resembling arrays. ...
... Description The pop method removes the last element from an array and returns that value to the caller. pop is intentionally generic; this method can be called or applied to objects resembling arrays. ...
...y is empty. Description The pop method removes the last element from an array and returns that value to the caller. pop is intentionally generic; this method can be called or applied to objects resembling arrays. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner. ...
...And 2 more matches
Array.prototype.reverse() - JavaScript
Description The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. reverse is intentionally generic; this method can be called or applied to objects resembling arrays. ...
... Description The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. reverse is intentionally generic; this method can be called or applied to objects resembling arrays. ...
...ric; this method can be called or applied to objects resembling arrays. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner. Examples Reversing the elements in an array The following example creates an array a, containing three elements, then reverses the array. ...
...And 2 more matches
Array.prototype.shift() - JavaScript
Description The shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value. If the length property is 0, undefined is returned. shift is intentionally generic; this method can be called or applied to objects resembling arrays. ...
... Description The shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value. If the length property is 0, undefined is returned. shift is intentionally generic; this method can be called or applied to objects resembling arrays. ...
...t consecutive indexes down, then returns the removed value. If the length property is 0, undefined is returned. shift is intentionally generic; this method can be called or applied to objects resembling arrays. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner. Array.prototype.pop
() has similar behavior to shift, but applied to the last element in an array. Examples Removing an element from an array The following code displays the myFish array before and after removing its first element. It also displays the removed element: var myFish = ['angel', 'clown', 'mandarin', 'surgeon']; console.log('myFish before:', JSON.stringify(myFish)); // myFish before: ['angel', 'clown',...
...And 2 more matches
BigInt.prototype.toLocaleString() - JavaScript
The toLocaleString
() method returns a string with a language-sensitive representation of this BigInt. 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 bigIntObj.toLocaleString([locales [, options]]) Parameters The locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation-dependent. ...
...ntObj.toLocaleString([locales [, options]]) Parameters The locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation-dependent. See the Intl.NumberFormat
() constructor for details on these parameters and how to use them. Return value A string with a language-sensitive representation of the given BigInt. Performance When formatting large numbers of numbers, it is better to create a NumberFormat object and use the function provided by its NumberFormat.format property. Examples Using toLocaleString In basic use without specifying a locale, a for...
...epresentation of the given BigInt. Performance When formatting large numbers of numbers, it is better to create a NumberFormat object and use the function provided by its NumberFormat.format property. Examples Using toLocaleString In basic use without specifying a locale, a formatted string in the default locale and with default options is returned. var bigint = 3500n; bigint.toLocaleString
(); // Displays "3,500" if in U.S. English locale Using locales This example shows some of the variations in localized number formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: var bigint = 123456789123456789n; // German uses period for thousands...
...And 2 more matches
Date() constructor - JavaScript
t represents a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC. 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. ...
...amples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax new Date
() new Date(value) new Date(dateString) new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]) Note: The only correct way to instantiate a new Date object is by using the new operator. If you simply call the Date object directly, such as now = Date
(), the returned value is a string rather than a Date object. Parameters There are four basic forms for the Date
() constructor: No parameters When no parameters are provided, the newly-created Date object represents the current date and time as of the time of instantiation. Time value or timestamp number value An integer value representing the number of milliseconds since...
... An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most UNIX Timestamp functions are only accurate to the nearest second. Timestamp string dateString A string value representing a date, specified in a format recognized by the Date.parse
() method. (These formats are IETF-compliant RFC 2822 timestamps, and also strings in a version of ISO8601.) Note: Parsing of date strings with the Date constructor (and Date.parse
(), which works the same way) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in t...
...And 2 more matches
Date.UTC() - JavaScript
It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. 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 Since ECMAScript 2017: Date.UTC(year[, month[, day[, hour[, minute[, second[, millisecond]]]]]]) ECMAScript 2016 and earlier: (month used to be required) Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]]) Parameters year A full year. month An integer between 0 (January) and 11 (December) representing the month. ...
...epresenting the minutes. If omitted, defaults to 0. second Optional An integer between 0 and 59 representing the seconds. If omitted, defaults to 0. millisecond Optional An integer between 0 and 999 representing the milliseconds. If omitted, defaults to 0. Return value A number representing the number of milliseconds for the given date since January 1, 1970, 00:00:00, UTC. ...
...of milliseconds for the given date since January 1, 1970, 00:00:00, UTC. Description UTC
() takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time. Years between 0 and 99 are converted to a year in the 20th century (1900 + year). For example, 95 is converted to the year 1995. The UTC
() method differs from the Date constructor in two ways: Date.UTC
() uses universal time instead of the local time. Date.UTC
() returns a time value as a number instead of creating a Date object. If a parameter is outside of the expected range, the UTC
() method updates the other parameters to accommodate the value. For example, if 15 is used for month, the year will be incremented by 1 (year + 1...
...And 2 more matches
Date.prototype.getTime() - JavaScript
The getTime
() method returns the number of milliseconds* since the Unix Epoch. * JavaScript uses milliseconds as the unit of measurement, whereas Unix Time is in seconds. getTime
() always uses UTC for time representation. For example, a client browser in one timezone, getTime
() will be the same as a client browser in any other timezone. You can use this method to help assign a date and time to another Date object. This method is functionally equivalent to the valueOf
() method. 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. ...
...one. You can use this method to help assign a date and time to another Date object. This method is functionally equivalent to the valueOf
() method. 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 dateObj.getTime
() Return value A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date. Reduced time precision To offer protection against timing attacks and fingerprinting, the precision of new Date
().getTime
() might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecision preference is enabled by default and defaults to 20us in Fi...
...0:00:00 UTC and the given date. Reduced time precision To offer protection against timing attacks and fingerprinting, the precision of new Date
().getTime
() might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecision preference is enabled by default and defaults to 20us in Firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in Firefox 60 new Date
().getTime
(); // 1519211809934 // 1519211810362 // 1519211811670 // ... // reduced time precision with `privacy.resistFingerprinting` enabled new Date
().getTime
(); // 1519129853500 // 1519129858900 // 1519129864400 // ... In Firefox, you can also enable privacy.resistFingerprinting, the precision will be 100ms or the value of privacy.resistFingerprinting.reduceTimerPrecision.microseconds, whiche...
...And 2 more matches
Date.prototype.setFullYear() - JavaScript
Returns new timestamp. 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 dateObj.setFullYear(yearValue[, monthValue[, dateValue]]) Parameters yearValue An integer specifying the numeric value of the year, for example, 1995. monthValue Optional. An integer between 0 and 11 representing the months January through December. dateValue Optional. An integer between 1 and 31 representing the day of the month. If you specify the dateValue parameter, you must also specify the monthValue. ...
...ary through December. dateValue Optional. An integer between 1 and 31 representing the day of the month. If you specify the dateValue parameter, you must also specify the monthValue. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ...
...cember. dateValue Optional. An integer between 1 and 31 representing the day of the month. If you specify the dateValue parameter, you must also specify the monthValue. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ...
...And 2 more matches
Date.prototype.setMinutes() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dateObj.setMinutes(minutesValue[, secondsValue[, msValue]]) Versions prior to JavaScript 1.3 dateObj.setMinutes(minutesValue) Parameters minutesValue An integer between 0 and 59, representing the minutes. secondsValue Optional. An integer between 0 and 59, representing the seconds. If you specify the secondsValue parameter, you must also specify the minutesValue. msValue Optional. A number between 0 and 999, representing the milliseconds. ...
...inutesValue. msValue Optional. A number between 0 and 999, representing the milliseconds. If you specify the msValue parameter, you must also specify the minutesValue and secondsValue. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ...
... Optional. A number between 0 and 999, representing the milliseconds. If you specify the msValue parameter, you must also specify the minutesValue and secondsValue. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If you do not specify the secondsValue and msValue parameters, the values returned from getSeconds
() and getMilliseconds
() methods are used. ...
...And 2 more matches
Date.prototype.setUTCFullYear() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dateObj.setUTCFullYear(yearValue[, monthValue[, dayValue]]) Parameters yearValue An integer specifying the numeric value of the year, for example, 1995. monthValue Optional. An integer between 0 and 11 representing the months January through December. dayValue Optional. An integer between 1 and 31 representing the day of the month. If you specify the dayValue parameter, you must also specify the monthValue. ...
...ary through December. dayValue Optional. An integer between 1 and 31 representing the day of the month. If you specify the dayValue parameter, you must also specify the monthValue. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ...
...ber. dayValue Optional. An integer between 1 and 31 representing the day of the month. If you specify the dayValue parameter, you must also specify the monthValue. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If you do not specify the monthValue and dayValue parameters, the values returned from the getUTCMonth
() and getUTCDate
() methods are used. ...
...And 2 more matches
Date.prototype.setUTCMinutes() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dateObj.setUTCMinutes(minutesValue[, secondsValue[, msValue]]) Parameters minutesValue An integer between 0 and 59, representing the minutes. secondsValue Optional. An integer between 0 and 59, representing the seconds. If you specify the secondsValue parameter, you must also specify the minutesValue. msValue Optional. A number between 0 and 999, representing the milliseconds. ...
...tesValue. msValue Optional. A number between 0 and 999, representing the milliseconds. If you specify the msValue parameter, you must also specify the minutesValue and secondsValue. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ...
...nal. A number between 0 and 999, representing the milliseconds. If you specify the msValue parameter, you must also specify the minutesValue and secondsValue. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If you do not specify the secondsValue and msValue parameters, the values returned from getUTCSeconds
() and getUTCMilliseconds
() methods are used. ...
...And 2 more matches
Date.prototype.toString() - JavaScript
"Sat" space Month name: 3 letter English month name, e.g. "Sep" space Date: 2 digit day in month, e.g. ...
..."Sat" space Month name: 3 letter English month name, e.g. "Sep" space Date: 2 digit day in month, e.g. ...
... representing the specified Date object. 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 dateObj.toString
() Return value A string representing the given date. Description Date instances inherit their toString
() method from Date.prototype, not Object.prototype. Date.prototype.toString
() returns a string representation of the Date in the format specified in ECMA-262 which can be summarised as: Week day: 3 letter English week day name, e.g. "Sat" space Month name: 3 letter English month name, e.g. "Sep" space Date: 2 digit day in month, e.g. "01" space Year: 4 digit year, e.g. "2018" space Hour:...
...And 2 more matches
Float32Array() constructor - JavaScript
The Float32Array
() typed array constructor creates a new Float32Array object, which is, an array of 32-bit floating point numbers (corresponding to the C float data type) in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ...
... which is, an array of 32-bit floating point numbers (corresponding to the C float data type) in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). Syntax new Float32Array
(); // new in ES2017 new Float32Array(length); new Float32Array(typedArray); new Float32Array(object); new Float32Array(buffer [, byteOffset [, length]]); Parameters length When called with a length argument, an internal array buffer is created in memory, of size length multiplied by BYTES_PER_ELEMENT bytes, containing zeros. typedArray When called with a typedArray argument, which can be an ...
...array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the typedArray argument. object When called with an object argument, a new typed array is created as if by the TypedArray.from
() method. buffer, byteOffset, length When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified ArrayBuffer. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is view...
...And 2 more matches
Float64Array() constructor - JavaScript
The Float64Array
() typed array constructor creates a new Float64Array object, which is, an array of 64-bit floating point numbers (corresponding to the C double data type) in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ...
...which is, an array of 64-bit floating point numbers (corresponding to the C double data type) in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). Syntax new Float64Array
(); // new in ES2017 new Float64Array(length); new Float64Array(typedArray); new Float64Array(object); new Float64Array(buffer [, byteOffset [, length]]); Parameters length When called with a length argument, an internal array buffer is created in memory, of size length multiplied by BYTES_PER_ELEMENT bytes, containing zeros. typedArray When called with a typedArray argument, which can be an ...
...array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the typedArray argument. object When called with an object argument, a new typed array is created as if by the TypedArray.from
() method. buffer, byteOffset, length When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified ArrayBuffer. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is view...
...And 2 more matches
Math.atan() - JavaScript
The Math.atan
() function returns the arctangent (in radians) of a number, that is Math.atan(x)=arctan(x)= the unique y?[-?2;?2]such thattan(y)=x\mathtt{\operatorname{Math.atan}(x)} = \arctan(x) = \text{ the unique } \; y \in \left[-\frac{\pi}{2}; \frac{\pi}{2}\right] \, \text{such that} \; \tan(y) = x The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.atan(x) Parameters x A number. Return value The arctangent (in radians) of the given number. Description The Math.atan
() method returns a numeric value between -?2-\frac{\pi}{2} and ?2\frac{\pi}{2} radians. ...
...tory. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.atan(x) Parameters x A number. Return value The arctangent (in radians) of the given number. Description The Math.atan
() method returns a numeric value between -?2-\frac{\pi}{2} and ?2\frac{\pi}{2} radians. ...
... project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.atan(x) Parameters x A number. Return value The arctangent (in radians) of the given number. Description The Math.atan
() method returns a numeric value between -?2-\frac{\pi}{2} and ?2\frac{\pi}{2} radians. Because atan
() is a static method of Math, you always use it as Math.atan
(), rather than as a method of a Math object you created (Math is not a constructor). ...
...And 2 more matches
Math.ceil() - JavaScript
The Math.ceil
() function always rounds a number up to the next largest integer. Note: Math.ceil(null) returns integer 0 and does not give a NaN error. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.ceil(x) Parameters x A number. Return value The smallest integer greater than or equal to the given number. Description Because ceil
() is a static method of Math, you always use it as Math.ceil
(), rather than as a method of a Math object you created (Math is not a constructor). Examples Using Math.ceil
() The following example shows example usage of Math.ceil
(). Math.ceil(.95); // 1 Math.c...
... * * @param {String} type The type of adjustment. * @param {Number} value The number. * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). * @returns {Number} The adjusted value. */ function decimalAdjust(type, value, exp) { // If the exp is undefined or zero... ...
...malAdjust(type, value, exp) { // If the exp is undefined or zero... if (typeof exp === 'undefined' || +exp === 0) { return Math[type](value); } value = +value; exp = +exp; // If the value is not a number or the exp is not an integer... ...
...And 2 more matches
Math.fround() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax var singleFloat = Math.fround(doubleFloat); Parameters doubleFloat A Number. If the parameter is of a different type, it will get converted to a number or to NaN if it cannot be converted. Return value The nearest 32-bit single precision float representation of the given number. Description JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. ...
...avaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a Float32Array. This can create confusion: Checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. ...
...s are seemingly identical. To solve this, Math.fround
() can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to 0. If the number is outside the range of a 32-bit float, Infinity or -Infinity is returned. Because fround
() is a static method of Math, you always use it as Math.fround
(), rather than as a method of a Math object you created (Math is not a constructor). Polyfill This can be emulated with the following function, if Float32Array are supported: Math.fround = Math.fround || (function (array) { return function(x) { return array[0] = x, array[0]; }; })(new Float32Array(1)); Supporting older brow...
...And 2 more matches
Math.min() - JavaScript
The static function Math.min
() returns the lowest-valued number passed into it, or NaN if any parameter isn't a number and can't be converted into one. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.min([value1[, value2[, ...]]]) Parameters value1, value2, ... Zero or more numbers among which the lowest value will be selected and returned. Return value The smallest of the given numbers. If any one or more of the parameters cannot be converted into a number, NaN is returned. The result is Infinity if no parameters are provided. ...
...us a pull request. Syntax Math.min([value1[, value2[, ...]]]) Parameters value1, value2, ... Zero or more numbers among which the lowest value will be selected and returned. Return value The smallest of the given numbers. If any one or more of the parameters cannot be converted into a number, NaN is returned. The result is Infinity if no parameters are provided. ...
...]]) Parameters value1, value2, ... Zero or more numbers among which the lowest value will be selected and returned. Return value The smallest of the given numbers. If any one or more of the parameters cannot be converted into a number, NaN is returned. The result is Infinity if no parameters are provided. ...
...And 2 more matches
Number.prototype.toExponential() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax numObj.toExponential([fractionDigits]) Parameters fractionDigits Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number. Return value A string representing the given Number object in exponential notation with one digit before the decimal point, rounded to fractionDigits digits after the decimal point. ...
... 20, inclusive, will not cause a RangeError. Implementations are allowed to support larger and smaller values as well. TypeError If this method is invoked on an object that is not a Number. Description If the fractionDigits argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. If you use the toExponential
() method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. If a number has more digits than requested by the fractionDigits parameter, the number is rounded to the nearest number represented by fractionDigits digits. See the discussion of ...
...ric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. If a number has more digits than requested by the fractionDigits parameter, the number is rounded to the nearest number represented by fractionDigits digits. ...
...And 2 more matches
Number.prototype.toLocaleString() - JavaScript
The toLocaleString
() method returns a string with a language-sensitive representation of this number. 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 numObj.toLocaleString([locales [, options]]) Parameters The locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. ...
...Obj.toLocaleString([locales [, options]]) Parameters The locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. See the Intl.NumberFormat
() constructor for details on these parameters and how to use them. Return value A string with a language-sensitive representation of the given number. Performance When formatting large numbers of numbers, it is better to create a NumberFormat object and use the function provided by its NumberFormat.format property. Examples Using toLocaleString In basic use without specifying a locale, ...
...of the given number. Performance When formatting large numbers of numbers, it is better to create a NumberFormat object and use the function provided by its NumberFormat.format property. Examples Using toLocaleString In basic use without specifying a locale, a formatted string in the default locale and with default options is returned. ...
...And 2 more matches
Number.prototype.toString() - JavaScript
The toString
() method returns a string representing the specified Number object. 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 numObj.toString([radix]) Parameters radix Optional. An integer in the range 2 through 36 specifying the base to use for representing numeric values. Return value A string representing the specified Number object. Exceptions RangeError If toString
() is given a radix less than 2 or greater than 36, a RangeError is thrown. Description The Number object overrides the toString
() method of the Object object. (It does not inherit Object.prototype.toString
()). For Number ...
...the base to use for representing numeric values. Return value A string representing the specified Number object. Exceptions RangeError If toString
() is given a radix less than 2 or greater than 36, a RangeError is thrown. Description The Number object overrides the toString
() method of the Object object. (It does not inherit Object.prototype.toString
()). For Number objects, the toString
() method returns a string representation of the object in the specified radix. The toString
() method parses its first argument, and attempts to return a string representation in the specified radix (base). For radices above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), a through f are used. If the radix is not specified, the pref...
...d to be 10. If the numObj is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the numObj preceded by a - sign, not the two's complement of the numObj. If the numObj is not a whole number, the 'dot' sign is used to separate the decimal places. ...
...And 2 more matches
Object.prototype.__lookupGetter__() - JavaScript
the specified property. Description If a getter has been defined for an object's property, it's not possible to reference the getter function through that property, because that property refers to the return value of that function. __lookupGetter__ can be used to obtain a reference to the getter function. ...
...scription If a getter has been defined for an object's property, it's not possible to reference the getter function through that property, because that property refers to the return value of that function. __lookupGetter__ can be used to obtain a reference to the getter function. It is now possible to do this in a standardized way using Object.getOwnPropertyDescriptor
() and Object.getPrototypeOf
(). ...
...tter function through that property, because that property refers to the return value of that function. __lookupGetter__ can be used to obtain a reference to the getter function. It is now possible to do this in a standardized way using Object.getOwnPropertyDescriptor
() and Object.getPrototypeOf
(). ...
...And 2 more matches
Object.keys() - JavaScript
The Object.keys
() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would. 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 Object.keys(obj) Parameters obj The object of which the enumerable's own properties are to be returned. Return value An array of strings that represent all the enumerable properties of the given object. Description Object.keys
() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by loopi...
...able properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually. ...
... For a simple Browser Polyfill, see Javascript - Object.keys Browser Compatibility. Examples Using Object.keys // simple array const arr = ['a', 'b', 'c']; console.log(Object.keys(arr)); // console: ['0', '1', '2'] // array-like object const obj = { 0: ...
...And 2 more matches
Promise() constructor - JavaScript
iseObj becomes "resolved." Typically, it works like this: The operation within executor is asynchronous and provides a callback. The callback is defined within the executor code. The callback terminates by invoking resolutionFunc. The invocation of resolutionFunc includes a value parameter. The value is passed back to the tethered promiseObj. The promiseObj (asynchronously) invokes any .then
() associated with it. The value received by promiseObj.then
() is passed to the invocation of handleFulfilled as an input parameter (See "Chained Promises" section). The executor might also include a try{} catch
() block that invokes rejectionFunc upon error. The signatures of these two functions are simple, they accept a single parameter of any type. Of course, the actual names of these functions ...
... ...
... ...
...And 2 more matches
Promise.race() - JavaScript
The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Promise.race(iterable); Parameters iterable An iterable object, such as an Array. See iterable. Return value A pending Promise that asynchronously yields the value of the first promise in the given iterable to fulfill or reject. ...
...of Promise.race: // we are passing as argument an array of promises that are already resolved, // to trigger Promise.race as soon as possible var resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)]; var p = Promise.race(resolvedPromisesArray); // immediately logging the value of p console.log(p); // using setTimeout we can execute code after the stack is empty setTimeout(function
(){ console.log('the stack is now empty'); console.log(p); }); // logs, in order: // Promise { <state>: "pending" } // the stack is now empty // Promise { <state>: "fulfilled", <value>: 33 } An empty iterable causes the returned promise to be forever pending: var foreverPendingPromise = Promise.race([]); console.log(foreverPendingPromise); setTimeout(function
(){ console.log('the stack...
... of these values found in the array: var foreverPendingPromise = Promise.race([]); var alreadyFulfilledProm = Promise.resolve(100); var arr = [foreverPendingPromise, alreadyFulfilledProm, "non-Promise value"]; var arr2 = [foreverPendingPromise, "non-Promise value", Promise.resolve(100)]; var p = Promise.race(arr); var p2 = Promise.race(arr2); console.log(p); console.log(p2); setTimeout(function
(){ console.log('the stack is now empty'); console.log(p); console.log(p2); }); // logs, in order: // Promise { <state>: "pending" } // Promise { <state>: "pending" } // the stack is now empty // Promise { <state>: "fulfilled", <value>: 100 } // Promise { <state>: "fulfilled", <value>: "non-Promise value" } Using Promise.race - examples with setTimeout var p1 = new Promise(function(r...
...And 2 more matches
handler.set() - JavaScript
The handler.set
() method is a trap for setting a property 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 const p = new Proxy(target, { set: function(target, property, value, receiver) { } }); Parameters The following parameters are passed to the set
() method. this is bound to the handler. target The target object. property The name or Symbol of the property to set. value The new value of the property to set. receiver The object to which the assignment was originally directed. This is usually the proxy itself. ...
...ction(target, property, value, receiver) { } }); Parameters The following parameters are passed to the set
() method. this is bound to the handler. target The target object. property The name or Symbol of the property to set. value The new value of the property to set. receiver The object to which the assignment was originally directed. This is usually the proxy itself. But a set
() handler can also be called indirectly, via the prototype chain or various other ways. For example: Suppose a script does obj.name = "jen", and obj is not a proxy, and has no own property .name, but it has a proxy on its prototype chain. That proxy's set
() handler will be called, and obj will be passed as the receiver. Return value The set
() method should return a boolean value. Retu...
...chain or various other ways. For example: Suppose a script does obj.name = "jen", and obj is not a proxy, and has no own property .name, but it has a proxy on its prototype chain. That proxy's set
() handler will be called, and obj will be passed as the receiver. Return value The set
() method should return a boolean value. Return true to indicate that assignment succeeded. If the set
() method returns false, and the assignment happened in strict-mode code, a TypeError will be thrown. Description The handler.set
() method is a trap for setting property value. ...
...And 2 more matches
Proxy() constructor - JavaScript
This constructor takes two mandatory arguments: target is the object for which you want to create the proxy handler is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. ...
...This constructor takes two mandatory arguments: target is the object for which you want to create the proxy handler is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. ...
...rguments: target is the object for which you want to create the proxy handler is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the handler object, you can customise specific aspects of the proxy's behavior. ...
...And 2 more matches
RegExp.prototype.test() - JavaScript
The test
() method executes a search for a match between a regular expression and a specified string. Returns true or false. 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 regexObj.test(str) Parameters str The string against which to match the regular expression. Returns true if there is a match between the regular expression and the string str. Otherwise, false. Description Use test
() whenever you want to know whether a pattern is found in a string. test
() returns a boolean, unlike the String.prototype.search
() method (which returns the index of a match, or -1 if not found). To get more informa...
...pression. Returns true if there is a match between the regular expression and the string str. Otherwise, false. Description Use test
() whenever you want to know whether a pattern is found in a string. test
() returns a boolean, unlike the String.prototype.search
() method (which returns the index of a match, or -1 if not found). To get more information (but with slower execution), use the exec
() method. (This is similar to the String.prototype.match
() method.) As with exec
() (or in combination with it), test
() called multiple times on the same global regular expression instance will advance past the previous match. Examples Using test
() Simple example that tests if "hello" is contained at the very beginning of a string, returning a boolean result. const str = 'hello world!'; const r...
...an result. ...
...And 2 more matches
RegExp.prototype.toSource() - JavaScript
This method is usually called internally by JavaScript and not explicitly in web code. ...
... This method is usually called internally by JavaScript and not explicitly in web code. ...
... This method is usually called internally by JavaScript and not explicitly in web code. ...
...And 2 more matches
Set.prototype[@@iterator]() - JavaScript
operty is the same function object as the initial value of the values property. 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. ...
...ue of the values property. 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 mySet[Symbol.iterator] Return value The Set iterator function, which is the values
() function by default. ...
.... 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 mySet[Symbol.iterator] Return value The Set iterator function, which is the values
() function by default. ...
...And 2 more matches
String.prototype[@@iterator]() - JavaScript
The [@@iterator]
() method returns a new Iterator object that iterates over the code points of a String value, returning each code point as a String value. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str[Symbol.iterator] Return value A new Iterator object. ...
...code points of a String value, returning each code point as a String 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 str[Symbol.iterator] Return value A new Iterator object. ...
...ng 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 str[Symbol.iterator] Return value A new Iterator object. ...
...And 2 more matches
String.prototype.blink() - JavaScript
The blink
() method creates a <blink> HTML element that causes a string to blink. Warning: Blinking text is frowned upon by several accessibility standards. The <blink> element itself is non-standard and deprecated! ...
... The blink
() method creates a <blink> HTML element that causes a string to blink. Warning: Blinking text is frowned upon by several accessibility standards. The <blink> element itself is non-standard and deprecated! ...
... The blink
() method creates a <blink> HTML element that causes a string to blink. Warning: Blinking text is frowned upon by several accessibility standards. The <blink> element itself is non-standard and deprecated! ...
...And 2 more matches
String.fromCharCode() - JavaScript
The static String.fromCharCode
() method returns a string created from the specified sequence of UTF-16 code units. 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 String.fromCharCode(num1[, ...[, numN]]) Parameters num1, ..., numN A sequence of numbers that are UTF-16 code units. The range is between 0 and 65535 (0xFFFF). Numbers greater than 0xFFFF are truncated. No validity checks are performed. Return value A string of length N consisting of the N specified UTF-16 code units. Description This method returns a string and not a String object. ...
...e(num1[, ...[, numN]]) Parameters num1, ..., numN A sequence of numbers that are UTF-16 code units. The range is between 0 and 65535 (0xFFFF). Numbers greater than 0xFFFF are truncated. No validity checks are performed. Return value A string of length N consisting of the N specified UTF-16 code units. Description This method returns a string and not a String object. Because fromCharCode
() is a static method of String, you always use it as String.fromCharCode
(), rather than as a method of a String object you created. Returning supplementary characters In UTF-16, the most common characters can be represented by a single 16-bit value (i.e. a code unit). However, this set of characters, known as the Base Multilingual Plane (BMP), is only 1/17th of the total addressable Unicode code...
...e points. The remaining code points, in the range of 65536 (0x010000) to 1114111 (0x10FFFF) are known as supplementary characters. In UTF-16, supplementary characters are represented by two 16-bit code units, known as surrogates, that were reserved for this purpose. A valid combination of two surrogates used to represent a supplementary character is known as a surrogate pair. Because fromCharCode
() only works with 16-bit values (same as the \u escape sequence), a surrogate pair is required in order to return a supplementary character. For example, both String.fromCharCode(0xD83C, 0xDF03) and \uD83C\uDF03 return code point U+1F303 "Night with Stars". While there is a mathematical relationship between the supplementary code point value (e.g. 0x1F303) and both surrogate values that represent ...
...And 2 more matches
String.prototype.toLocaleLowerCase() - JavaScript
If multiple locales are given in an Array, the best available locale is used. The default locale is the host environment's current locale. ...
...If multiple locales are given in an Array, the best available locale is used. The default locale is the host environment's current locale. ...
...cale. Return value A new string representing the calling string converted to lower case, according to any locale-specific case mappings. Exceptions A RangeError ("invalid language tag: xx_yy") is thrown if a locale argument isn't a valid language tag. A TypeError ("invalid element in locales argument") is thrown if an array element isn't of type string. Description The toLocaleLowerCase
() method returns the value of the string converted to lower case according to any locale-specific case mappings. toLocaleLowerCase
() does not affect the value of the string itself. In most cases, this will produce the same result as toLowerCase
(), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. Examples...
...And 2 more matches
String.prototype.trimEnd() - JavaScript
Aliasing For consistency with functions like String.prototype.padEnd the standard method name is trimEnd. ...
... Aliasing For consistency with functions like String.prototype.padEnd the standard method name is trimEnd. ...
... Aliasing For consistency with functions like String.prototype.padEnd the standard method name is trimEnd. ...
...And 2 more matches
TypedArray.prototype.filter() - JavaScript
TypedArray is one of the typed array types here. 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 typedarray.filter(callback[, thisArg]) Parameters callback Function to test each element of the typed array. Invoked with arguments (element, index, typedarray). Return true to keep the element, false otherwise. thisArg Optional Value to use as this when executing callback. ...
...ull request. Syntax typedarray.filter(callback[, thisArg]) Parameters callback Function to test each element of the typed array. Invoked with arguments (element, index, typedarray). Return true to keep the element, false otherwise. thisArg Optional Value to use as this when executing callback. Return value A new typed array with the elements that pass the test. Description The filter
() method calls a provided callback function once for each element in a typed array, and constructs a new typed array of all the values for which callback returns a true value. callback is invoked only for indexes of the typed array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Typed array elements which do not pass the c...
...e index of the element the typed array object being traversed If a thisArg parameter is provided to filter, it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. ...
...And 2 more matches
Uint16Array() constructor - JavaScript
typedArray When called with a typedArray argument, which can be an object of any of the typed array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array. ...
...array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the typedArray argument. object When called with an object argument, a new typed array is created as if by the TypedArray.from
() method. buffer, byteOffset, length When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified ArrayBuffer. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is vie...
...h When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified ArrayBuffer. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed. Description The Uint16Array
() typed array constructor creates an array of 16-bit unsigned integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). Starting with ECMAScript 2015, Uint16Array const...
...And 2 more matches
Uint8ClampedArray() constructor - JavaScript
The Uint8ClampedArray
() constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ...
...ers clamped to 0-255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). Syntax new Uint8ClampedArray
(); // new in ES2017 new Uint8ClampedArray(length); new Uint8ClampedArray(typedArray); new Uint8ClampedArray(object); new Uint8ClampedArray(buffer [, byteOffset [, length]]); Parameters length When called with a length argument, an internal array buffer is created in memory, of size length multiplied by BYTES_PER_ELEMENT bytes, containing zeros. typedArray When called with a typedArray argume...
...array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the typedArray argument. object When called with an object argument, a new typed array is created as if by the TypedArray.from
() method. buffer, byteOffset, length When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified ArrayBuffer. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is vie...
...And 2 more matches
WebAssembly.Table() constructor - JavaScript
Syntax new WebAssembly.Table(tableDescriptor); Parameters tableDescriptor An object that can contain the following members: element A string representing the type of value to be stored in the table. At the moment this can only have a value of "anyfunc" (functions). initial The initial number of elements of the WebAssembly Table. maximum Optional The maximum number of elements the WebAssembly Table is allowed to grow to. Exceptions If tableDescriptor is not of type object, a TypeError is thrown. If maximum is specified and is smaller than initial, a RangeError is thrown. ...
...ypeError is thrown. If maximum is specified and is smaller than initial, a RangeError is thrown. Examples Creating a new WebAssembly Table instance The following example (see table2.html source code and live version) creates a new WebAssembly Table instance with an initial size of 2 elements. We then print out the table length and contents of the two indexes (retrieved via Table.prototype.get
() to show that the length is two and both elements are null. var tbl = new WebAssembly.Table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" We then create an import object that contains the table: var importObj = { js: { tbl:tbl } }; Finally, we load and instantiate a wasm module (table2.wasm) usi...
...h elements are null. var tbl = new WebAssembly.Table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" We then create an import object that contains the table: var importObj = { js: { tbl:tbl } }; Finally, we load and instantiate a wasm module (table2.wasm) using the WebAssembly.instantiateStreaming
() method. The table2.wasm module contains two functions (one that returns 42 and another that returns 83) and stores both into elements 0 and 1 of the imported table (see text representation). So after instantiation, the table still has length 2, but the elements now contain callable Exported WebAssembly Functions which we can call from JS. WebAssembly.instantiateStreaming(fetch('table2.wasm'), ...
...And 2 more matches
WebAssembly.Table.prototype.set() - JavaScript
Syntax table.set(index, value); Parameters index The index of the function reference you want to mutate. value The value you want to mutate the reference to. This must be an exported WebAssembly function, a JavaScript wrapper for an underlying wasm function. Return value Void. Exceptions If index is greater than or equal to Table.prototype.length, a RangeError is thrown. If value is not an exported WebAssembly function or null, a TypeError is thrown. Examples Using Table.set The following example (see table2.html source code and live version) creates a new WebAssembly Table instance with an initial size of 2 references. ...
...ototype.length, a RangeError is thrown. If value is not an exported WebAssembly function or null, a TypeError is thrown. Examples Using Table.set The following example (see table2.html source code and live version) creates a new WebAssembly Table instance with an initial size of 2 references. We then print out the table length and contents of the two indexes (retrieved via Table.prototype.get
()) to show that the length is two, and the indexes currently contain no function references (they currently return null). var tbl = new WebAssembly.Table({initial:2, element:"anyfunc"}); console.log(tbl.length); console.log(tbl.get(0)); console.log(tbl.get(1)); We then create an import object that contains a reference to the table: var importObj = { js: { tbl:tbl } }; Finally, we load a...
...ences (they currently return null). ...
...And 2 more matches
WebAssembly.instantiateStreaming() - JavaScript
This is the most efficient, optimized way to load wasm code. Syntax Promise<ResultObject> WebAssembly.instantiateStreaming(source, importObject); Parameters source A Response object or a promise that will fulfill with one, representing the underlying source of a .wasm module you want to stream, compile, and instantiate. importObject Optional An object containing the values to be imported into the newly-created Instance, such as functions or WebAssembly.Memory objects. There must be one matching property for each declared import of the compiled module or else a WebAssembly.LinkError is thrown. ...
...unctions or WebAssembly.Memory objects. There must be one matching property for each declared import of the compiled module or else a WebAssembly.LinkError is thrown. Return value A Promise that resolves to a ResultObject which contains two fields: module: A WebAssembly.Module object representing the compiled WebAssembly module. This Module can be instantiated again or shared via postMessage
(). instance: A WebAssembly.Instance object that contains all the Exported WebAssembly functions. Exceptions If either of the parameters are not of the correct type or structure, a TypeError is thrown. If the operation fails, the promise rejects with a WebAssembly.CompileError, WebAssembly.LinkError, or WebAssembly.RuntimeError, depending on the cause of the failure. Examples Instantiating...
...rror, WebAssembly.LinkError, or WebAssembly.RuntimeError, depending on the cause of the failure. Examples Instantiating streaming The following example (see our instantiate-streaming.html demo on GitHub, and view it live also) directly streams a .wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a ResultObject. ...
...And 2 more matches
Date.getVarDate() - Archive of obsolete content
These include objects in Visual Basic and Visual Basic Scripting Edition (VBScript). The actual format of the returned value depends on regional settings. ...
...These include objects in Visual Basic and Visual Basic Scripting Edition (VBScript). The actual format of the returned value depends on regional settings. ...
... (VBScript). ...
...he actual format of the returned value depends on regional settings. Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, and Internet Explorer 10 standards. Not supported in Windows 8.x Store apps. Applies To: Date Object See Also Date.getDate
() Date.parse
() ...
Object.prototype.unwatch() - Archive of obsolete content
Syntax obj.unwatch(prop) Parameters prop The name of a property of the object to stop watching. Return value undefined. Description The JavaScript debugger has functionality similar to that provided by this method, as well as other debugging options. ...
... Syntax obj.unwatch(prop) Parameters prop The name of a property of the object to stop watching. Return value undefined. Description The JavaScript debugger has functionality similar to that provided by this method, as well as other debugging options. ...
... Syntax obj.unwatch(prop) Parameters prop The name of a property of the object to stop watching. Return value undefined. Description The JavaScript debugger has functionality similar to that provided by this method, as well as other debugging options. For information on the debugger, see Venkman. ...
...atch(prop) Parameters prop The name of a property of the object to stop watching. Return value undefined. Description The JavaScript debugger has functionality similar to that provided by this method, as well as other debugging options. For information on the debugger, see Venkman. By default, this method is inherited by every object descended from Object. Note: The reason for unwatch
() to take the property name prop as its only parameter is due to the "single handler allowing" behavior of the watch
() method. Examples See watch
(). Specifications Not part of any standard. ...
HTMLIFrameElement.clearMatch()
Parameters None. Examples The following function is taken from our Browser API demo, and (amongst other things) clears the search results when the search bar is hidden, if an existing search is active. ...
...rs any content highlighted by findAll
() or findNext
(). Invoking this method results in a mozbrowserfindchange event firing, which carries details about the search results. Note: Use of the Browser API requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. See Using the Browser API for more details. Syntax instanceOfHTMLIframeElement.clearMatch
(); Returns Void. Parameters None. Examples The following function is taken from our Browser API demo, and (amongst other things) clears the search results when the search bar is hidden, if an existing search is active. See Implementing the search bar for more explanation. ...
...API for more details. Syntax instanceOfHTMLIframeElement.clearMatch
(); Returns Void. Parameters None. Examples The following function is taken from our Browser API demo, and (amongst other things) clears the search results when the search bar is hidden, if an existing search is active. See Implementing the search bar for more explanation. ...
...if an existing search is active. See Implementing the search bar for more explanation. searchToggle.addEventListener('touchend',function
() { if(search.getAttribute('class') === 'search') { search.setAttribute('class', 'search shifted'); } else if(search.getAttribute('class') === 'search shifted') { search.setAttribute('class', 'search'); if(searchActive) { browser.clearMatch
(); searchActive = false; prev.disabled = true; next.disabled = true; searchBar.value = ''; } } }); Specification Not part of any specification. ...
HTMLIFrameElement.getMuted()
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The getMuted
() method of the HTMLIFrameElement indicates whether the browser <iframe> is currently muted. Syntax There are two versions of this method, a callback version: var request = instanceOfHTMLIframeElement.getMuted
(); and a Promise version: instanceOfHTMLIframeElement.getMuted
().then(function(muted) { ... }); Returns Callback version: A DOMRequest that represents the get muted request. It has an onsuccess handler to handle the success case, and an onerror handler to handle the failu...
...he failure case. The muted value is available in the request.result property, and is a Boolean value -- true means muted, and false means unmuted. Promise version: A Promise that resolves with the muted value -- a Boolean where true means muted, and false means unmuted. Parameters None. ...
...is available in the request.result property, and is a Boolean value -- true means muted, and false means unmuted. Promise version: A Promise that resolves with the muted value -- a Boolean where true means muted, and false means unmuted. Parameters None. ...
...d false means unmuted. Parameters None. Example Callback version: var browser = document.querySelector('iframe'); var request = browser.getMuted
(); request.onsuccess = function
() { if(request.result) { console.log('The browser is muted.'); } else { console.log('The browser is unmuted.'); } } Promise version: var browser = document.querySelector('iframe'); browser.getMuted
().then(function(muted) { if(muted) { console.log('The browser is muted.'); } else { console.log('The browser is unmuted.'); } }); Specification Not part of any specification. ...
HTMLIFrameElement.getStructuredData()
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The getStructuredData
() method of the HTMLIFrameElement interface retrieves any structured microdata (and hCard and hCalendar microformat data) contained in the HTML loaded in the browser <iframe> and returns it as JSON. Syntax var instanceOfDOMRequest = instanceOfHTMLIframeElement.getStructuredData
(); Returns A DOMRequest to handle the getStructuredData
() request's success and error cases. If the request is successful, the request.result is a JSON object representation of all microdata containe...
...frameElement.getStructuredData
(); Returns A DOMRequest to handle the getStructuredData
() request's success and error cases. If the request is successful, the request.result is a JSON object representation of all microdata contained on the page loaded in the browser. Parameters None. ...
...DOMRequest to handle the getStructuredData
() request's success and error cases. If the request is successful, the request.result is a JSON object representation of all microdata contained on the page loaded in the browser. Parameters None. ...
...uredData
() request's success and error cases. If the request is successful, the request.result is a JSON object representation of all microdata contained on the page loaded in the browser. Parameters None. ...
HTMLIFrameElement.purgeHistory()
}); Returns Either A DOMRequest object that returns an onsuccess handler if the history is deleted, or an onerror handler if not. ...
...}); Returns Either A DOMRequest object that returns an onsuccess handler if the history is deleted, or an onerror handler if not. ...
...TMLIFrameElement interface is used to clear the browsing history associated with the browser <iframe>. It only deletes history, not cookies or other stored information. Note: To delete cookies for a Firefox OS app, you could call clearBrowserData
() on the actual app itself. Syntax There is a DOMRequest version and a Promise version: var myDOMRequest = instanceOfHTMLIframeElement.purgeHistory
(); instanceOfHTMLIframeElement.purgeHistory
().then(function
() { ... }); Returns Either A DOMRequest object that returns an onsuccess handler if the history is deleted, or an onerror handler if not. A Promise that resolves, with no parameters, if the history is deleted, or rejects if not. Parameters None. Examples DOMRequest: var browser = document.querySelector('iframe'); var request =...
...meElement.purgeHistory
().then(function
() { ... }); Returns Either A DOMRequest object that returns an onsuccess handler if the history is deleted, or an onerror handler if not. A Promise that resolves, with no parameters, if the history is deleted, or rejects if not. Parameters None. Examples DOMRequest: var browser = document.querySelector('iframe'); var request = browser.purgeHistory
(); request.onsuccess = function
() { console.log('History deleted!'); } request.onerror = function
() { console.error(this.error.name); } Promise: var browser = document.querySelector('iframe'); browser.purgeHistory
().then(function
() { console.log('History deleted!'); }, function(error) { console.error(this.error.name); }); Specification Not part of any specification. ...
Animation.play() - Web APIs
The play
() method of the Web Animations API's Animation Interface starts or resumes playing of an animation. If the animation is finished, calling play
() restarts the animation, playing it from the beginning. Syntax animation.play
(); Parameters None. Return value undefined Example In the Growing/Shrinking Alice Game example, clicking or tapping the cake causes Alice's growing animation (aliceChange) to play forward, causing her to get bigger, as well as triggering the cake's animation. ...
...imation is finished, calling play
() restarts the animation, playing it from the beginning. Syntax animation.play
(); Parameters None. Return value undefined Example In the Growing/Shrinking Alice Game example, clicking or tapping the cake causes Alice's growing animation (aliceChange) to play forward, causing her to get bigger, as well as triggering the cake's animation. ...
...ation.play
()s, one EventListener: // The cake has its own animation: var nommingCake = document.getElementById('eat-me_sprite').animate( [ { transform: 'translateY(0)' }, { transform: 'translateY(-80%)' } ], { fill: 'forwards', easing: 'steps(4, end)', duration: aliceChange.effect.timing.duration / 2 }); // Pause the cake's animation so it doesn't play immediately. nommingCake.pause
(); // This function will play when ever a user clicks or taps var growAlice = function
() { // Play Alice's animation. aliceChange.play
(); // Play the cake's animation. nommingCake.play
(); } // When a user holds their mouse down or taps, call growAlice to make all the animations play. cake.addEventListener("mousedown", growAlice, false); cake.addEventListener("touchstart", growAlice, fa...
...ation. aliceChange.play
(); // Play the cake's animation. nommingCake.play
(); } // When a user holds their mouse down or taps, call growAlice to make all the animations play. cake.addEventListener("mousedown", growAlice, false); cake.addEventListener("touchstart", growAlice, false); Specifications Specification Status Comment Web AnimationsThe definition of 'play
()' in that specification. Working Draft ...
Animation.reverse() - Web APIs
The Animation.reverse
() method of the Animation Interface reverses the playback direction, meaning the animation ends at its beginning. If called on an unplayed animation, the whole animation is played backwards. If called on a paused animation, the animation will continue in reverse. Syntax animation.reverse
(); Parameters None. Return value undefined Example In the Growing/Shrinking Alice Game example, clicking or tapping the bottle causes Alice's growing animation (aliceChange) to play backwards, causing her to get smaller. ...
...n, the animation will continue in reverse. Syntax animation.reverse
(); Parameters None. Return value undefined Example In the Growing/Shrinking Alice Game example, clicking or tapping the bottle causes Alice's growing animation (aliceChange) to play backwards, causing her to get smaller. ...
...Return value undefined Example In the Growing/Shrinking Alice Game example, clicking or tapping the bottle causes Alice's growing animation (aliceChange) to play backwards, causing her to get smaller. ...
...nking Alice Game example, clicking or tapping the bottle causes Alice's growing animation (aliceChange) to play backwards, causing her to get smaller. It is done by setting aliceChange's Animation.playbackRate to -1 like so: var shrinkAlice = function
() { // play Alice's animation in reverse aliceChange.playbackRate = -1; aliceChange.play
(); // play the bottle's animation drinking.play
() } But it could also have been done by calling reverse
() on aliceChange like so: var shrinkAlice = function
() { // play Alice's animation in reverse aliceChange.reverse
(); // play the bottle's animation drinking.play
() } Specifications Specification Status Comment Web AnimationsThe definition of 'reverse
()' in that specification. Working Draft ...
AnimationEvent() - Web APIs
type A DOMString representing the name of the type of the AnimationEvent. It is case-sensitive and can be: 'animationstart', 'animationend', or 'animationiteration'. animationName Optional A DOMString containing the value of the animation-name CSS property associated with the transition. It defaults to "". ...
... type A DOMString representing the name of the type of the AnimationEvent. It is case-sensitive and can be: 'animationstart', 'animationend', or 'animationiteration'. animationName Optional A DOMString containing the value of the animation-name CSS property associated with the transition. It defaults to "". ...
...turns a newly created AnimationEvent, representing an event in relation with an animation. Syntax animationEvent = new AnimationEvent(type, {animationName: aPropertyName, elapsedTime : aFloat, pseudoElement: aPseudoElementName}); Parameters The AnimationEvent
() constructor also inherits arguments from Event
(). type A DOMString representing the name of the type of the AnimationEvent. It is case-sensitive and can be: 'animationstart', 'animationend', or 'animationiteration'. animationName Optional A DOMString containing the value of the animation-name CSS property associated with the transition. It defaults to "". elapsedTime Optional A float giving the amount of time the animation has been runn...
... Working Draft Initial definition. ...
AudioBufferSourceNode.start() - Web APIs
Syntax AudioBufferSourceNode.start([when][, offset][, duration]); Parameters when Optional The time, in seconds, at which the sound should begin to play, in the same time coordinate system used by the AudioContext. If when is less than (AudioContext.currentTime, or if it's 0, the sound begins to play at once. The default value is 0. offset Optional An offset, specified as the number of seconds in the same time coordinate system as the AudioContext, to the time within the audio buffer that playback should begin. For example, to start playback halfway through a 10-second audio clip, offset should be 5. ...
...he sound buffer's natural sample rate, rather than the current playback rate, so even if the sound is playing at twice its normal speed, the midway point through a 10-second audio buffer is still 5. duration Optional The duration of the sound to be played, specified in seconds. If this parameter isn't specified, the sound plays until it reaches its natural conclusion or is stopped using the stop
() method. Using this parameter is functionally identical to calling start(when, offset) and then calling stop(when+duration). Return value undefined. Exceptions TypeError A negative value was specified for one or more of the three time parameters. Please don't attempt to tamper with the laws of temporal physics. InvalidStateError start
() has already been called. You can only call this fun...
...e of the three time parameters. Please don't attempt to tamper with the laws of temporal physics. InvalidStateError start
() has already been called. You can only call this function once during the lifetime of an AudioBufferSourceNode. Examples The most simple example just starts the audio buffer playing from the beginning -- you don't need to specify any parameters in this case: source.start
(); The following more complex example will, 1 second from now, start playing 10 seconds worth of sound starting 3 seconds into the audio buffer. source.start(audioCtx.currentTime + 1,3,10); For a more complete example showing start
() in use, check out our AudioContext.decodeAudioData
() example, You can also run the code example live, or view the source. Specifications Specification ...
...t playing 10 seconds worth of sound starting 3 seconds into the audio buffer. source.start(audioCtx.currentTime + 1,3,10); For a more complete example showing start
() in use, check out our AudioContext.decodeAudioData
() example, You can also run the code example live, or view the source. Specifications Specification Status Comment Web Audio APIThe definition of 'start
()' in that specification. Working Draft ...
AudioContext.createMediaStreamSource() - Web APIs
For more details about media stream audio source nodes, check out the MediaStreamAudioSourceNode reference page. Syntax audioSourceNode = audioContext.createMediaStreamSource(stream); Parameters stream A MediaStream to serve as an audio source to be fed into an audio processing graph for use and manipulation. Return value A new MediaStreamAudioSourceNode object representing the audio node whose media is obtained from the specified source stream. ...
...etUserMedia block - grab stream // put it into a MediaStreamAudioSourceNode // also output the visuals into a video element if (navigator.mediaDevices) { console.log('getUserMedia supported.'); navigator.mediaDevices.getUserMedia ({audio: true, video: true}) .then(function(stream) { video.srcObject = stream; video.onloadedmetadata = function(e) { video.play
(); video.muted = true; }; // Create a MediaStreamAudioSourceNode // Feed the HTMLMediaElement into it var audioCtx = new AudioContext
(); var source = audioCtx.createMediaStreamSource(stream); // Create a biquadfilter var biquadFilter = audioCtx.createBiquadFilter
(); biquadFilter.type = "lowshelf"; biquadFilter.fre...
...nect the AudioBufferSourceNode to the gainNode // and the gainNode to the destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(biquadFilter); biquadFilter.connect(audioCtx.destination); // Get new mouse pointer coordinates when mouse is moved // then set new gain value range.oninput = function
() { biquadFilter.gain.value = range.value; } }) .catch(function(err) { console.log('The following gUM error occured: ' + err); }); } else { console.log('getUserMedia not supported on your browser!'); } // dump script to pre element pre.innerHTML = myScript.innerHTML; Note: As a consequence of calling createMediaStreamSource
(), audio playback from the m...
... As a consequence of calling createMediaStreamSource
(), audio playback from the media stream will be re-routed into the processing graph of the AudioContext. So playing/pausing the stream can still be done through the media element API and the player controls. Specifications Specification Status Comment Web Audio APIThe definition of 'AudioContext.createMediaStreamSource
()' in that specification. Working Draft ...
AudioNode.disconnect() - Web APIs
If no parameters are provided, all outgoing connections are disconnected. destination Optional An AudioNode or AudioParam specifying the node or nodes to disconnect from. ...
...If no parameters are provided, all outgoing connections are disconnected. destination Optional An AudioNode or AudioParam specifying the node or nodes to disconnect from. ...
...Node is to be disconnected. The index numbers are defined according to the number of input channels (see Audio channels). If this parameter is out-of-bound, an IndexSizeError exception is thrown. Exceptions IndexSizeError A value specified for input or output is invalid, referring to a node which doesn't exist or outside the permitted range. ...
...xception is thrown. Exceptions IndexSizeError A value specified for input or output is invalid, referring to a node which doesn't exist or outside the permitted range. InvalidAccessError The node on which disconnect
() was called isn't connected to the specified destination node. Example var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext
(); var oscillator = audioCtx.createOscillator
(); var gainNode = audioCtx.createGain
(); oscillator.connect(gainNode); gainNode.connect(audioCtx.destination); gainNode.disconnect
(); Specifications Specification Status Comment Web Audio APIThe definition of 'disconnect' in that specification. Working Draft ...
AudioWorkletNode() - Web APIs
options Optional An object based on the AudioWorkletNodeOptions dictionary, which contains zero or more optional properties to configure the new node. ...
...de = 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. ...
...Available properties are as follows: numberOfInputs Optional The value to initialize the numberOfInputs property to. Defaults to 1. ...
...annelCount is 0 or larger than the current implementation supports. IndexSizeError The length of options.outputChannelCount array does not match options.numberOfOutputs. Example For a complete example demonstrating user-defined audio processing, see the AudioWorkletNode page. Specifications Specification Status Comment Web Audio APIThe definition of 'AudioWorkletNode
()' in that specification. Working Draft Initial definition. ...
AudioWorkletProcessor() - Web APIs
Syntax 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. var processor = new AudioWorkletProcessor(options); Parameters options An object that is passed as options parameter to AudioWorkletNode constructor and passed through the structured clone algorithm. The object is based on AudioWorkletNodeOptions dictionary. Available properties are as follows: numberOfInputs Optional The value to initialize the numberOfInputs property to. ...
...is example we pass custom options to the AudioWorkletNode constructor and observe how a structured clone of them gets passed to our AudioWorkletProcessor constructor. First, we need to define a custom AudioWorkletProcessor and register it. Note that this should be done in a separate file. // test-processor.js class TestProcessor extends AudioWorkletProcessor { constructor (options) { super
() console.log(options.numberOfInputs) console.log(options.processorOptions.someUsefulVariable) } process (inputs, outputs, parameters) { return true } } registerProcessor('test-processor', TestProcessor) Next, in our main script file we'll load the processor, create an instance of AudioWorkletNode passing it the name of the processor and options object. In the options object w...
...rocessor('test-processor', TestProcessor) Next, in our main script file we'll load the processor, create an instance of AudioWorkletNode passing it the name of the processor and options object. In the options object we pass processorOptions with a Map instance under someUsefulVariable key. We don't pass numberOfInputs and see how it gets its default value. ...
... Working Draft Initial definition. ...
BaseAudioContext.createDynamicsCompressor() - Web APIs
The createDynamicsCompressor
() method of the BaseAudioContext Interface is used to create a DynamicsCompressorNode, which can be used to apply compression to an audio signal. Compression lowers the volume of the loudest parts of the signal and raises the volume of the softest parts. Overall, a louder, richer, and fuller sound can be achieved. It is especially important in games and musical applications where large numbers of individual sounds are played simultaneously, where you want to control the overall signal level and help avoid clipping (distorting) of the audio output. Syntax baseAudioCtx.createDynamicsCompressor
(); Returns A DynamicsCompressorNode. Example The below code demonstrates a simple usage of createDynamicsCompressor
() to add compression to an audio track. For a mo...
...rates a simple usage of createDynamicsCompressor
() to add compression to an audio track. For a more complete example, have a look at our basic Compressor example (view the source code). ...
...ValueAtTime(-50, audioCtx.currentTime); compressor.knee.setValueAtTime(40, audioCtx.currentTime); compressor.ratio.setValueAtTime(12, audioCtx.currentTime); compressor.attack.setValueAtTime(0, audioCtx.currentTime); compressor.release.setValueAtTime(0.25, audioCtx.currentTime); // connect the AudioBufferSourceNode to the destination source.connect(audioCtx.destination); button.onclick = function
() { var active = button.getAttribute('data-active'); if(active == 'false') { button.setAttribute('data-active', 'true'); button.innerHTML = 'Remove compression'; source.disconnect(audioCtx.destination); source.connect(compressor); compressor.connect(audioCtx.destination); } else if(active == 'true') { button.setAttribute('data-active', 'false'); button.innerHTML =...
... Working Draft ...
BaseAudioContext.createPeriodicWave() - Web APIs
Syntax var wave = AudioContext.createPeriodicWave(real, imag[, constraints]); Returns A PeriodicWave. Parameters real An array of cosine terms (traditionally the A terms). imag An array of sine terms (traditionally the B terms). The real and imag arrays have to have the same length, otherwise an error is thrown. ...
...whether normalization should be disabled (if not specified, normalization is enabled by default.) It takes one property: disableNormalization: If set to true, normalization is disabled for the periodic wave. The default is false. If normalized, the resulting wave will have a maximum absolute peak value of 1. ...
...true, normalization is disabled for the periodic wave. The default is false. If normalized, the resulting wave will have a maximum absolute peak value of 1. Example The following example illustrates simple usage of createPeriodicWave
(), to create a PeriodicWave object containing a simple sine wave. var real = new Float32Array(2); var imag = new Float32Array(2); var ac = new AudioContext
(); var osc = ac.createOscillator
(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createPeriodicWave(real, imag, {disableNormalization: true}); osc.setPeriodicWave(wave); osc.connect(ac.destination); osc.start
(); osc.stop(2); This works because a sound that contains only a fundamental tone is by definition a sine wave Here, we create a PeriodicWave with two values. The fi...
... values. The first value is the DC offset, which is the value at which the oscillator starts. 0 is good here, because we want to start the curve at the middle of the [-1.0; 1.0] range. The second and subsequent values are sine and cosine components. You can think of it as the result of a Fourier transform, where you get frequency domain values from time domain value. Here, with createPeriodicWave
(), you specify the frequencies, and the browser performs an inverse Fourier transform to get a time domain buffer for the frequency of the oscillator. Here, we only set one component at full volume (1.0) on the fundamental tone, so we get a sine wave. The coefficients of the Fourier transform should be given in ascending order (i.e. (a+bi)ei,(c+di)e2i,(f+gi)e3i\left(a+bi\right)e^{i} , \left(c+di\r...
BaseAudioContext.createStereoPanner() - Web APIs
The createStereoPanner
() method of the BaseAudioContext interface creates a StereoPannerNode, which can be used to apply stereo panning to an audio source. It positions an incoming audio stream in a stereo image using a low-cost equal-power panning algorithm. Syntax baseAudioContext.createStereoPanner
(); Returns A StereoPannerNode. Example In our StereoPannerNode example (see source code) HTML we have a simple <audio> element along with a slider <input> to increase and decrease pan value. In the JavaScript we create a MediaElementAudioSourceNode and a StereoPannerNode, and connect the two together using the connect
() method. We then use an oninput event handler to change the value of the StereoPannerNode.pan parameter and update the pan value display when the slider is moved. Movin...
...ther using the connect
() method. We then use an oninput event handler to change the value of the StereoPannerNode.pan parameter and update the pan value display when the slider is moved. Moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. ...
...Audio = document.querySelector('audio'); var panControl = document.querySelector('.panning-control'); var panValue = document.querySelector('.panning-value'); pre.innerHTML = myScript.innerHTML; // Create a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it var source = audioCtx.createMediaElementSource(myAudio); // Create a stereo panner var panNode = audioCtx.createStereoPanner
(); // Event handler function to increase panning to the right and left // when the slider is moved panControl.oninput = function
() { panNode.pan.setValueAtTime(panControl.value, audioCtx.currentTime); panValue.innerHTML = panControl.value; } // connect the MediaElementAudioSourceNode to the panNode // and the panNode to the destination, so we can play the // music and adjust the panning usin...
... Working Draft ...
BiquadFilterNode.getFrequencyResponse() - Web APIs
The two output arrays, magResponseOutput and phaseResponseOutput, must be created before calling this method; they must be the same size as the array of input frequency values (frequencyArray). Syntax BiquadFilterNode.getFrequencyResponse(frequencyArray, magResponseOutput, phaseResponseOutput); Parameters frequencyArray A Float32Array containing an array of frequencies, specified in Hertz, which you want to filter. ...
...ay(5); var phaseResponseOutput = new Float32Array(5); Next we create a <ul> element in our HTML to contain our results, and grab a reference to it in our JavaScript: <p>Biquad filter frequency response for: </p> <ul class="freq-response-output"> </ul> var freqResponseOutput = document.querySelector('.freq-response-output'); Finally, after creating our biquad filter, we use getFrequencyResponse
() to generate the response data and put it in our arrays, then loop through each data set and output them in a human-readable list at the bottom of the page: var biquadFilter = audioCtx.createBiquadFilter
(); biquadFilter.type = "lowshelf"; biquadFilter.frequency.value = 1000; biquadFilter.gain.value = range.value; ... function calcFrequencyResponse
() { biquadFilter.getFrequencyResponse(myFr...
... Working Draft ...
... Working Draft ...
Bluetooth.getAvailability() - Web APIs
Return value A Promise that resolves with Boolean. Exceptions This method doesn't throw any exceptions. ...
... Return value A Promise that resolves with Boolean. Exceptions This method doesn't throw any exceptions. ...
... Bluetooth interface of Web Bluetooth API interface exposes the Bluetooth capabilities of the current device. For a returns a Boolean which is true if the deveice has a Bluetooth adapter and false otherwise (unless user configured User Agent not to expose a real value). Note: User might not allow use of Web Bluetooth API, even if getAvailability
() returned true (navigator.bluetooth.requestDevice
() might not resolve with a BluetoothDevice). Also, user can configure User Agent to return a fixed value instead of a real one. Syntax var readerPromise = Bluetooth.getAvailability
(); Parameters None. Return value A Promise that resolves with Boolean. Exceptions This method doesn't throw any exceptions. Examples The following snippet prints out a message in the console specifying wheter...
... User Agent to return a fixed value instead of a real one. Syntax var readerPromise = Bluetooth.getAvailability
(); Parameters None. Return value A Promise that resolves with Boolean. Exceptions This method doesn't throw any exceptions. Examples The following snippet prints out a message in the console specifying wheter or not Bluetooth is supported: navigator.bluetooth.getAvailability
().then(available => { if (available) console.log("This device supports Bluetooth!"); else console.log("Doh! Bluetooth is not supported"); }); Specifications Specification Status Comment Web BluetoothThe definition of 'getAvailability
()' in that specification. Draft Initial definition. ...
CanvasRenderingContext2D.clip() - Web APIs
The CanvasRenderingContext2D.clip
() method of the Canvas 2D API turns the current or given path into the current clipping region. It replaces any previous clipping region. In the image below, the red outline represents a clipping region shaped like a star. Only those parts of the checkerboard pattern that are within the clipping region get drawn. Note: Be aware that the clipping region is only constructed from shapes added to the path. It doesn't work with shape primitives drawn directly to the canvas, such as fillRect
(). Instead, you'd have to use rect
() to add a rectangular shape to the path before calling clip
(). Syntax void ctx.clip([fillRule]); void ctx.clip(path [, fillRule]); Parameters fillRule The algorithm by which to determine if a point is inside or outside the cli...
...clip([fillRule]); void ctx.clip(path [, fillRule]); Parameters fillRule The algorithm by which to determine if a point is inside or outside the clipping region. Possible values: "nonzero": The non-zero winding rule. Default rule. "evenodd": The even-odd winding rule. path A Path2D path to use as the clipping region. Examples A simple clipping region This example uses the clip
() method to create a clipping region according to the shape of a circular arc. Two rectangles are then drawn; only those parts within the clipping region are rendered. HTML <canvas id="canvas"></canvas> JavaScript The clipping region is a full circle, with its center at (100, 75), and a radius of 50. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Cr...
...ng to the shape of a circular arc. Two rectangles are then drawn; only those parts within the clipping region are rendered. HTML <canvas id="canvas"></canvas> JavaScript The clipping region is a full circle, with its center at (100, 75), and a radius of 50. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Create circular clipping region ctx.beginPath
(); ctx.arc(100, 75, 50, 0, Math.PI * 2); ctx.clip
(); // Draw stuff that gets clipped ctx.fillStyle = 'blue'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = 'orange'; ctx.fillRect(0, 0, 100, 100); Result Specifying a path and a fillRule This example saves two rectangles to a Path2D object, which is then made the current clipping region using the clip
() method. The "evenodd" ...
...ect, which is then made the current clipping region using the clip
() method. The "evenodd" rule creates a hole where the clipping rectangles intersect; by default (with the "nonzero" rule), there would be no hole. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Create clipping path let region = new Path2D
(); region.rect(80, 10, 20, 130); region.rect(40, 50, 100, 50); ctx.clip(region, "evenodd"); // Draw stuff that gets clipped ctx.fillStyle = 'blue'; ctx.fillRect(0, 0, canvas.width, canvas.height); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.clip' in that specification. Living Standard ...
CanvasRenderingContext2D.closePath() - Web APIs
The CanvasRenderingContext2D.closePath
() method of the Canvas 2D API attempts to add a straight line from the current point to the start of the current sub-path. If the shape has already been closed or has only one point, this function does nothing. This method doesn't draw anything to the canvas directly. You can render the path using the stroke
() or fill
() methods. Syntax void ctx.closePath
(); Examples Closing a triangle This example creates the first two (diagonal) sides of a triangle using the lineTo
() method. After that, the triangle's base is created with the closePath
() method, which automatically connects the shape's first and last points. HTML <canvas id="canvas"></canvas> JavaScript The triangle's corners are at (20, 150), (120, 20), and (220, 150). const canvas = doc...
...s of a triangle using the lineTo
() method. After that, the triangle's base is created with the closePath
() method, which automatically connects the shape's first and last points. HTML <canvas id="canvas"></canvas> JavaScript The triangle's corners are at (20, 150), (120, 20), and (220, 150). const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath
(); ctx.moveTo(20, 140); // Move pen to bottom-left corner ctx.lineTo(120, 10); // Line to top corner ctx.lineTo(220, 140); // Line to bottom-right corner ctx.closePath
(); // Line to bottom-left corner ctx.stroke
(); Result Closing just one sub-path This example draws a smiley face consisting of three disconnected sub-paths. ...
...etContext('2d'); ctx.beginPath
(); ctx.moveTo(20, 140); // Move pen to bottom-left corner ctx.lineTo(120, 10); // Line to top corner ctx.lineTo(220, 140); // Line to bottom-right corner ctx.closePath
(); // Line to bottom-left corner ctx.stroke
(); Result Closing just one sub-path This example draws a smiley face consisting of three disconnected sub-paths. Note: Although closePath
() is called after all the arcs have been created, only the last arc (sub-path) gets closed. HTML <canvas id="canvas"></canvas> JavaScript The first two arcs create the face's eyes. The last arc creates the mouth. ...
...ey face consisting of three disconnected sub-paths. Note: Although closePath
() is called after all the arcs have been created, only the last arc (sub-path) gets closed. HTML <canvas id="canvas"></canvas> JavaScript The first two arcs create the face's eyes. The last arc creates the mouth. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath
(); ctx.arc(240, 20, 40, 0, Math.PI); ctx.moveTo(100, 20); ctx.arc(60, 20, 40, 0, Math.PI); ctx.moveTo(215, 80); ctx.arc(150, 80, 65, 0, Math.PI); ctx.closePath
(); ctx.lineWidth = 6; ctx.stroke
(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.closePath' in that specification. Living Standard ...
CanvasRenderingContext2D.createPattern() - Web APIs
This method returns a CanvasPattern. This method doesn't draw anything to the canvas directly. The pattern it creates must be assigned to the CanvasRenderingContext2D.fillStyle or CanvasRenderingContext2D.strokeStyle properties, after which it is applied to any subsequent drawing. Syntax CanvasPattern ctx.createPattern(image, repetition); Parameters image A CanvasImageSource to be used as the pattern's image. ...
...are: "repeat" (both directions) "repeat-x" (horizontal only) "repeat-y" (vertical only) "no-repeat" (neither direction) If repetition is specified as an empty string ("") or null (but not undefined), a value of "repeat" will be used. Return value CanvasPattern An opaque object describing a pattern. ...
... createPattern
() method to create a CanvasPattern with a repeating source image. Once created, the pattern is assigned to the canvas context's fill style and applied to a rectangle. The original image looks like this: HTML <canvas id="canvas" width="300" height="300"></canvas> JavaScript var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var img = new Image
(); img.src = 'https://udn.realityripple.com/samples/04/aaeaf9aac4.png'; img.onload = function
() { var pattern = ctx.createPattern(img, 'repeat'); ctx.fillStyle = pattern; ctx.fillRect(0, 0, 300, 300); }; Creating a pattern from a canvas In this example we create a pattern from the contents of an offscreen canvas. We then apply it to the fill style of our primary canvas, and fill that can...
...t('canvas'); const patternContext = patternCanvas.getContext('2d'); // Give the pattern a width and height of 50 patternCanvas.width = 50; patternCanvas.height = 50; // Give the pattern a background color and draw an arc patternContext.fillStyle = '#fec'; patternContext.fillRect(0, 0, patternCanvas.width, patternCanvas.height); patternContext.arc(0, 0, 50, 0, .5 * Math.PI); patternContext.stroke
(); // Create our primary canvas and fill it with the pattern const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const pattern = ctx.createPattern(patternCanvas, 'repeat'); ctx.fillStyle = pattern; ctx.fillRect(0, 0, canvas.width, canvas.height); // Add our primary canvas to the webpage document.body.appendChild(canvas); Result Specifications Specif...
CanvasRenderingContext2D.drawFocusIfNeeded() - Web APIs
The CanvasRenderingContext2D.drawFocusIfNeeded
() method of the Canvas 2D API draws a focus ring around the current or given path, if the specified element is focused. Syntax void ctx.drawFocusIfNeeded(element); void ctx.drawFocusIfNeeded(path, element); Parameters element The element to check whether it is focused or not. path A Path2D path to use. Examples Managing button focus This example draws two buttons on a canvas. The drawFocusIfNeeded
() method is used to draw a focus ring when appropriate. HTML <canvas id="canvas"> <button id="button1">Continue</button> <button id="button2">Quit</button> </canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const button1 = document.getElementById('button1'); const button2 ...
...="button2">Quit</button> </canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const button1 = document.getElementById('button1'); const button2 = document.getElementById('button2'); document.addEventListener('focus', redraw, true); document.addEventListener('blur', redraw, true); canvas.addEventListener('click', handleClick, false); redraw
(); function redraw
() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawButton(button1, 20, 20); drawButton(button2, 20, 80); } function handleClick(e) { // Calculate click coordinates const x = e.clientX - canvas.offsetLeft; const y = e.clientY - canvas.offsetTop; // Focus button1, if appropriate drawButton(button1, 20, 20); if (ctx.isPointInPath(x, y)) { button1.focu...
... function redraw
() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawButton(button1, 20, 20); drawButton(button2, 20, 80); } function handleClick(e) { // Calculate click coordinates const x = e.clientX - canvas.offsetLeft; const y = e.clientY - canvas.offsetTop; // Focus button1, if appropriate drawButton(button1, 20, 20); if (ctx.isPointInPath(x, y)) { button1.focus
(); } // Focus button2, if appropriate drawButton(button2, 20, 80); if (ctx.isPointInPath(x, y)) { button2.focus
(); } } function drawButton(el, x, y) { const active = document.activeElement === el; const width = 150; const height = 40; // Button background ctx.fillStyle = active ? 'pink' : 'lightgray'; ctx.fillRect(x, y, width, height); // Button text ctx.font = '15...
... Living Standard Initial definition ...
CanvasRenderingContext2D.drawImage() - Web APIs
Syntax void ctx.drawImage(image, dx, dy); void ctx.drawImage(image, dx, dy, dWidth, dHeight); void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight); Parameters image An element to draw into the context. The specification permits any canvas image source (CanvasImageSource), specifically, a CSSImageValue, an HTMLImageElement, an SVGImageElement, an HTMLVideoElement, an HTMLCanvasElement, an ImageBitmap, or an OffscreenCanvas. sx Optional The x-axis coordinate of the top left corner of the sub-rectangle of the source image to draw into the destination context. ...
... If the canvas or source rectangle width or height is zero. INVALID_STATE_ERR The image has no image data. TYPE_MISMATCH_ERR The specified source element isn't supported. NS_ERROR_NOT_AVAILABLE The image is not loaded yet. Use .complete === true and .onload to determine when it is ready. Examples Drawing an image to the canvas This example draws an image to the canvas using the drawImage
() method. HTML <canvas id="canvas"></canvas> <div style="display:none;"> <img id="source" src="https://udn.realityripple.com/samples/db/f374e9c6fc.jpg" width="300" height="227"> </div> JavaScript The source image is taken from the coordinates (33, 71), with a width of 104 and a height of 124. It is drawn to the canvas at (21, 20), where it is given a width of 87 and a height of...
... of 124. It is drawn to the canvas at (21, 20), where it is given a width of 87 and a height of 104. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const image = document.getElementById('source'); image.addEventListener('load', e => { ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104); }); Result Understanding source element size The drawImage
() method uses the source element's intrinsic size in CSS pixels when drawing. For example, if you load an Image and specify the optional size parameters in its constructor, you will have to use the naturalWidth and naturalHeight properties of the created instance to properly calculate things like crop and scale regions, rather than element.width and element.height. The same goes for videoWidth and...
.../canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const image = new Image(60, 45); // Using optional size for image image.onload = drawImageActualSize; // Draw when image has loaded // Load an image of intrinsic size 300x227 in CSS pixels image.src = 'https://udn.realityripple.com/samples/db/f374e9c6fc.jpg'; function drawImageActualSize
() { // Use the intrinsic size of image in CSS pixels for the canvas element canvas.width = this.naturalWidth; canvas.height = this.naturalHeight; // Will draw the image as 300x227, ignoring the custom size of 60x45 // given in the constructor ctx.drawImage(this, 0, 0); // To use the custom size we'll have to specify the scale parameters // using the element's width and height prop...
CanvasRenderingContext2D.fill() - Web APIs
The CanvasRenderingContext2D.fill
() method of the Canvas 2D API fills the current or given path with the current fillStyle. Syntax void ctx.fill([fillRule]); void ctx.fill(path [, fillRule]); Parameters fillRule The algorithm by which to determine if a point is inside or outside the filling region. Possible values: "nonzero": The non-zero winding rule. Default rule. "evenodd": The even-odd winding rule. path A Path2D path to fill. Examples Filling a rectangle This example fills a rectangle with the fill
() method. ...
...values: "nonzero": The non-zero winding rule. Default rule. "evenodd": The even-odd winding rule. path A Path2D path to fill. Examples Filling a rectangle This example fills a rectangle with the fill
() method. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 10, 150, 100); ctx.fill
(); Result Specifying a path and a fillRule This example saves some intersecting lines to a Path2D object. The fill
() method is then used to render the object to the canvas. A hole is left unfilled in the object's center by using the "evenodd" rule; by default (with the "nonzero" rule), the hole would also be filled. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.ge...
...2D object. The fill
() method is then used to render the object to the canvas. A hole is left unfilled in the object's center by using the "evenodd" rule; by default (with the "nonzero" rule), the hole would also be filled. ...
... (with the "nonzero" rule), the hole would also be filled. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Create path let region = new Path2D
(); region.moveTo(30, 90); region.lineTo(110, 20); region.lineTo(240, 130); region.lineTo(60, 130); region.lineTo(190, 20); region.lineTo(270, 90); region.closePath
(); // Fill path ctx.fillStyle = 'green'; ctx.fill(region, 'evenodd'); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.fill' in that specification. Living Standard ...
CanvasRenderingContext2D.isPointInPath() - Web APIs
Syntax ctx.isPointInPath(x, y [, fillRule]); ctx.isPointInPath(path, x, y [, fillRule]); Parameters x The x-axis coordinate of the point to check, unaffected by the current transformation of the context. y The y-axis coordinate of the point to check, unaffected by the current transformation of the context. fillRule The algorithm by which to determine if a point is inside or outside the path. Possible values: "nonzero": The non-zero winding rule. Default rule. "evenodd": The even-odd winding rule. path A Path2D path to check against. If unspecified, the current path is used. ...
...nonzero": The non-zero winding rule. Default rule. "evenodd": The even-odd winding rule. path A Path2D path to check against. If unspecified, the current path is used. Return value Boolean A Boolean, which is true if the specified point is contained in the current or specified path, otherwise false. ...
...If yes, the circle becomes green, otherwise it is red. ...
...Path(30, 70); Result Checking a point in the specified path Whenever you move the mouse, this example checks whether the cursor is in a circular Path2D path. If yes, the circle becomes green, otherwise it is red. ...
CanvasRenderingContext2D.rotate() - Web APIs
Examples Rotating a shape This example rotates a rectangle by 45?. Note that the center of rotation is the top-left corner of the canvas, and not a location relative to any shape. ...
... Examples Rotating a shape This example rotates a rectangle by 45?. Note that the center of rotation is the top-left corner of the canvas, and not a location relative to any shape. ...
...ng a shape This example rotates a rectangle by 45?. Note that the center of rotation is the top-left corner of the canvas, and not a location relative to any shape. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Point of transform origin ctx.arc(0, 0, 5, 0, 2 * Math.PI); ctx.fillStyle = 'blue'; ctx.fill
(); // Non-rotated rectangle ctx.fillStyle = 'gray'; ctx.fillRect(100, 0, 80, 20); // Rotated rectangle ctx.rotate(45 * Math.PI / 180); ctx.fillStyle = 'red'; ctx.fillRect(100, 0, 80, 20); // Reset transformation matrix to the identity matrix ctx.setTransform(1, 0, 0, 1, 0, 0); Result The center of rotation is blue. The non-rotated rectangle is gray, and the rotated rectangle is red. Rotati...
....fillRect(100, 0, 80, 20); // Reset transformation matrix to the identity matrix ctx.setTransform(1, 0, 0, 1, 0, 0); Result The center of rotation is blue. The non-rotated rectangle is gray, and the rotated rectangle is red. Rotating a shape around its center This example rotates a shape around its center point. To do this, the following steps are applied to the matrix: First, translate
() moves the matrix's origin to the shape's center. rotate
() rotates the matrix by the desired amount. Finally, translate
() moves the matrix's origin back to its starting point. This is done by applying the values of the shape's center coordinates in a negative direction. HTML <canvas id="canvas"></canvas> JavaScript The shape is a rectangle with its corner at (80, 60), a width of 140, a hei...
ChildNode.before() - Web APIs
DOMString objects are inserted as equivalent Text nodes. Syntax [Throws, Unscopable] void ChildNode.before((Node or DOMString)... nodes); Parameters nodes A set of Node or DOMString objects to insert. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. ...
...ld(child); child.before("Text"); console.log(parent.outerHTML); // "<div>Text<p></p></div>" Inserting an element and text var parent = document.createElement("div"); var child = document.createElement("p"); parent.appendChild(child); var span = document.createElement("span"); child.before(span, "Text"); console.log(parent.outerHTML); // "<div><span></span>Text<p></p></div>" ChildNode.before
() is unscopable The before
() method is not scoped into the with statement. See Symbol.unscopables for more information. 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 (functi...
...ternet 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) { if (item.hasOwnProperty('before')) { return; } Object.defineProperty(item, 'before', { configurable: true, enumerable: true, writable: true, value: function before
() { var argArr = Array.prototype.slice.call(arguments), docFrag = document.createDocumentFragment
(); argArr.forEach(function (argItem) { var isNode = argItem instanceof Node; docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); }); this.parentNode.insertBefore(docFrag, this); } }); }); })([Eleme...
... Living Standard Initial definition. ...
Clipboard.read() - Web APIs
The read
() method of the Clipboard interface requests a copy of the clipboard's contents, delivering the data to the returned Promise when the promise is resolved. Unlike readText
(), the read
() method can return arbitrary data, such as images. This method can also return text. To read from the clipboard, you must first have the "clipboard-read" permission. Note: The asynchronous Clipboard and Permissions APIs are still in the process of being integrated into most browsers, so they often deviate from the official rules for permissions and the like. Be sure to review the compatibility table before using these methods. Syntax var promise = navigator.clipboard.read
(); Parameters None. Return value A Promise that resolves with a DataTransfer object containing the clipboard's contents. ...
...If it's not a png image, an error message is presented. ...
...ipboard's contents. // First, ask the Permissions API if we have some kind of access to // the "clipboard-read" feature. navigator.permissions.query({name: "clipboard-read"}).then(result => { // If permission to read the clipboard is granted or if the user will // be prompted to allow it, we proceed. if (result.state == "granted" || result.state == "prompt") { navigator.clipboard.read
().then(data => { for (let i=0; i<data.items.length; i++) { if (data.items[i].type != "image/png") { alert("Clipboard contains non-image data. Unable to access it."); } else { const blob = data.items[i].getType("image/png"); imgElem.src = URL.createObjectURL(blob); } } }); } }); Note: At this time, while Firefox does implemen...
...data => { for (let i=0; i<data.items.length; i++) { if (data.items[i].type != "image/png") { alert("Clipboard contains non-image data. Unable to access it."); } else { const blob = data.items[i].getType("image/png"); imgElem.src = URL.createObjectURL(blob); } } }); } }); Note: At this time, while Firefox does implement read
(), it does not recognize the "clipboard-read" permission, so attempting to use the Permissions API to manage access to the API will not work. Specifications Specification Status Comment Clipboard API and eventsThe definition of 'read
()' in that specification. Working Draft Initial definition. ...
Clipboard.write() - Web APIs
This can be used to implement cut and copy functionality. The "clipboard-write" permission of the Permissions API, is granted automatically to pages when they are in the active tab. Note: Browser support for the asynchronous clipboard APIs is still in the process of being implemented. Be sure to check the compatibility table as well as Clipboard availability in Clipboard for more information. Syntax var promise = navigator.clipboard.write(data) Parameters data An array of ClipboardItem objects containing data to be written to the clipboard. Return value A Promise which is resolved when the data has been written to the clipboard. ...
...romise which is resolved when the data has been written to the clipboard. The promise is rejected if the clipboard is unable to complete the clipboard access. Example This example function replaces the current contents of the clipboard with a specified string. function setClipboard(text) { let data = [new ClipboardItem({ "text/plain": text })]; navigator.clipboard.write(data).then(function
() { /* success */ }, function
() { /* failure */ }); } The code begins by creating a new ClipboardItem object into which the text will be placed for sending to the clipboard. The key of the object passed to the ClipboardItem constructor indicates the content type, the value indicates the content. The content could be a text or even a Blob (e.g. for copying images to the clipboard). The...
.../* success */ }, function
() { /* failure */ }); } The code begins by creating a new ClipboardItem object into which the text will be placed for sending to the clipboard. The key of the object passed to the ClipboardItem constructor indicates the content type, the value indicates the content. The content could be a text or even a Blob (e.g. for copying images to the clipboard). Then write
() is called, specifying both a fulfilment function and an error function. ...
...a Blob (e.g. for copying images to the clipboard). Then write
() is called, specifying both a fulfilment function and an error function. Example of copying canvas contents to the clipboard function copyCanvasContentsToClipboard(canvas, onDone, onError) { canvas.toBlob(function (blob) { let data = [new ClipboardItem({ [blob.type]: blob })]; navigator.clipboard.write(data).then(function
() { onDone
(); }, function (err) { onError(err); }) }); } Note: You can only pass in one clipboard item at a time. Specifications Specification Status Comment Clipboard API and eventsThe definition of 'write
()' in that specification. Working Draft Initial definition. ...
ClipboardItem() - Web APIs
The ClipboardItem
() constructor of the Clipboard API creates a new ClipboardItem object which represents data to be stored or retrieved via the Clipboard API, that is clipboard.write
() and clipboard.read
() respectively. Note: Image format support varies by browser. See the browser compatibility table for the Clipboard interface. Syntax var ClipboardItem = new ClipboardItem(ClipboardItemData); Parameters ClipboardItemData An Object with the MIME type as the key and Blob as the value. Note: To work with text see the Clipboard.readText
() and Clipboard.writeText
() methods of the Clipboard interface. ...
...d interface. Syntax var ClipboardItem = new ClipboardItem(ClipboardItemData); Parameters ClipboardItemData An Object with the MIME type as the key and Blob as the value. Note: To work with text see the Clipboard.readText
() and Clipboard.writeText
() methods of the Clipboard interface. Examples The below example requests a png image using the Fetch API, and in turn, the responses' blob
() method, to create a new ClipboardItem and write it to the clipboard, using the Clipboard API. Note: You can only pass in one clipboard item at a time. ...
...: To work with text see the Clipboard.readText
() and Clipboard.writeText
() methods of the Clipboard interface. Examples The below example requests a png image using the Fetch API, and in turn, the responses' blob
() method, to create a new ClipboardItem and write it to the clipboard, using the Clipboard API. Note: You can only pass in one clipboard item at a time. ...
...les The below example requests a png image using the Fetch API, and in turn, the responses' blob
() method, to create a new ClipboardItem and write it to the clipboard, using the Clipboard API. Note: You can only pass in one clipboard item at a time. async function writeClipImg
() { try { const imgURL = '/myimage.png'; const data = await fetch(imgURL); const blob = await data.blob
(); await navigator.clipboard.write([ new ClipboardItem({ [blob.type]: blob }) ]); console.log('Fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } Specifications Specification Status Comment Clipboard API and eventsThe definition of 'ClipboardItem' in that specification. Working Draft Initial def...
Console.group() - Web APIs
Creates a new inline group in the Web Console log. This indents following console messages by an additional level, until console.groupEnd
() is called. Note: This feature is available in Web Workers. Syntax console.group([label]); Parameters label Label for the group. Optional. (Chrome 59 tested) Does not work with console.groupEnd
(). Using groups in the console Requires Gecko 9.0(Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) You can use nested groups to help organize your output by visually associating related messages. To create a new nested block, call console.group
(). ...
...el]); Parameters label Label for the group. Optional. (Chrome 59 tested) Does not work with console.groupEnd
(). Using groups in the console Requires Gecko 9.0(Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) You can use nested groups to help organize your output by visually associating related messages. To create a new nested block, call console.group
(). The console.groupCollapsed
() method is similar, but the new block is collapsed and requires clicking a disclosure button to read it. Note: From Gecko 9 until Gecko 51, the groupCollapsed
() method was the same as group
(). Collapsed groups are fully supported starting in Gecko 52. See bug 1088360. To exit the current group, call console.groupEnd
(). For example, given this code: console.log("This is the outer level"); consol...
... is similar, but the new block is collapsed and requires clicking a disclosure button to read it. Note: From Gecko 9 until Gecko 51, the groupCollapsed
() method was the same as group
(). Collapsed groups are fully supported starting in Gecko 52. See bug 1088360. To exit the current group, call console.groupEnd
(). For example, given this code: console.log("This is the outer level"); console.group
(); console.log("Level 2"); console.group
(); console.log("Level 3"); console.warn("More of level 3"); console.groupEnd
(); console.log("Back to level 2"); console.groupEnd
(); console.log("Back to the outer level"); The output looks like this: See Using groups in the console in the documentation of console for more details. Specifications Specification Status Comment ...
...onsole.log("Level 3"); console.warn("More of level 3"); console.groupEnd
(); console.log("Back to level 2"); console.groupEnd
(); console.log("Back to the outer level"); The output looks like this: See Using groups in the console in the documentation of console for more details. Specifications Specification Status Comment Console APIThe definition of 'console.group
()' in that specification. Living Standard Initial definition ...
console.log() - Web APIs
The Console method log
() outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects. Note: This feature is available in Web Workers. Syntax console.log(obj1 [, obj2, ..., objN]); console.log(msg [, subst1, ..., substN]); Parameters obj1 ... objN A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. ...
...... objN A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you call console.log
(), but it is the value of the object at the moment you open the console. msg A JavaScript string containing zero or more substitution strings. subst1 ... substN JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. See Outputting text to the console in the documentation of console for details. Difference bet...
... is the value of the object at the moment you open the console. msg A JavaScript string containing zero or more substitution strings. subst1 ... substN JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. See Outputting text to the console in the documentation of console for details. Difference between log
() and dir
() You might ask yourself what's the difference between console.dir
() and console.log
(). Another useful difference in Chrome exists when sending DOM elements to the console. Notice: console.log prints the element in an HTML-like tree console.dir prints the element in a JSON-like tree Specifically, console.log gives special treatment to DOM elements, whereas console.dir does not.
... Living Standard Initial definition ...
Console.timeLog() - Web APIs
If a label parameter is included, but there is no corresponding timer: Timer "timer name" doesn't exist. ...
... If a label parameter is included, but there is no corresponding timer: Timer "timer name" doesn't exist. ...
... Living Standard Initial definition ...
..."); alert("Do a bunch of other stuff..."); console.timeEnd("answer time"); The output from the example above shows the time taken by the user to dismiss the first alert box, followed by the time it took for the user to dismiss the second alert: Notice that the timer's name is displayed when the timer value is logged using timeLog
() and again when it's stopped. In addition, the call to timeEnd
() has the additional information, "timer ended" to make it obvious that the timer is no longer tracking time. Specifications Specification Status Comment Console APIThe definition of 'console.timeLog
()' in that specification. Living Standard Initial definition ...
CustomElementRegistry.get() - Web APIs
The get
() method of the CustomElementRegistry interface returns the constructor for a previously-defined custom element. Syntax constructor = customElements.get(name); Parameters name The name of the custom element whose constructor you want to return a reference to. Return value The constructor for the named custom element, or undefined if there is no custom element definition with that name. ...
...ed custom element. Syntax constructor = customElements.get(name); Parameters name The name of the custom element whose constructor you want to return a reference to. Return value The constructor for the named custom element, or undefined if there is no custom element definition with that name. ...
...t. Syntax constructor = customElements.get(name); Parameters name The name of the custom element whose constructor you want to return a reference to. Return value The constructor for the named custom element, or undefined if there is no custom element definition with that name. ...
... Living Standard Initial definition. ...
DOMException() - Web APIs
Candidate Recommendation Adds the constructor for the DOMException class. ...
... Candidate Recommendation Adds the constructor for the DOMException class. ...
...ters message Optional A description of the exception. If not present, the empty string '' is used. name Optional Returns a DOMString that contains one of the strings associated with an error constant. Return value DOMException A newly created DOMException object. Example TBD Specifications Specification Status Comment Web IDLThe definition of 'DOMException
()' in that specification. Candidate Recommendation Adds the constructor for the DOMException class. Browser Compatibility The compatibility table on this page is generated from 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 ExplorerOperaSafariAndro...
... 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. ...
DOMTokenList.forEach() - Web APIs
The forEach
() method of the DOMTokenList interface calls the callback given in parameter once for each value pair in the list, in insertion order. Syntax tokenList.forEach(callback [, thisArg]); Parameters callback Function to execute for each element, eventually taking three arguments: currentValue The current element being processed in the array. currentIndex The index of the current element being processed in the array. listObj The array that forEach
() is being applied to. thisArg Optional Value to use as this when executing callback. Return value undefined. Example In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. ...
...e current element being processed in the array. listObj The array that forEach
() is being applied to. thisArg Optional Value to use as this when executing callback. Return value undefined. Example In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We when retrieve an iterator containing the values using forEach
(), writing each one to the <span>'s Node.textContent inside the forEach
() inner function. ...
...etrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We when retrieve an iterator containing the values using forEach
(), writing each one to the <span>'s Node.textContent inside the forEach
() inner function. ...
... Living Standard Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome ...
DOMTokenList.replace() - Web APIs
Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. ...
... Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. ...
...ely, without adding the new token to the token list. Syntax tokenList.replace(oldToken, newToken); Parameters oldToken A DOMString representing the token you want to replace. newToken A DOMString representing the token you want to replace oldToken with. Return value A boolean value, which is true if oldToken was successfully replaced, or false if not. Note: In older browsers, replace
() returns void. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then replace a token in the list, and write the list into the <span>'s Node.textContent. First, the HTML: <span class="a b c"></span> Now the JavaScript: let span = document.querySelector("span"); let classes = span.classList; let result = c...
...ng code will only work with IE10-11. To use with earlier versions of IE, refer to the polyfill at element.classList#Polyfill DOMTokenList.prototype.replace = function (a, b) { if (this.contains(a)) { this.add(b); this.remove(a); return true; } return false; } Specifications Specification Status Comment DOMThe definition of 'replace
()' in that specification. Living Standard Initial definition ...
DataTransfer.getData() - Web APIs
The DataTransfer.getData
() method retrieves drag data (as a DOMString) for the specified type. If the drag operation does not include data, this method returns an empty string. Example data types are text/plain and text/uri-list. Syntax dataTransfer.getData(format); Arguments format A DOMString representing the type of data to retrieve. Return value DOMString A DOMString representing the drag data for the specified format. If the drag operation has no data or the operation has no data for the specified format, this method returns an empty string. Caveats Data availability The HTML5 Drag and Drop Specification dictates a drag data store mode. This may result in unexpected behavior, being DataTransfer.getData
() not returning an expected value. Example This example show...
...e drag operation has no data or the operation has no data for the specified format, this method returns an empty string. Caveats Data availability The HTML5 Drag and Drop Specification dictates a drag data store mode. This may result in unexpected behavior, being DataTransfer.getData
() not returning an expected value. Example This example shows the use of the DataTransfer object's getData
() and setData
() methods. HTML Content <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"> <span id="drag" draggable="true" ondragstart="drag(event)">drag me to the other box</span> </div> <div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div> CSS Content #div1, #div2 { width:100px; height:50px; padding:10px; border:1px solid #aaaaaa; } Jav...
...="true" ondragstart="drag(event)">drag me to the other box</span> </div> <div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div> CSS Content #div1, #div2 { width:100px; height:50px; padding:10px; border:1px solid #aaaaaa; } JavaScript Content function allowDrop(allowdropevent) { allowdropevent.target.style.color = 'blue'; allowdropevent.preventDefault
(); } function drag(dragevent) { dragevent.dataTransfer.setData("text", dragevent.target.id); dragevent.target.style.color = 'green'; } function drop(dropevent) { dropevent.preventDefault
(); var data = dropevent.dataTransfer.getData("text"); dropevent.target.appendChild(document.getElementById(data)); document.getElementById("drag").style.color = 'black'; } Result Spec...
...target.style.color = 'green'; } function drop(dropevent) { dropevent.preventDefault
(); var data = dropevent.dataTransfer.getData("text"); dropevent.target.appendChild(document.getElementById(data)); document.getElementById("drag").style.color = 'black'; } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'getData
()' in that specification. Living Standard HTML 5.1The definition of 'getData
()' in that specification. Recommendation Initial definition ...
DataTransferItemList.DataTransferItem() - Web APIs
Syntax dataItem = DataTransferItem[index]; Parameters index The zero-based index of the item in the drag data list to return. Return value The DataTransferItem object at the specified index in the item list. If the index is less than zero or greater than or equal to the number of items in the list (as indicated by the list's length property, undefined is returned. The returned value is never null. Example This example shows how to use drag and drop. ...
... drag payload so the drop handler will // know which element to add to its tree var dataList = ev.dataTransfer.items; dataList.add(ev.target.id, "text/plain"); // Add some other items to the drag payload dataList.add("<p>... ...
... data[i].getAsString(function (s){ console.log("... Drop: HTML = " + s); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI data[i].getAsString(function (s){ console.log("... ...
...i].getAsString(function (s){ console.log("... ...
DataTransferItemList.clear() - Web APIs
The DataTransferItemList method clear
() removes all DataTransferItem objects from the drag data items list, leaving the list empty. The drag data store in which this list is kept is only writable while handling the dragstart event. While handling drop, the drag data store is in read-only mode, and this method silently does nothing. No exception is thrown. Syntax DataTransferItemList.clear
(); Parameters None. Return value undefined Example This example shows the use of the clear
() method. HTML <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" on...
... drag payload so the drop handler will // know which element to add to its tree var dataList = ev.dataTransfer.items; dataList.add(ev.target.id, "text/plain"); // Add some other items to the drag payload dataList.add("<p>... ...
... data[i].getAsString(function (s){ console.log("... Drop: HTML = " + s); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI data[i].getAsString(function (s){ console.log("... ...
... }); } } } function dragover_handler(ev) { console.log("dragOver"); ev.preventDefault
(); // Set the dropEffect to move ev.dataTransfer.dropEffect = "move" } function dragend_handler(ev) { console.log("dragEnd"); var dataList = ev.dataTransfer.items; for (var i = 0; i < dataList.length; i++) { dataList.remove(i); } // Clear any remaining drag data dataList.clear
(); } Result Result link Specifications Specification Status Comment HTML Living StandardThe definition of 'clear
()' in that specification. Living Standard HTML 5.1The definition of 'clear
()' in that specification. Recommendation Not included in W3C HTML5 Recommendation ...
Document.createDocumentFragment() - Web APIs
Usage notes DocumentFragments are DOM Node objects which are never part of the main DOM tree. The usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all its children. ...
...is replaced by all its children. Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element's position and geometry). Historically, using document fragments could result in better performance. ...
...e the DocumentFragment constructor to create a new fragment: let fragment = new DocumentFragment
(); Example This example creates a list of major web browsers in a DocumentFragment, then adds the new DOM subtree to the document to be displayed. ...
... Living Standard Initial definition in the DOM 1 specification. ...
Document.createElement() - Web APIs
In Firefox, Opera, and Chrome, createElement(null) works like createElement("null"). ...
...y tagName, or an HTMLUnknownElement if tagName isn't recognized. Syntax let element = document.createElement(tagName[, options]); Parameters tagName A string that specifies the type of element to be created. The nodeName of the created element is initialized with the value of tagName. Don't use qualified names (like "html:a") with this method. When called on an HTML document, createElement
() converts tagName to lower case before creating the element. In Firefox, Opera, and Chrome, createElement(null) works like createElement("null"). options Optional An optional ElementCreationOptions object, containing a single property named is, whose value is the tag name of a custom element previously defined via customElements.define
(). See Web component example for more details. Return valu...
...ore details. Return value The new Element. Examples Basic example This creates a new <div> and inserts it before the element with the ID "div1". ...
...getElementById("div1"); document.body.insertBefore(newDiv, currentDiv); } Web component example The following example snippet is taken from our expanding-list-web-component example (see it live also). In this case, our custom element extends the HTMLUListElement, which represents the <ul> element. // Create a class for the element class ExpandingList extends HTMLUListElement { constructor
() { // Always call super first in constructor super
(); // constructor definition left out for brevity ... } } // Define the new element customElements.define('expanding-list', ExpandingList, { extends: "ul" }); If we wanted to create an instance of this element programmatically, we'd use a call along the following lines: let expandingList = document.createElement('ul', { is : ...
Document.evaluate() - Web APIs
rrespond to integers from 0 to 9. result is an existing XPathResult to use for the results. null is the most common and will create a new XPathResult Example var headings = document.evaluate("/html/body//h2", document, null, XPathResult.ANY_TYPE, null); /* Search the document for all h2 elements. * The result will likely be an unordered node iterator. */ var thisHeading = headings.iterateNext
(); var alertText = "Level 2 headings in this document are:\n"; while (thisHeading) { alertText += thisHeading.textContent + "\n"; thisHeading = headings.iterateNext
(); } alert(alertText); // Alerts the text of all h2 elements Note, in the above example, a more verbose XPath is preferred over common shortcuts such as //h2. Generally, more specific XPath selectors as in the above example usuall...
...example, the "." is important to indicate that the querying should start from the context node, document.body. If the "." was left out (leaving //h2) the query would start from the root node (html) which would be more wasteful.) See Introduction to using XPath in JavaScript for more information. Notes XPath expressions can be evaluated on HTML and XML documents. While using document.evaluate
() works in FF2, in FF3 one must use someXMLDoc.evaluate
() if evaluating against something other than the current document. Result types (Merge with Template:XPathResultConstants? These are supported values for the resultType parameter of the evaluate method: Result Type Value Description ANY_TYPE 0 Whatever type naturally results from the given expression. ...
... Result types (Merge with Template:XPathResultConstants? These are supported values for the resultType parameter of the evaluate method: Result Type Value Description ANY_TYPE 0 Whatever type naturally results from the given expression. NUMBER_TYPE 1 A result set containing a single number. Useful, for example, in an XPath expression using the count
() function. STRING_TYPE 2 A result set containing a single string. BOOLEAN_TYPE 3 A result set containing a single boolean value. Useful, for example, an an XPath expression using the not
() function. UNORDERED_NODE_ITERATOR_TYPE 4 A result set containing all the nodes matching the expression. The nodes in the result set are not necessarily in the same or...
... 10.1Safari iOS Full support 4.2Samsung Internet Android Full support 1.0Legend Full support Full support No support No support See also Document.createExpression
() XPathResult XPath Code Snippets Check for browser support ...
Document.getElementById() - Web APIs
Syntax var element = document.getElementById(id); Parameters id The ID of the element to locate. The ID is case-sensitive string which is unique within the document; only one element may have any given ID. Return value An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document. ...
...Because ID values must be unique throughout the entire document, there is no need for "...
...tml> JavaScript function changeColor(newColor) { var elem = document.getElementById('para'); elem.style.color = newColor; } Result Usage notes The capitalization of "Id" in the name of this method must be correct for the code to function; getElementByID
() is not valid and will not work, however natural it may seem. Unlike some other element-lookup methods such as Document.querySelector
() and Document.querySelectorAll
(), getElementById
() is only available as a method of the global document object, and not available as a method on all element objects in the DOM. Because ID values must be unique throughout the entire document, there is no need for "local" versions of the function. Example <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> ...
...tElementById is not a function </script> </body> </html> If there is no element with the given id, this function returns null. Note that the id parameter is case-sensitive, so document.getElementById("Main") will return null instead of the element <div id="main"> because "M" and "m" are different for the purposes of this method. Elements not in the document are not searched by getElementById
(). When creating an element and assigning it an ID, you have to insert the element into the document tree with Node.insertBefore
() or a similar method before you can access it with getElementById
(): var element = document.createElement('div'); element.id = 'testqq'; var el = document.getElementById('testqq'); // el will be null! Non-HTML documents. The DOM implementation must have information th...
Document.querySelector() - Web APIs
If no matches are found, null is returned. Note: The matching is done using depth-first pre-order traversal of the document's nodes starting with the first element in the document's markup and iterating through sequential nodes by order of the number of child nodes. Syntax element = document.querySelector(selectors); Parameters selectors A DOMString containing one or more selectors to match. This string must be a valid CSS selector string; if it isn't, a SYNTAX_ERR exception is thrown. See Locating DOM elements using selectors for more about selectors and how to manage them. ...
...ally careful when writing string literals using these characters. See Escaping special characters for more information. Return value An HTMLElement object representing the first element in the document that matches the specified set of CSS selectors, or null is returned if there are no matches. If you need a list of all elements matching the specified selectors, you should use querySelectorAll
() instead. Exceptions SYNTAX_ERR The syntax of the specified selectors is invalid. Usage notes If the specified selector matches an ID that is incorrectly used more than once in the document, the first element with that ID is returned. CSS pseudo-elements will never return any elements, as specified in the Selectors API. Escaping special characters To match against an ID or selectors tha...
...ng special characters To match against an ID or selectors that do not follow standard CSS syntax (by using a colon or space inappropriately, for example), you must escape the character with a backslash ("\"). ...
... Living Standard ...
DocumentOrShadowRoot.getSelection() - Web APIs
The getSelection
() property of the DocumentOrShadowRoot interface returns a Selection object representing the range of text selected by the user, or the current position of the caret. Syntax var selection = documentOrShadowRootInstance.getSelection
() Parameters None. Returns A Selection object. Example function foo
() { var selObj = document.getSelection
(); alert(selObj); var selRange = selObj.getRangeAt(0); // do stuff with the range } Notes String representation of the Selection object In JavaScript, when an object is passed to a function expecting a string (like Window.alert
()), the object's toString
() method is called and the returned value is passed to the function. This can make the object appear to be a string when used with other functions when it...
...representation of the Selection object In JavaScript, when an object is passed to a function expecting a string (like Window.alert
()), the object's toString
() method is called and the returned value is passed to the function. This can make the object appear to be a string when used with other functions when it is really an object with properties and methods. In the above example, selObj.toString
() is automatically called when it is passed to Window.alert
(). ...
... methods. In the above example, selObj.toString
() is automatically called when it is passed to Window.alert
(). However, attempting to use a JavaScript String property or method such as length or substr directly on a Selection object results in an error if it does not have that property or method and may return unexpected results if it does. To use a Selection object as a string, call its toString
() method directly: var selectedText = selObj.toString
(); selObj is a Selection object. selectedText is a string (Selected text). Related objects You can call Window.getSelection
(), which works identically to Document.getSelection
(). It is worth noting that currently getSelection
() doesn't work on the content of <input> elements in Firefox. ...
... Notice also the difference between selection and focus. Document.activeElement returns the focused element. Specifications Specification Status Comment Shadow DOMThe definition of 'DocumentOrShadowRoot' in that specification. Obsolete Initial definition. ...
Element.animate() - Web APIs
The Element interface's animate
() method is a shortcut method which creates a new Animation, applies it to the element, then plays the animation. It returns the created Animation object instance. Elements can have multiple animations applied to them. You can get a list of the animations that affect an element by calling Element.getAnimations
(). Syntax var animation = element.animate(keyframes, options); Parameters keyframes Either an array of keyframe objects, or a keyframe object whose property are arrays of values to iterate over. See Keyframe Formats for more details. ...
....animate(keyframes, options); Parameters keyframes Either an array of keyframe objects, or a keyframe object whose property are arrays of values to iterate over. See Keyframe Formats for more details. options Either an integer representing the animation's duration (in milliseconds), or an Object containing one or more timing properties: id Optional A property unique to animate
(): a DOMString with which to reference the animation. delay Optional The number of milliseconds to delay the start of the animation. Defaults to 0. direction Optional Whether the animation runs forwards (normal), backwards (reverse), switches direction after each iteration (alternate), or runs backwards and switches direction after each iteration (alternate-reverse). Defaults to "normal". ...
...not blur(2) blur(5). replace overwrites the previous value with the new one. iterationComposite Optional Determines how values build from iteration to iteration in this animation. Can be set to accumulate or replace (see above). Defaults to replace. Return value Returns an Animation. Examples In the demo Down the Rabbit Hole (with the Web Animation API), we use the convenient animate
() method to immediately create and play an animation on the #tunnel element to make it flow upwards, infinitely. Notice the array of objects passed as keyframes and also the timing options block. document.getElementById("tunnel").animate([ // keyframes { transform: 'translateY(0px)' }, { transform: 'translateY(-300px)' } ], { // timing options duration: 1000, iterations: Infinity }); ...
... Working Draft Initial definition ...
Element.getAttributeNames() - Web APIs
The getAttributeNames
() method of the Element interface returns the attribute names of the element as an Array of strings. If the element has no attributes it returns an empty array. Using getAttributeNames
() along with getAttribute
(), is a memory-efficient and performant alternative to accessing Element.attributes. ...
... The getAttributeNames
() method of the Element interface returns the attribute names of the element as an Array of strings. If the element has no attributes it returns an empty array. Using getAttributeNames
() along with getAttribute
(), is a memory-efficient and performant alternative to accessing Element.attributes. ...
...attribute names of the element as an Array of strings. If the element has no attributes it returns an empty array. Using getAttributeNames
() along with getAttribute
(), is a memory-efficient and performant alternative to accessing Element.attributes. ...
...performant alternative to accessing Element.attributes. Syntax let attributeNames = element.getAttributeNames
(); Example // Iterate over element's attributes for (let name of element.getAttributeNames
()) { let value = element.getAttribute(name); console.log(name, value); } Polyfill if (Element.prototype.getAttributeNames == undefined) { Element.prototype.getAttributeNames = function
() { var attributes = this.attributes; var length = attributes.length; var result = new Array(length); for (var i = 0; i < length; i++) { result[i] = attributes[i].name; } return result; }; } Specifications Specification Status Comment DOMThe definition of 'Element.getAttributeNames' in that specification. Living Standard Initial de...
Element.getClientRects() - Web APIs
Each DOMRect object contains read-only left, top, right and bottom properties describing the border box, in pixels, with the top-left relative to the top-left of the viewport. For tables with captions, the caption is included even though it's outside the border box of the table. ...
...JavaScript The JavaScript code draws the client rects for all HTML elements that have CSS class withClientRectsOverlay assigned. function addClientRectsOverlay(elt) { /* Absolutely position a div over each client rect so that its border width is the same as the rectangle's width. Note: the overlays will be out of place if the user resizes or zooms. ...
....style.padding = '0'; tableRectDiv.style.top = (rect.top + scrollTop) + 'px'; tableRectDiv.style.left = (rect.left + scrollLeft) + 'px'; // We want rect.width to be the border width, so content width is 2px less. ...
... 'px'; tableRectDiv.style.height = (rect.height - 2) + 'px'; document.body.appendChild(tableRectDiv); } } (function
() { /* Call function addClientRectsOverlay(elt) for all elements with assigned class "withClientRectsOverlay" */ var elt = document.getElementsByClassName('withClientRectsOverlay'); for (var i = 0; i < elt.length; i++) { addClientRectsOverlay(elt[i]); } })
(); Result Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'Element.getClientRects
()' in that specification. Working Draft Initial definition Notes getClientRects
() was first introduced in the MS IE DHTML object model. ...
Element.getElementsByClassName() - Web APIs
Syntax var elements = element.getElementsByClassName(names); Parameters names A DOMString containing one or more class names to match on, separated by whitespace. Return value An HTMLCollection providing a live-updating list of every element which is a member of every class in names. ...
... true; as elements no longer match the set of names, they are immediately removed from the collection. In quirks mode, the class names are compared in a case-insensitive fashion. Otherwise, they're case sensitive. ...
...However the following code will not work as one might expect because "matches" will change as soon as any "colorbox" class is removed. var matches = element.getElementsByClassName('colorbox'); for (var i=0; i<matches.length; i++) { matches[i].classList.remove('colorbox'); matches...
... as the method's this value. Here we'll find all <div> elements that have a class of test: var testElements = document.getElementsByClassName('test'); var testDivs = Array.prototype.filter.call(testElements, function(testElement) { return testElement.nodeName === 'DIV'; }); Specifications Specification Status Comment DOMThe definition of 'Element.getElementsByClassName
()' in that specification. Living Standard Initial definition ...
Element.matches() - Web APIs
Syntax var result = element.matches(selectorString); Parameters selectorString is a string representing the selector to test. Return value result is a Boolean. Exceptions SYNTAX_ERR The specified selector string is invalid. ...
...lementsByTagName('li'); for (var i = 0; i < birds.length; i++) { if (birds[i].matches('.endangered')) { console.log('The ' + birds[i].textContent + ' is endangered!'); } } </script> This will log "The Philippine eagle is endangered!" to the console, since the element has indeed a class attribute with value endangered. ...
...r (var i = 0; i < birds.length; i++) { if (birds[i].matches('.endangered')) { console.log('The ' + birds[i].textContent + ' is endangered!'); } } </script> This will log "The Philippine eagle is endangered!" to the console, since the element has indeed a class attribute with value endangered. ...
...i].matches('.endangered')) { console.log('The ' + birds[i].textContent + ' is endangered!'); } } </script> This will log "The Philippine eagle is endangered!" to the console, since the element has indeed a class attribute with value endangered. ...
Element.removeAttribute() - Web APIs
Many attributes will not behave as expected if you set them to null. ...
...Many attributes will not behave as expected if you set them to null. ...
...Many attributes will not behave as expected if you set them to null. ...
...Many attributes will not behave as expected if you set them to null. ...
Element.setAttribute() - Web APIs
Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value. To get the current value of an attribute, use getAttribute
(); to remove an attribute, call removeAttribute
(). Syntax Element.setAttribute(name, value); Parameters name A DOMString specifying the name of the attribute whose value is to be set. The attribute name is automatically converted to all lower-case when setAttribute
() is called on an HTML element in an HTML document. value A DOMString containing the value to assign to the attribute. Any non-string value specified is converted automatically into a string. Boolean attributes are considered to be true if they're present on the element at all, re...
...attribute's name; this works but is non-standard). See the example below for a practical demonstration. Since the specified value gets converted into a string, specifying null doesn't necessarily do what you expect. Instead of removing the attribute or setting its value to be null, it instead sets the attribute's value to the string "null". If you wish to remove an attribute, call removeAttribute
(). Return value undefined. Exceptions InvalidCharacterError The specified attribute name contains one or more characters which are not valid in attribute names. Example In the following example, setAttribute
() is used to set attributes on a <button>. HTML <button>Hello World</button> JavaScript var b = document.querySelector("button"); b.setAttribute("name", "helloButton"); b.setAttr...
...You can see this using your browser's page inspector (Chrome, Edge, Firefox, Safari). To set the value of a Boolean attribute, such as disabled, you can specify any value. ...
... Living Standard ...
Element.toggleAttribute() - Web APIs
force Optional A boolean value to determine whether the attribute should be added or removed, no matter whether the attribute is present or not at the moment. Return value true if attribute name is eventually present, and false otherwise. ...
... force Optional A boolean value to determine whether the attribute should be added or removed, no matter whether the attribute is present or not at the moment. Return value true if attribute name is eventually present, and false otherwise. ...
... determine whether the attribute should be added or removed, no matter whether the attribute is present or not at the moment. Return value true if attribute name is eventually present, and false otherwise. Exceptions InvalidCharacterError The specified attribute name contains one or more characters which are not valid in attribute names. ...
...ntains one or more characters which are not valid in attribute names. Example In the following example, toggleAttribute
() is used to toggle the readonly attribute of a <input>. ...
Event.initEvent() - Web APIs
The page on Creating and triggering events gives more information about the way to use these. Syntax event.initEvent(type, bubbles, cancelable); type Is a DOMString defining the type of event. bubbles Is a Boolean deciding whether the event should bubble up through the event chain or not. ...
...The page on Creating and triggering events gives more information about the way to use these. Syntax event.initEvent(type, bubbles, cancelable); type Is a DOMString defining the type of event. bubbles Is a Boolean deciding whether the event should bubble up through the event chain or not. ...
...The page on Creating and triggering events gives more information about the way to use these. Syntax event.initEvent(type, bubbles, cancelable); type Is a DOMString defining the type of event. bubbles Is a Boolean deciding whether the event should bubble up through the event chain or not. ...
...nt. var event = document.createEvent('Event'); // Create a click event that bubbles up and // cannot be canceled event.initEvent('click', true, false); // Listen for the event. elem.addEventListener('click', function (e) { // e.target matches elem }, false); elem.dispatchEvent(event); Specifications Specification Status Comment DOMThe definition of 'Event.initEvent
()' in that specification. Living Standard From Document Object Model (DOM) Level 2 Events Specification, deprecated it, superseded by event constructors. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'Event.initEvent
()' in that specification. Obsolete Initial definition. Browser compatibility The compatibility table on this page is generated ...
EventTarget() - Web APIs
The EventTarget
() constructor creates a new EventTarget object instance. Syntax var myEventTarget = new EventTarget
(); Parameters None. Return value An instance of the EventTarget object. ...
... The EventTarget
() constructor creates a new EventTarget object instance. Syntax var myEventTarget = new EventTarget
(); Parameters None. Return value An instance of the EventTarget object. ...
... The EventTarget
() constructor creates a new EventTarget object instance. Syntax var myEventTarget = new EventTarget
(); Parameters None. Return value An instance of the EventTarget object. ...
... Living Standard ...
FileSystemDirectoryEntry.removeRecursively() - Web APIs
Syntax FileSystemDirectoryEntry.removeRecursively(successCallback[, errorCallback]); Parameters successCallback A function to call once the directory removal process has completed. The callback has no parameters. errorCallback Optional A function to be called if an error occurs while attempting to remove the directory subtree. Receives a FileError describing the error which occurred as input. Return value undefined. ...
...y concerns as raised by the user agent or the operating system. If you try to delete a directory which contains one or more files that can't be removed, or if an error occurs while deletion of a number of files is underway, some files may not be deleted. You should provide an errorCallback to watch for and handle this, perhaps by trying again. Example directory.removeRecursively(function
() { /* The directory was removed successfully */ }, function
() { /* an error occurred while removing the directory */ }); 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 ExplorerOp...
...ewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetremoveRecursively DeprecatedNon-standardChrome Full support 8Edge Full support 79Firefox No support 50 -- 52Notes No support 50 -- 52Notes Notes While the removeRecursively
() method existed, it immediately called the error callback with NS_ERROR_DOM_SECURITY_ERR.IE No support NoOpera No support NoSafari No support NoWebView Android Full support <=37Chrome Android Full support...
... NoSafari No support NoWebView Android Full support <=37Chrome Android Full support 18Firefox Android No support 50 -- 52Notes No support 50 -- 52Notes Notes While the removeRecursively
() method existed, it immediately called the error callback with NS_ERROR_DOM_SECURITY_ERR.Opera Android No support NoSafari iOS No support NoSamsung Internet Android Full support YesLegend Full support ...
FileSystemEntry.toURL() - Web APIs
This is done by exposing a new URL scheme--filesystem:--that can be used as the value of src and href attributes. Syntax FileSystemEntry.toURL([mimeType]); Parameters mimeType Optional An optional string specifying the MIME type to use when interpreting the file. This can be used to help deal with files whose types aren't recognized automatically by the user agent. If this parameter is omitted, the user agent uses its standard algorithms to identify the file. ...
...elp deal with files whose types aren't recognized automatically by the user agent. If this parameter is omitted, the user agent uses its standard algorithms to identify the file. ...
...rithms to identify the file. Return value A DOMString containing a URL that can then be used as a document reference in HTML content, or an empty string if the URL can't be generated (such as if the file system implementation doesn't support toURL
()). Example If you have a FileSystemFileEntry corresponding to an image file in a file system available to your Web site or app, you can call toURL
() to get its URL for use in HTML. If your site is located at http://my-awesome-website.woot, and you have a temporary file system that contains an image file named awesomesauce.jpg, the URL returned by toURL
() might be (depending on the browser's implementation) something like "filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg". Code that makes use of this might look like this: ...
...some-website.woot, and you have a temporary file system that contains an image file named awesomesauce.jpg, the URL returned by toURL
() might be (depending on the browser's implementation) something like "filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg". Code that makes use of this might look like this: let img = document.createElement("img"); img.src = imageFileEntry.toURL
(); document.body.appendChild(img); Assuming the scenario mentioned before the code, the result would be HTML that looks like this being appended to the end of the document: <img src="filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg"> Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please c...
GainNode() - Web APIs
Working Draft Initial definition. ...
... Working Draft Initial definition. ...
... the AudioNodeOptions dictionary. context A reference to an AudioContext. options Optional Options are as follows: gain: The amount of gain to apply. This parameter is a-rate and it's nominal range is (-?,+?). The default is 1. Return value A new GainNode object instance. Specifications Specification Status Comment Web Audio APIThe definition of 'GainNode
()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for...
...n. 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. ...
HTMLDialogElement.show() - Web APIs
The show
() method of the HTMLDialogElement interface displays the dialog modelessly, i.e. still allowing interaction with content outside of the dialog. Syntax dialogInstance.show
(); Parameters None. Return value Void. Examples The following example shows a simple button that, when clicked, opens a <dialog> containing a form via the show
() method. From there you can click the Cancel button to close the dialog (via the HTMLDialogElement.close
() method), or submit the form via the submit button. <!-- Simple pop-up dialog box, containing a form --> <dialog id="favDialog"> <form method="dialog"> <section> <p><label for="favAnimal">Favorite animal:</label> <select id="favAnimal" name="favAnimal"> <option></option> <option>Brine shrimp<...
...ption>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function
() { var updateButton = document.getElementById('updateDetails'); var cancelButton = document.getElementById('cancel'); var dialog = document.getElementById('favDialog'); dialog.returnValue = 'favAnimal'; function openCheck(dialog) { if(dialog.open) { console.log('Dialog open'); } else { console.log('Dialog closed'); } ...
...ent.getElementById('cancel'); var dialog = document.getElementById('favDialog'); dialog.returnValue = 'favAnimal'; function openCheck(dialog) { if(dialog.open) { console.log('Dialog open'); } else { console.log('Dialog closed'); } } // Update button opens a modal dialog updateButton.addEventListener('click', function
() { dialog.showModal
(); openCheck(dialog); }); // Form cancel button closes the dialog box cancelButton.addEventListener('click', function
() { dialog.close('animalNotChosen'); openCheck(dialog); }); })
(); </script> Specifications Specification Status Comment HTML Living StandardThe definition of 'show
()' i...
...cel button closes the dialog box cancelButton.addEventListener('click', function
() { dialog.close('animalNotChosen'); openCheck(dialog); }); })
(); </script> Specifications Specification Status Comment HTML Living StandardThe definition of 'show
()' in that specification. Living Standard HTML 5.1The definition of 'show
()' in that specification. Recommendation ...
HTMLFormElement.requestSubmit() - Web APIs
The HTMLFormElement method requestSubmit
() requests that the form be submitted using a specific submit button. Syntax htmlFormElement.requestSubmit(submitter); Parameters submitter Optional The submit button whose attributes describe the method by which the form is to be submitted. This may be either an <input> or <button> element whose type attribute is submit. If you omit the submitter parameter, the form element itself is used as the submitter. Return value None. Exceptions TypeError The specified submitter is not a submit button. NotFoundError The specified submitter isn't a member of the form on which requestSubmit
() was called. The submitter must be either a descendant of the form element or must have an form attribute referring to the form. Usage notes The o...
...value None. Exceptions TypeError The specified submitter is not a submit button. NotFoundError The specified submitter isn't a member of the form on which requestSubmit
() was called. The submitter must be either a descendant of the form element or must have an form attribute referring to the form. Usage notes The obvious question is: Why does this method exist, when we've had the submit
() method since the dawn of time? The answer is simple. submit
() submits the form, but that's all it does. requestSubmit
(), on the other hand, acts as if a submit button were clicked. The form's content is validated, and the form is submitted only if validation succeeds. Once the form has been submitted, the submit event is sent back to the form object. Examples In the example below, the form is ...
... submits the form, but that's all it does. requestSubmit
(), on the other hand, acts as if a submit button were clicked. The form's content is validated, and the form is submitted only if validation succeeds. Once the form has been submitted, the submit event is sent back to the form object. Examples In the example below, the form is submitted by attempting to send the request using requestSubmit
() if it's available. If a submit button with the ID main-submit is found, that's used to submit the form. Otherwise, the form is submitted with no submitter parameter, so it's submitted directly by the form itself. If, on the other hand, requestSubmit
() isn't available, this code falls back to calling the form's submit
() method. let myForm = document.querySelector("form"); let submitButton = myFo...
...meter, so it's submitted directly by the form itself. If, on the other hand, requestSubmit
() isn't available, this code falls back to calling the form's submit
() method. let myForm = document.querySelector("form"); let submitButton = myForm.querySelector("#main-submit"); if (myForm.requestSubmit) { if (submitButton) { myForm.requestSubmit(submitButton); } else { myForm.requestSubmit
(); } } else { myForm.submit
(); } Specifications Specification Status Comment HTML Living StandardThe definition of 'requestSubmit
()' in that specification. Living Standard ...
HTMLInputElement.setSelectionRange() - Web APIs
Optionally, in newer browser versions, you can specify the direction in which selection should be considered to have occurred. This lets you indicate, for example, that the selection was set by the user clicking and dragging from the end of the selected text toward the beginning. This method updates the HTMLInputElement.selectionStart, selectionEnd, and selectionDirection properties in one call. Note that accordingly to the WHATWG forms spec selectionStart, selectionEnd properties and setSelectionRange method apply only to inputs of types text, search, URL, tel and password. ...
...ssword. Chrome, starting from version 33, throws an exception while accessing those properties and method on the rest of input types. For example, on input of type number: "Failed to read the 'selectionStart' property from 'HTMLInputElement': The input element's type ('number') does not support selection". If you wish to select all text of an input element, you can use the HTMLInputElement.select
() method instead. Syntax element.setSelectionRange(selectionStart, selectionEnd [, selectionDirection]); Parameters If selectionEnd is less than selectionStart, then both are treated as the value of selectionEnd. selectionStart The 0-based index of the first selected character. An index greater than the length of the element's value is treated as pointing to the end of the value. selectio...
...e selection is considered to have been performed. Possible values: "forward" "backward" "none" if the direction is unknown or irrelevant. Default value. Example Click the button in this example to select the third, fourth, and fifth characters in the text box ("zil" in the word "Mozilla"). HTML <input type="text" id="text-box" size="20" value="Mozilla"> <button onclick="selectText
()">Select text</button> JavaScript function selectText
() { const input = document.getElementById('text-box'); input.focus
(); input.setSelectionRange(2, 5); } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLInputElement.setSelectionRange
()' in that specification. Living Standard No change HTML 5.1T...
...Text
() { const input = document.getElementById('text-box'); input.focus
(); input.setSelectionRange(2, 5); } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLInputElement.setSelectionRange
()' in that specification. Living Standard No change HTML 5.1The definition of 'HTMLInputElement.setSelectionRange
()' in that specification. Recommendation No change HTML5The definition of 'HTMLInputElement.setSelectionRange
()' in that specification. Recommendation Initial definition ...
HTMLInputElement.stepUp() - Web APIs
The method, when invoked, increments the value by (step * n), where n defaults to 1 if not specified, and step defaults to the default value for step if not specified. ...
...The method, when invoked, changes the form control's value by the value given in the step attribute, multiplied by the parameter, within the constraints set on the form control. The default value for the parameter, if no value is passed, is 1. The method will not cause the value to exceed the set max value, or defy the constraints set by the step attribute. If the value before invoking the stepUp
() method is invalid--for example, if it doesn't match the constraints set by the step attribute--invoking the stepUp
() method will return a value that does match the form controls constraints. If the form control is non time, date, or numeric in nature, and therefore does not support the step attribute (see the list of supported input types in the the table above), or if the step value is set to a...
..."400"> </label> </p> <p> <label>Enter how many values of step you would like to increment by or leave it blank: <input type="number" step="1" id="incrementer" min="0" max="25"> </label> </p> <input type="button" value="Increment" id="theButton"> JavaScript /* make the button call the function */ let button = document.getElementById('theButton') button.addEventListener('click', function
() { steponup
() }) function steponup
() { let input = document.getElementById('theNumber') let val = document.getElementById('incrementer').value if (val) { /* increment with a parameter */ input.stepUp(val) } else { /* or without a parameter. Try it with 0 */ input.stepUp
() } } CSS input:invalid { border: red solid 3px; } Result Note if you don't pass a parameter to...
...ange, in this case stopping when it reaches 400, and rounding down any floats that are passed as a parameter. Try setting the step increment to 1.2. What happens when you invoke the method? Try setting the value to 4, which is not valid. What happens when you invoke the method? Specifications Specification Status Comment HTML Living StandardThe definition of 'stepUp
()' in that specification. Living Standard HTML 5.1The definition of 'stepUp
()' in that specification. Recommendation HTML5The definition of 'stepUp
()' in that specification. Recommendation Initial definition ...
HTMLMediaElement.load() - Web APIs
The HTMLMediaElement method load
() resets the media element to its initial state and begins the process of selecting a media source and loading the media in preparation for playback to begin at the beginning. The amount of media data that is prefetched is determined by the value of the element's preload attribute. This method is generally only useful when you've made dynamic changes to the set of sources available for the media element, either by changing the element's src attribute or by adding or removing <source> elements nested within the media element itself. load
() will reset the element and rescan the available sources, thereby causing the changes to take effect. Syntax mediaElement.load
(); Parameters None. Return value undefined. ...
...anges to the set of sources available for the media element, either by changing the element's src attribute or by adding or removing <source> elements nested within the media element itself. load
() will reset the element and rescan the available sources, thereby causing the changes to take effect. Syntax mediaElement.load
(); Parameters None. Return value undefined. Usage notes Calling load
() aborts all ongoing operations involving this media element, then begins the process of selecting and loading an appropriate media resource given the options specified in the <audio> or <video> element and its src attribute or child <source> element(s). This is described in more detail in Supporting multiple formats in Video and audio content. The process of aborting any ongoing activities will c...
...media element, then begins the process of selecting and loading an appropriate media resource given the options specified in the <audio> or <video> element and its src attribute or child <source> element(s). This is described in more detail in Supporting multiple formats in Video and audio content. The process of aborting any ongoing activities will cause any outstanding Promises returned by play
() being resolved or rejected as appropriate based on their status before the loading of new media can begin. Pending play promises are aborted with an "AbortError" DOMException. Appropriate events will be sent to the media element itself as the load process proceeds: If the element is already in the process of loading media, that load process is aborted and the abort event is sent. If the elem...
...to the beginning of the media actually changes the playback position (that is, it was not already at the beginning), a timeupdate event is sent. Once media has been selected and loading is ready to begin, the loadstart event is delivered. From this point onward, events are sent just like any media load. Example This example finds a <video> element in the document and resets it by calling load
(). var mediaElem = document.querySelector("video"); mediaElem.load
(); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.load
()' in that specification. Living Standard Initial definition. HTML5The definition of 'HTMLMediaElement.load
()' in that specification. Recommendation Initial definition. ...
HTMLSelectElement.add() - Web APIs
Syntax collection.add(item[, before]); Parameters item is an HTMLOptionElement or HTMLOptGroupElement before is optional and an element of the collection, or an index of type long, representing the item item should be inserted before. If this parameter is null (or the index does not exist), the new element is appended to the end of the collection. Exceptions A DOMError of the type HierarchyRequestError if the item passed to the method is an ancestor of the HTMLSelectElement. ...
... Recommendation Is a snapshot of HTML Living Standard. The value of before can now be a long and is optional. It throws a DOMError of the type HierarchyRequestError if the passed item is an ancestor of the HTMLSelectElement and no longer throws if the before par...
... Recommendation Is a snapshot of HTML Living Standard. ...
...tion. Recommendation Is a snapshot of HTML Living Standard. The value of before can now be a long and is optional. It throws a DOMError of the type HierarchyRequestError if the passed item is an ancestor of the HTMLSelectElement and no longer throws if the before parameter is not found. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLSelectElement.add
()' in that specification. Obsolete The method now throws an NOT_FOUND_ERR exception if the item of the before parameter is not a child of this element. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLSelectElement.add
()' in that specification. Obsolete Initial definition ...
Headers.set() - Web APIs
For security reasons, some headers can only be controller by the user agent. These headers include the forbidden header names and forbidden response header names. Syntax myHeaders.set(name, value); Parameters name The name of the HTTP header you want to set to a new value. If the given name is not the name of an HTTP header, this method throws a TypeError. ...
...orbidden header names and forbidden response header names. Syntax myHeaders.set(name, value); Parameters name The name of the HTTP header you want to set to a new value. If the given name is not the name of an HTTP header, this method throws a TypeError. value The new value you want to set. Returns Void. Example Creating an empty Headers object is simple: var myHeaders = new Headers
(); // Currently empty You could add a header to this using Headers.append, then set a new value for this header using set
(): myHeaders.append('Content-Type', 'image/jpeg'); myHeaders.set('Content-Type', 'text/html'); If the specified header does not already exist, set
() will create it and set its value to the specified value. If the specified header does already exist and does accept multiple v...
...ntly empty You could add a header to this using Headers.append, then set a new value for this header using set
(): myHeaders.append('Content-Type', 'image/jpeg'); myHeaders.set('Content-Type', 'text/html'); If the specified header does not already exist, set
() will create it and set its value to the specified value. If the specified header does already exist and does accept multiple values, set
() will overwrite the existing value with the new one: myHeaders.set('Accept-Encoding', 'deflate'); myHeaders.set('Accept-Encoding', 'gzip'); myHeaders.get('Accept-Encoding'); // Returns 'gzip' You'd need Headers.append to append the new value onto the values, not overwrite it. ...
...t multiple values, set
() will overwrite the existing value with the new one: myHeaders.set('Accept-Encoding', 'deflate'); myHeaders.set('Accept-Encoding', 'gzip'); myHeaders.get('Accept-Encoding'); // Returns 'gzip' You'd need Headers.append to append the new value onto the values, not overwrite it. Specifications Specification Status Comment FetchThe definition of 'set
()' in that specification. Living Standard ...
History.go() - Web APIs
The History.go
() method loads a specific page from the session history. You can use it to move forwards and backwards through the history depending on the value of a parameter. This method is asynchronous. Add a listener for the popstate event in order to determine when the navigation has completed. Syntax history.go([delta]) Parameters delta Optional The position in the history to which you want to move, relative to the current page. A negative value moves backwards, a positive value moves forwards. So, for example, history.go(2) moves forward two pages and history.go(-2) moves back two pages. If no value is passed or if delta equals 0, it has the same result as calling location.reload
(). ...
...on in the history to which you want to move, relative to the current page. A negative value moves backwards, a positive value moves forwards. So, for example, history.go(2) moves forward two pages and history.go(-2) moves back two pages. If no value is passed or if delta equals 0, it has the same result as calling location.reload
(). ...
...ge. A negative value moves backwards, a positive value moves forwards. So, for example, history.go(2) moves forward two pages and history.go(-2) moves back two pages. If no value is passed or if delta equals 0, it has the same result as calling location.reload
(). Examples To move back one page (the equivalent of calling back
()): history.go(-1) To move forward a page, just like calling forward
(): history.go(1) To move forward two pages: history.go(2); To move backwards by two pages: history.go(-2); And, finally either of the following statements will reload the current page: history.go
(); history.go(0); Specifications Specification Status Comment HTML Living StandardThe definition of 'History.go
()' in that specification. Living Standard No change fr...
....go(2); To move backwards by two pages: history.go(-2); And, finally either of the following statements will reload the current page: history.go
(); history.go(0); Specifications Specification Status Comment HTML Living StandardThe definition of 'History.go
()' in that specification. Living Standard No change from HTML5. HTML5The definition of 'History.go
()' in that specification. Recommendation Initial definition. ...
IDBCursor.continue() - Web APIs
If no key is specified, the cursor advances to the immediate next position, based on its direction. Note: This feature is available in Web Workers. Syntax cursor.continue(key); Parameters key Optional The key to position the cursor at. Exceptions This method may raise a DOMException of one of the following types: Exception Description TransactionInactiveError This IDBCursor's transaction is inactive. DataError The key parameter may have any of the following conditions: The key is not a valid key. ...
... use a cursor to iterate through all the records in the object store. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. ...
... it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. ...
...action(['rushAlbumList'], "readonly"); var objectStore = transaction.objectStore('rushAlbumList'); objectStore.openCursor
().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year; list.appendChild(listItem); cursor.continue
(); } else { console.log('Entries all displayed.'); } }; }; Specifications Specification Status Comment Indexed Database API 2.0The definition of 'continue
()' in that specification. Recommendation Indexed Database API DraftThe definition of 'continue
()' in that specification. Recommendation Browser compatibility The compati...
IDBDatabase.createObjectStore() - Web APIs
The method takes the name of the store as well as a parameter object that lets you define important optional properties. You can use the property to uniquely identify individual objects in the store. As the property is an identifier, it should be unique to every object, and every object should have that property. This method can be called only within a versionchange transaction. Note: This feature is available in Web Workers. Syntax IDBDatabase.createObjectStore(name); IDBDatabase.createObjectStore(name, options); Parameters name The name of the new object store to be created. Note that it is possible to create an object store with an empty name. ...
...Increment is set to true and keyPath is either an empty string or an array containing an empty string. Example // Let us open our database var request = window.indexedDB.open("toDoList", 4); // This handler is called when a new version of the database // is created, either when one has not been created before // or when a new version number is submitted by calling // window.indexedDB.open
(). // This handler is only supported in recent browsers. request.onupgradeneeded = function(event) { var db = event.target.result; db.onerror = function(event) { note.innerHTML += "<li>Error loading database.</li>"; }; // Create an objectStore for this database var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" }); // define what data items the objectStore...
... Recommendation Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
...{ unique: false }); objectStore.createIndex("notified", "notified", { unique: false }); note.innerHTML += "<li>Object store created.</li>"; }; Specification Specification Status Comment Indexed Database API 2.0The definition of 'createObjectStore
()' in that specification. Recommendation Indexed Database API DraftThe definition of 'createObjectStore
()' in that specification. Recommendation Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for...
IDBKeyRange.bound() - Web APIs
The bounds can be open (that is, the bounds exclude the endpoint values) or closed (that is, the bounds include the endpoint values). By default, the bounds are closed. Note: This feature is available in Web Workers. Syntax var myIDBKeyRange = IDBKeyRange.bound(lower, upper); var myIDBKeyRange = IDBKeyRange.bound(lower, upper, lowerOpen); var myIDBKeyRange = IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen); Parameters lower specifies the lower bound of the new key range. upper specifies the upper bound of the new key range. lowerOpen Optional indicates whether the lower bound excludes the endpoint value. The default is false. ...
...A" and "F", as we haven't declared that they should be open bounds. If we used IDBKeyRange.bound("A", "F", true, true);, then the range would not include "A" and "F", only the values between them. ...
... Recommendation Browser compatibility The com...
...m = document.createElement('li'); listItem.innerHTML = '<strong>' + cursor.value.fThing + '</strong>, ' + cursor.value.fRating; list.appendChild(listItem); cursor.continue
(); } else { console.log('Entries all displayed.'); } }; }; Specification Specification Status Comment Indexed Database API 2.0The definition of 'bound
()' in that specification. Recommendation Indexed Database API DraftThe definition of 'bound
()' in that specification. Recommendation Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMo...
IDBKeyRange.includes() - Web APIs
The includes
() method of the IDBKeyRange interface returns a boolean indicating whether a specified key is inside the key range. Note: This feature is available in Web Workers. Syntax var isIncluded = myKeyRange.includes(key) Parameters key The key you want to check for in your key range. This can be any type. Return value A Boolean. Exceptions This method may raise a DOMException of the following type: Attribute Description DataError The supplied key was not a valid key. ...
...lean. Exceptions This method may raise a DOMException of the following type: Attribute Description DataError The supplied key was not a valid key. Example var keyRangeValue = IDBKeyRange.bound('A', 'K', false, false); var myResult = keyRangeValue.includes('F'); // Returns true var myResult = keyRangeValue.includes('W'); // Returns false Polyfill The includes
() method was added in the second edition of the Indexed DB specification. For browsers that do not support it, the following polyfill can be used. IDBKeyRange.prototype.includes = IDBKeyRange.prototype.includes || function(key) { var r = this, c; if (r.lower !== undefined) { c = indexedDB.cmp(key, r.lower); if (r.lowerOpen && c <= 0) return false; if (!r.lowerOpen && c < 0) return ...
... Recommendation Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. Desktop...
...== undefined) { c = indexedDB.cmp(key, r.upper); if (r.upperOpen && c >= 0) return false; if (!r.upperOpen && c > 0) return false; } return true; }; Specification Specification Status Comment Indexed Database API DraftThe definition of 'includes
()' in that specification. Recommendation Indexed Database API DraftThe definition of 'includes
()' in that specification. Recommendation Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for...
IDBKeyRange.lowerBound() - Web APIs
By default, it includes the lower endpoint value and is closed. Note: This feature is available in Web Workers. Syntax var myIDBKeyRange = IDBKeyRange.lowerBound(lower); var myIDBKeyRange = IDBKeyRange.lowerBound(lower, open); Parameters lower specifies the lower bound of the new key range. open Optional indicates whether the lower bound excludes the endpoint value. The default is false. Return value IDBKeyRange: The newly created key range. Exceptions This method may raise a DOMException of the following type: Exception Description DataError The value parameter passed was not a valid key. ...
...value. This means that the cursor will only retrieve the record with the key value "F" and all that come after it. If we used IDBKeyRange.lowerBound("F", true);, then the range would not include "F"; only the values after it. ...
... Recommendation Browser compatibilit...
...ument.createElement('li'); listItem.innerHTML = '<strong>' + cursor.value.fThing + '</strong>, ' + cursor.value.fRating; list.appendChild(listItem); cursor.continue
(); } else { console.log('Entries all displayed.'); } }; }; Specification Specification Status Comment Indexed Database API 2.0The definition of 'lowerBound
()' in that specification. Recommendation Indexed Database API DraftThe definition of 'lowerBound
()' in that specification. Recommendation Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. Deskt...
IDBKeyRange.upperBound() - Web APIs
By default, it includes the upper endpoint value and is closed. Note: This feature is available in Web Workers. Syntax var myIDBKeyRange = IDBKeyRange.upperBound(upper[, open=false]) Parameters bound specifies the upper bound of the new key range. open indicates whether the upper bound excludes the endpoint value. The default is false. Optional Return value IDBKeyRange: The newly created key range. Exceptions This method may raise a DOMException of the following type: Exception Description DataError The value parameter passed was not a valid key. Example The following example illustrates how you'd use an upper bound key range. ...
...n a Cursor with IDBObjectStore.openCursor, declaring keyRangeValue as its optional key range value. If we used IDBKeyRange.upperBound("F", true);, then the range excludes "F"; and instead only includes the values before it. ...
... Recommendation Browser compatibi...
...nt.createElement('li'); listItem.innerHTML = '<strong>' + cursor.value.fThing + '</strong>, ' + cursor.value.fRating; list.appendChild(listItem); cursor.continue
(); } else { console.log('Entries all displayed.'); } }; }; Specification Specification Status Comment Indexed Database API 2.0The definition of 'upperBound
()' in that specification. Recommendation Indexed Database API DraftThe definition of 'upperBound
()' in that specification. Recommendation Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. Deskt...
IDBObjectStore.count() - Web APIs
Return value An IDBRequest object on which subsequent events related to this operation are fired. ...
... Return value An IDBRequest object on which subsequent events related to this operation are fired. ...
... Exception Description InvalidStateError This IDBObjectStore has been deleted. TransactionInactiveError This IDBObjectStore's transaction is inactive. DataError The specified key or key range is invalid. ...
...valid. Example In this simple fragment we create a transaction, retrieve an object store, then count the number of records in the store using count
() -- when the success handler fires, we log the count value (an integer) to the console. var transaction = db.transaction(['fThings'], 'readonly'); var objectStore = transaction.objectStore('fThings'); var countRequest = objectStore.count
(); countRequest.onsuccess = function
() { console.log(countRequest.result); } Specification Specification Status Comment Indexed Database API 2.0The definition of 'count
()' in that specification. Recommendation Indexed Database API DraftThe definition of 'count
()' in that specification. Recommendation Browser compatibility The compatibil...
IDBObjectStore.openCursor() - Web APIs
If a single valid key is passed, this will default to a range containing only that key. If nothing is passed, this will default to a key range that selects all the records in this object store. ...
...If a single valid key is passed, this will default to a range containing only that key. If nothing is passed, this will default to a key range that selects all the records in this object store. ...
...nsaction is inactive. DataError The specified key or key range is invalid. ...
... the object store: var transaction = db.transaction("name", "readonly"); var objectStore = transaction.objectStore("name"); var request = objectStore.openCursor
(); request.onsuccess = function(event) { var cursor = event.target.result; if(cursor) { // cursor.value contains the current record being iterated through // this is where you'd do something with the result cursor.continue
(); } else { // no more results } }; Specification Specification Status Comment Indexed Database API 2.0The definition of 'openCursor
()' in that specification. Recommendation Indexed Database API DraftThe definition of 'openCursor
()' in that specification. Recommendation Browser compatibility The compatibility table on this page...
IDBObjectStore.openKeyCursor() - Web APIs
If a single valid key is passed, this will default to a range containing only that key. If nothing is passed, this will default to a key range that selects all the records in this object store. ...
...If a single valid key is passed, this will default to a range containing only that key. If nothing is passed, this will default to a key range that selects all the records in this object store. ...
...ction is inactive. DataError The specified key or key range is invalid. ...
... objectStore = transaction.objectStore("name"); var request = objectStore.openKeyCursor
(); request.onsuccess = function(event) { var cursor = event.target.result; if(cursor) { // cursor.key contains the key of the current record being iterated through // note that there is no cursor.value, unlike for openCursor // this is where you'd do something with the result cursor.continue
(); } else { // no more results } }; Specifications Specification Status Comment Indexed Database API 2.0The definition of 'openKeyCursor
()' in that specification. Recommendation Indexed Database API DraftThe definition of 'openKeyCursor
()' in that specification. Recommendation ...
IIRFilterNode.getFrequencyResponse() - Web APIs
The two output arrays, magResponseOutput and phaseResponseOutput, must be created before calling this method; they must be the same size as the array of input frequency values (frequencyArray). Syntax IIRFilterNode.getFrequencyResponse(frequencyArray, magResponseOutput, phaseResponseOutput); Parameters frequencyArray A Float32Array containing an array of frequencies, specified in Hertz, which you want to filter. ...
...Float32Array(5); var phaseResponseOutput = new Float32Array(5); Next we create a <ul> element in our HTML to contain our results, and grab a reference to it in our JavaScript: <p>IIR filter frequency response for: </p> <ul class="freq-response-output"> </ul> var freqResponseOutput = document.querySelector('.freq-response-output'); Finally, after creating our filter, we use getFrequencyResponse
() to generate the response data and put it in our arrays, then loop through each data set and output them in a human-readable list at the bottom of the page: var feedforwardCoefficients = [0.1, 0.2, 0.3, 0.4, 0.5]; var feedbackCoefficients = [0.5, 0.4, 0.3, 0.2, 0.1]; var iirFilter = audioCtx.createIIRFilter(feedforwardCoefficients, feedbackCoefficients); ... function calcFrequencyResponse
() ...
... Working Draft ...
... Working Draft ...
ImageBitmapRenderingContext.transferFromImageBitmap() - Web APIs
The old name is being kept as an alias to avoid code breakage. Syntax void ImageBitmapRenderingContext.transferFromImageBitmap(bitmap) Parameters bitmap An ImageBitmap object to transfer. ...
...The old name is being kept as an alias to avoid code breakage. Syntax void ImageBitmapRenderingContext.transferFromImageBitmap(bitmap) Parameters bitmap An ImageBitmap object to transfer. ...
... Living Standard ...
...en = new OffscreenCanvas(256, 256); var gl = offscreen.getContext("webgl"); // ... some drawing using the gl context ... // Transfer the current frame to the visible canvas var bitmap = offscreen.transferToImageBitmap
(); htmlCanvas.transferFromImageBitmap(bitmap); Specifications Specification Status Comment HTML Living StandardThe definition of 'transferFromImageBitmap
()' in that specification. Living Standard ...
ImageCapture.takePhoto() - Web APIs
Syntax const blobPromise = imageCaptureObj.takePhoto([photoSettings]) Parameters photoSettings Optional An object that sets options for the photo to be taken. The available options are: fillLightMode: The flash setting of the capture device, one of "auto", "off", or "flash". imageHeight: The desired image height as an integer. The user agent selects the closest height value to this setting if it only supports discrete heights. imageWidth: The desired image width as an integer. ...
...an integer. The user agent selects the closest width value to this setting if it only supports discrete widths. redEyeReduction: A boolean indicating whether the red-eye reduction should be used if it is available. Return value A Promise that resolves with a Blob. Example This example is extracted from this Simple Image Capture demo. ...
...e is extracted from this Simple Image Capture demo. It shows how to use the Promise returned by takePhoto
() to copy the returned Blob to an <img> element. For simplicy it does not show how to instantiate the ImageCapture object. ...
...le Image Capture demo. It shows how to use the Promise returned by takePhoto
() to copy the returned Blob to an <img> element. For simplicy it does not show how to instantiate the ImageCapture object. var takePhotoButton = document.querySelector('button#takePhoto'); var canvas = document.querySelector('canvas'); takePhotoButton.onclick = takePhoto; function takePhoto
() { imageCapture.takePhoto
().then(function(blob) { console.log('Took photo:', blob); img.classList.remove('hidden'); img.src = URL.createObjectURL(blob); }).catch(function(error) { console.log('takePhoto
() error: ', error); }); } Specifications Specification Status Comment MediaStream Image CaptureThe definition of 'takePhoto
()' in that specification. Working Draft Initial...
MediaDevices.enumerateDevices() - Web APIs
It simply outputs a list of the device IDs, with their labels if available. ...
...It simply outputs a list of the device IDs, with their labels if available. ...
...ray describing the devices. Syntax var enumeratorPromise = navigator.mediaDevices.enumerateDevices
(); Return value A Promise that receives an array of MediaDeviceInfo objects when the promise is fulfilled. Each object in the array describes one of the available media input and output devices. If enumeration fails, the promise is rejected. Example Here's an example of using enumerateDevices
(). It simply outputs a list of the device IDs, with their labels if available. if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) { console.log("enumerateDevices
() not supported."); return; } // List cameras and microphones. ...
...ces. If enumeration fails, the promise is rejected. Example Here's an example of using enumerateDevices
(). It simply outputs a list of the device IDs, with their labels if available. if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) { console.log("enumerateDevices
() not supported."); return; } // List cameras and microphones. ...
MediaMetadata.MediaMetadata() - Web APIs
Syntax var mediaMetadata = new MediaMetadata([metadata]) Parameters metadata Optional The metadata parameters are as follows: title: The title of the media to be played. artist: The name of the artist, group, creator, etc. of the media to be played. album: The name of the album, or collection, containing the media to be played. artwork: An array of images associated with the playing media. ...
...he playing media. ...
...w media session and assigns action handlers to it: if ('mediaSession' in navigator){ navigator.mediaSession.metadata = new MediaMetadata({ title: "Podcast Episode Title", artist: "Podcast Host", album: "Podcast Name", artwork: [{src: "podcast.jpg"}] }); navigator.mediaSession.setActionHandler('play', function
() {}); navigator.mediaSession.setActionHandler('pause', function
() {}); navigator.mediaSession.setActionHandler('seekbackward', function
() {}); navigator.mediaSession.setActionHandler('seekforward', function
() {}); navigator.mediaSession.setActionHandler('previoustrack', function
() {}); navigator.mediaSession.setActionHandler('nexttrack', function
() {}); } Specifications Specification Status Comment Media Session StandardThe def...
... Draft Initial definition. ...
MediaRecorder.pause() - Web APIs
Example ... ...
... Example ... ...
...hod is called, the browser queues a task that runs the below steps: If MediaRecorder.state is "inactive", raise a DOM InvalidState error and terminate these steps. If not, continue to the next step. Set MediaRecorder.state to "paused". Stop gathering data into the current Blob, but keep it available so that recording can be resumed later on. Raise a pause event. Syntax MediaRecorder.pause
() Return value undefined. Exceptions InvalidStateError The MediaRecorder is currently "inactive"; you can't pause recording if it's not active. If you call pause
() while already paused, it silently does nothing. Example ... pause.onclick = function
() { mediaRecorder.pause
(); console.log("recording paused"); } ... Specifications Specification Status Comment ...
...diaRecorder is currently "inactive"; you can't pause recording if it's not active. If you call pause
() while already paused, it silently does nothing. Example ... pause.onclick = function
() { mediaRecorder.pause
(); console.log("recording paused"); } ... Specifications Specification Status Comment MediaStream RecordingThe definition of 'MediaRecorder.pause
()' in that specification. Working Draft Initial definition ...
MediaRecorder.requestData() - Web APIs
The MediaRecorder.requestData
() method (part of the MediaRecorder API) is used to raise a dataavailable event containing a Blob object of the captured media as it was when the method was called. This can then be grabbed and manipulated as you wish. When the requestData
() method is invoked, the browser queues a task that runs the following steps: If MediaRecorder.state is not "recording", raise a DOM InvalidState error and terminate these steps. If MediaRecorder.state is "recording", continue to the next step. Raise a dataavailable event containing a Blob of the currently captured data (the Blob is available under the event's data attribute.) Create a new Blob and place subsequently captured data into it. ...
...MediaRecorder.state is not "recording", raise a DOM InvalidState error and terminate these steps. If MediaRecorder.state is "recording", continue to the next step. Raise a dataavailable event containing a Blob of the currently captured data (the Blob is available under the event's data attribute.) Create a new Blob and place subsequently captured data into it. ...
...te error and terminate these steps. If MediaRecorder.state is "recording", continue to the next step. Raise a dataavailable event containing a Blob of the currently captured data (the Blob is available under the event's data attribute.) Create a new Blob and place subsequently captured data into it. Syntax MediaRecorder.requestData
() Errors An InvalidState error is raised if the requestData
() method is called while the MediaRecorder object's MediaRecorder.state is not "recording" -- the media cannot be captured if recording is not occurring. Example ... captureMedia.onclick = function
() { mediaRecorder.requestData
(); // makes snapshot available of data so far // ondataavailable fires, then capturing continues // in new Blob } ... Specifications Speci...
...annot be captured if recording is not occurring. Example ... captureMedia.onclick = function
() { mediaRecorder.requestData
(); // makes snapshot available of data so far // ondataavailable fires, then capturing continues // in new Blob } ... Specifications Specification Status Comment MediaStream RecordingThe definition of 'MediaRecorder.requestData
()' in that specification. Working Draft Initial definition ...
MediaSource.addSourceBuffer() - Web APIs
The new SourceBuffer is also returned. Syntax var sourceBuffer = mediaSource.addSourceBuffer(mimeType); Parameters mimeType A DOMString specifying the MIME type of the SourceBuffer to create and add to the MediaSource. Return value A SourceBuffer object representing the new source buffer that has been created and added to the media source. Exceptions InvalidAccessError The value specified for mimeType is an empty string rather than a valid MIME type. InvalidStateError The MediaSource is not in the "open" readyState. ...
... Recommendation Initial definition. ...
... Recommendation Initial definition. ...
... Recommendation Initial definition. ...
MediaSource.endOfStream() - Web APIs
Syntax mediaSource.endOfStream(endOfStreamError); Parameters endOfStreamError Optional A DOMString representing an error to throw when the end of the stream is reached. The possible values are: network: Terminates playback and signals that a network error has occured. This can be used create a custom error handler related to media streams. For example, you might have a function that handles media chunk requests, separate from other network requests. ...
... Recommendation Initial definition. ...
... Recommendation Initial definition. ...
... Recommendation Initial definition. ...
MediaSource.isTypeSupported() - Web APIs
That is, if it can successfully create SourceBuffer objects for that MIME type. If the returned value is false, then the user agent is certain that it cannot access media of the specified format. Syntax var isItSupported = mediaSource.isTypeSupported(mimeType); Parameters mimeType The MIME media type that you want to test support for in the current browser. This may include the codecs parameter to provide added details about the codecs used within the file. Return value A Boolean which is true if the browser feels that it can probably play media of the specified type. ...
... Recommendation Initial definition. ...
... Recommendation Initial definition. ...
... Recommendation Initial definition. ...
MediaStreamTrack.getConstraints() - Web APIs
These constraints indicate values and ranges of values that the Web site or application has specified are required or acceptable for the included constrainable properties. Constraints can be used to ensure that the media meets certain guidelines you prefer. For example, you may prefer high definition video but require that the frame rate be a little low to help keep the data rate low enough not overtax the network. Constraints can also specify ideal and/or acceptable sizes or ranges of sizes. ...
... prefer. For example, you may prefer high definition video but require that the frame rate be a little low to help keep the data rate low enough not overtax the network. Constraints can also specify ideal and/or acceptable sizes or ranges of sizes. See Capabilities, constraints, and settings for details on how to work with constrainable properties. Syntax const constraints = track.getConstraints
() Return value A MediaTrackConstraints object which indicates the constrainable properties the Web site or app most recently set using applyConstraints
(). The properties in the returned object are listed in the same order as when they were set, and only properties specifically set by the site or app are included. Note: The returned set of constraints doesn't necessarily describe the actual stat...
...properties specifically set by the site or app are included. Note: The returned set of constraints doesn't necessarily describe the actual state of the media. Even if any of the constraints couldn't be met, they are still included in the returned object as originally set by the site's code. To get the currently active settings for all constrainable properties, you should instead call getSettings
(). ...
...are still included in the returned object as originally set by the site's code. To get the currently active settings for all constrainable properties, you should instead call getSettings
(). Example This example obtains the current constraints for a track, sets the facingMode, and applies the updated constraints. function switchCameras(track, camera) { const constraints = track.getConstraints
(); constraints.facingMode = camera; track.applyConstraints(constraints); } Specifications Specification Status Comment Media Capture and StreamsThe definition of 'getConstraints
()' in that specification. Candidate Recommendation Initial definition. ...
MediaStreamTrack.stop() - Web APIs
The MediaStreamTrack.stop
() method stops the track. Syntax track.stop
() Description Calling stop
() tells the user agent that the track's source--whatever that source may be, including files, network streams, or a local camera or microphone--is no longer needed by the MediaStreamTrack. Since multiple tracks may use the same source (for example, if two tabs are using the device's microphone), the source itself isn't necessarily immediately stopped. It is instead disassociated from the track and the track object is stopped. Once no media tracks are using the source, the source may actually be completely stopped. Immediately after calling stop
(), the readyState property is set to ended. Examples Stopping a video stream In this example, we see a function which stops a streamed video by ...
...elf isn't necessarily immediately stopped. It is instead disassociated from the track and the track object is stopped. Once no media tracks are using the source, the source may actually be completely stopped. Immediately after calling stop
(), the readyState property is set to ended. Examples Stopping a video stream In this example, we see a function which stops a streamed video by calling stop
() on every track on a given <video>. ...
...the source, the source may actually be completely stopped. Immediately after calling stop
(), the readyState property is set to ended. Examples Stopping a video stream In this example, we see a function which stops a streamed video by calling stop
() on every track on a given <video>. function stopStreamedVideo(videoElem) { const stream = videoElem.srcObject; const tracks = stream.getTracks
(); tracks.forEach(function(track) { track.stop
(); }); videoElem.srcObject = null; } This works by obtaining the video element's stream from its srcObject property. Then the stream's track list is obtained by calling its getTracks
() method. From there, all that remains to do is to iterate over the track list using forEach
() and calling each track's stop
() method. Finally, srcObject is ...
...y calling its getTracks
() method. From there, all that remains to do is to iterate over the track list using forEach
() and calling each track's stop
() method. Finally, srcObject is set to null to sever the link to the MediaStream object so it can be released. Specifications Specification Status Comment Media Capture and StreamsThe definition of 'MediaStreamTrack.stop
()' in that specification. Candidate Recommendation Initial specification. ...
MessageChannel() - Web APIs
The MessageChannel
() constructor of the MessageChannel interface returns a new MessageChannel object with two new MessagePort objects. Note: This feature is available in Web Workers. Syntax var channel = new MessageChannel
(); Returns A newly created MessageChannel object. Example In the following code block, you can see a new channel being created using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we pass port2 to the IFrame using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. ...
...essageChannel.MessageChannel constructor. When the IFrame has loaded, we pass port2 to the IFrame using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. ...
...ge being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. var channel = new MessageChannel
(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded
() { otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } For a full working example, see our channel messaging basic demo on Github (run it live too). Specifications Specification Status Comment HTML Living StandardThe definition of 'MessageChan...
... Living Standard ...
MessagePort.postMessage() - Web APIs
Note: This feature is available in Web Workers. Syntax port.postMessage(message, transferList); Returns Void. Parameters message The message you want to send through the channel. This can be of any basic data type. Multiple data items can be sent as an array. transferList Optional Transferable objects to be transferred -- these objects have their ownership transferred to the receiving browsing context, so are no longer usable by the sending browsing context. Example In the following code block, you can see a new channel being created using the MessageChannel.MessageChannel constructor. ...
... MessageChannel.MessageChannel constructor. When the IFrame has loaded, we pass MessageChannel.port2 to the IFrame using window.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame using onmessage, putting it into a paragraph -- MessageChannel.port1 is listened to, to check when the message arrives. ...
...s to a message being sent back from the IFrame using onmessage, putting it into a paragraph -- MessageChannel.port1 is listened to, to check when the message arrives. var channel = new MessageChannel
(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded
() { otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } For a full working example, see our channel messaging basic demo on Github (run it live too). Specifications Specification Status Comment HTML Living StandardThe definition of 'postMessage...
... Living Standard ...
MutationObserver.MutationObserver() - Web APIs
Syntax const observer = new MutationObserver(callback) Parameters callback A function which will be called on each DOM change that qualifies given the observed node or subtree and options. The callback function takes as input two parameters: An array of MutationRecord objects, describing each change that occurred; and the MutationObserver which invoked the callback. ...
...to and/or removed from the tree. (See mutation.addedNodes and mutation.removedNodes.) */ break; case 'attributes': /* An attribute value changed on the element in mutation.target. The attribute name is in mutation.attributeName, and its previous value is in mutation.oldValue. */ break; } }); } The callback
() function is invoked when the observer sees changes matching the configuration of the observation request specified when calling observe
() to begin watching the DOM. The kind of change that took place (either a change to the list of children, or a change to an attribute) is detected by looking at the mutation.type property. Creating and starting the observer This code actually sets up the obser...
...utationObserver(callback); observer.observe(targetNode, observerOptions); The desired subtree is located by finding an element with the ID someElement. A set of options for the observer is also established in the observerOptions record. In it, we specify values of true for both childList and attributes, so we get the information we want. Then the observer is instantiated, specifying the callback
() function. We begin observing the DOM nodes of interest by calling observe
(), specifying the target node and the options object. From this point until disconnect
() is called, callback
() will be called each time an element is added to or removed from the DOM tree rooted at targetNode, or any of those elements' attributes are changed. Specifications Specification Status Comment ...
...nterest by calling observe
(), specifying the target node and the options object. From this point until disconnect
() is called, callback
() will be called each time an element is added to or removed from the DOM tree rooted at targetNode, or any of those elements' attributes are changed. Specifications Specification Status Comment DOMThe definition of 'MutationObserver
()' in that specification. Living Standard ...
MutationObserver.takeRecords() - Web APIs
The MutationObserver method takeRecords
() returns a list of all matching DOM changes that have been detected but not yet processed by the observer's callback function, leaving the mutation queue empty. The most common use case for this is to immediately fetch all pending mutation records immediately prior to disconnecting the observer, so that any pending mutations can be processed when stopping down the observer. Syntax const mutationRecords = mutationObserver.takeRecords
() Parameters None. Return value An array MutationRecord objects, each describing one change applied to the observed portion of the document's DOM tree. Note: The queue of mutations which have occurred, but not been delivered to the observer's callback is left empty after calling takeRecords
(). Example In this ...
...s None. Return value An array MutationRecord objects, each describing one change applied to the observed portion of the document's DOM tree. Note: The queue of mutations which have occurred, but not been delivered to the observer's callback is left empty after calling takeRecords
(). Example In this example, we demonstrate how to handle any undelivered MutationRecords by calling takeRecords
() just before disconnecting the observer. ...
...ds
() just before disconnecting the observer. const targetNode = document.querySelector("#someElement"); const observerOptions = { childList: true, attributes: true } const observer = new MutationObserver(callback); observer.observe(targetNode, observerOptions); /* ...later, when it's time to stop observing... */ /* handle any still-pending mutations */ let mutations = observer.takeRecords
(); observer.disconnect
(); if (mutations) { callback(mutations); } The code in lines 12-17 fetches any unprocessed mutation records, then invokes the callback with the records so that they can be processed. This is done immediately prior to calling disconnect
() to stop observing the DOM. Specifications Specification Status Comment DOMThe definition of 'MutationObs...
...nnect
(); if (mutations) { callback(mutations); } The code in lines 12-17 fetches any unprocessed mutation records, then invokes the callback with the records so that they can be processed. This is done immediately prior to calling disconnect
() to stop observing the DOM. Specifications Specification Status Comment DOMThe definition of 'MutationObserver.takeRecords
()' in that specification. Living Standard ...
Navigator.getUserMedia() - Web APIs
The deprecated Navigator.getUserMedia
() method prompts the user for permission to use up to one video input device (such as a camera or shared screen) and up to one audio input device (such as a microphone) as the source for a MediaStream. If permission is granted, a MediaStream whose video and/or audio tracks come from those devices is delivered to the specified success callback. If permission is denied, no compatible input devices exist, or any other error condition occurs, the error callback is executed with a MediaStreamError object describing what went wrong. If the user instead doesn't make a choice at all, neither callback is executed. This is a legacy method. Please use the newer navigator.mediaDevices.getUserMedia
() instead. While technically not deprecated, this old callback...
...such, since the specification strongly encourages using the newer promise returning version. Syntax navigator.getUserMedia(constraints, successCallback, errorCallback); Parameters constraints A MediaStreamConstraints object specifying the types of media to request, along with any requirements for each type. For details, see the constraints section under the modern MediaDevices.getUserMedia
() method, as well as the article Capabilities, constraints, and settings. successCallback A function which is invoked when the request for media access is approved. The function is called with one parameter: the MediaStream object that contains the media stream. Your callback can then assign the stream to the desired object (such as an <audio> or <video> element), as shown in the following exampl...
...ething with the video here. }; } errorCallback When the call fails, the function specified in the errorCallback is invokedwith a MediaStreamError object as its sole argument; this object is is modeled on DOMException. See {anch("Errors")}} below for a list of the errors which can occur. Return value undefined. Errors Examples Width and height Here's an example of using getUserMedia
(), including code to cope with various browsers' prefixes. Note that this is the deprecated way of doing it: See the Examples section under the MediaDevices.getUserMedia
() for modern examples. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; if (navigator.getUserMedia) { navigator.get...
... navigator.webkitGetUserMedia || navigator.mozGetUserMedia; if (navigator.getUserMedia) { navigator.getUserMedia({ audio: true, video: { width: 1280, height: 720 } }, function(stream) { var video = document.querySelector('video'); video.srcObject = stream; video.onloadedmetadata = function(e) { video.play
(); }; }, function(err) { console.log("The following error occurred: " + err.name); } ); } else { console.log("getUserMedia not supported"); } ...
Navigator.sendBeacon() - Web APIs
Otherwise, it returns false. Description This method is for analytics and diagnostics that send data to a server before the document is unloaded, where sending the data any sooner may miss some possible data collection. ...
...Otherwise, it returns false. Description This method is for analytics and diagnostics that send data to a server before the document is unloaded, where sending the data any sooner may miss some possible data collection. ...
...the next navigation. There is nothing the next page can do to avoid this, so the new page seems slow, even though it's the previous page's fault. The following example shows theoretical analytics code that attempts to submit data to a server with a synchronous XMLHttpRequest in an unload handler. This results in the next page load to be delayed. window.addEventListener("unload", function logData
() { var xhr = new XMLHttpRequest
(); xhr.open("POST", "/log", false); // third parameter of `false` means synchronous xhr.send(analyticsData); }); This is what sendBeacon
() replaces. With the sendBeacon
() method, the data is transmitted asynchronously when the User Agent has an opportunity to do so, without delaying unload or the next navigation. This solves all of the problems with submissi...
...ying unload or the next navigation. This solves all of the problems with submission of analytics data: The data is sent reliably It's sent asynchronously It doesn't impact the loading of the next page In addition, the code is simpler to write than any of the older techniques! The following example shows a theoretical analytics code pattern that submits data to a server using the sendBeacon
() method. window.addEventListener("unload", function logData
() { navigator.sendBeacon("/log", analyticsData); }); The beacon sends an HTTP request via the POST method, with all relevant cookies available when called. Specifications Specification Status Comment BeaconThe definition of 'sendBeacon
()' in that specification. Candidate Recommendation Initial defi...
Navigator.share() - Web APIs
Syntax var sharePromise = navigator.share(data); Parameters data An object containing data to share. At least one of the following fields must be specified. Available options are: url: A USVString representing a URL to be shared. text: A USVString representing text to be shared. title: A USVString representing the title to be shared. files: A " FrozenArray" representing the array of file to be shared. Return value A Promise that will be fulfilled once a user has completed a share action (usually the user has chosen an application to share to). ...
...en clicked, invokes the Web Share API to share MDN's URL. ...
...n'); const resultPara = document.querySelector('.result'); // Must be triggered some kind of "user activation" btn.addEventListener('click', async
() => { try { await navigator.share(shareData) resultPara.textContent = 'MDN shared successfully' } catch(err) { resultPara.textContent = 'Error: ' + err } }); Sharing Files To share files, first test for and call navigator.canShare
(). Then include an array of files in the call to navigator.share
(): Notice: That the sample handles feature detection by testing for navigator.canShare
() rather than for navigator.share
(). The data object passed to canShare
() only supports the files property. Image, video, audio, and text files can be shared. if (navigator.canShare && navigator.canShare({ files: filesArray })) { navigator.sha...
...e handles feature detection by testing for navigator.canShare
() rather than for navigator.share
(). The data object passed to canShare
() only supports the files property. Image, video, audio, and text files can be shared. if (navigator.canShare && navigator.canShare({ files: filesArray })) { navigator.share({ files: filesArray, title: 'Pictures', text: 'Our Pictures.', }) .then(
() => console.log('Share was successful.')) .catch((error) => console.log('Sharing failed', error)); } else { console.log(`Your system doesn't support sharing files.`); } Specifications Specification Status Comment Web Share APIThe definition of 'share
()' in that specification. Draft ...
Node.hasChildNodes() - Web APIs
The Node.hasChildNodes
() method returns a Boolean value indicating whether the given Node has child nodes or not. Syntax bool = node.hasChildNodes
(); Return value A Boolean that is true if the node has child nodes, and false otherwise. ...
... The Node.hasChildNodes
() method returns a Boolean value indicating whether the given Node has child nodes or not. Syntax bool = node.hasChildNodes
(); Return value A Boolean that is true if the node has child nodes, and false otherwise. ...
... child nodes or not. Syntax bool = node.hasChildNodes
(); Return value A Boolean that is true if the node has child nodes, and false otherwise. ...
... Living Standard ...
Node.insertBefore() - Web APIs
If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node. ...
... If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node. ...
...rence node as a child of a specified parent node. If the given node already exists in the document, insertBefore
() moves it from its current position to the new position. (That is, it will automatically be removed from its existing parent before appending it to the specified new parent.) This means that a node cannot be in two locations of the document simultaneously. Note: The Node.cloneNode
() can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode
() will not be automatically kept in sync. If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node. Syntax let insertedNode = parentNode.insertBefore(newNode, referenceNode) inserte...
...It can be emulated by combining the insertBefore method with Node.nextSibling. In the previous example, sp1 could be inserted after sp2 using: parentDiv.insertBefore(sp1, sp2.nextSibling) If sp2 does not have a next sibling, then it must be the last child -- sp2.nextSibling returns null, and sp1 is inserted at the end of the child node list (immediately after sp2). Example 3 Insert ...
Notification.close() - Web APIs
Returns Void. ...
...od will also remove the notification from any notification tray, preventing users from interacting with it after it was initially shown. A valid use for this API would be to remove a notification that is no longer relevant (e.g. the user already read the notification on the webpage in the case of a messaging app or the following song is already playing in a music app). Syntax Notification.close
(); Parameters None. Returns Void. Examples In the following snippet, we have a simple function that when called creates an options object and then a new notification. At the end of the function, it also calls close
() inside a addEventListener
() function to remove the notification when the relevant content has been read on the webpage. function spawnNotification(theBody, theIcon, theTitle) { ...
...ication. At the end of the function, it also calls close
() inside a addEventListener
() function to remove the notification when the relevant content has been read on the webpage. function spawnNotification(theBody, theIcon, theTitle) { var options = { body: theBody, icon: theIcon }; var n = new Notification(theTitle,options); document.addEventListener('visibilitychange', function
() { if (document.visibilityState === 'visible') { // The tab has become visible so clear the now-stale Notification. ...
...content has been read on the webpage. ...
Notification.requestPermission() - Web APIs
Note: This feature is available in Web Workers. Note: This feature is not available in SharedWorker Note: Safari still uses the callback syntax to get the permission. Read Using the Notifications API for a good example of how to feature detect this and run code as appropriate. The requestPermission
() method of the Notification interface requests permission from the user for the current origin to display notifications. Syntax The latest spec has updated this method to a promise-based syntax that works like this: Notification.requestPermission
().then(function(permission) { ... }); Previously, the syntax was based on a simple callback; this version is now deprecated: Notification.requestPermission(callback); Parameters callback Optional Deprecated since Gecko 46 An opt...
...; Parameters callback Optional Deprecated since Gecko 46 An optional callback function that is called with the permission value. Deprecated in favor of the promise return value. Returns A Promise that resolves to a DOMString with the permission picked by the user. ...
...otifyMe
()">Notify me!</button> It's possible to send a notification as follows -- here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification. ...
...} We no longer show a live sample on this page, as Chrome and Fir...
OfflineAudioContext.OfflineAudioContext() - Web APIs
Either way, the individual parameters are the same. numberOfChannels An integer specifying the number of channels the resulting AudioBuffer should have. ...
...the Web Audio API--creates and returns a new OfflineAudioContext object instance, which can then be used to render audio to an AudioBuffer rather than to an audio output device. Syntax var offlineAudioCtx = new OfflineAudioContext(numberOfChannels, length, sampleRate); var offlineAudioCtx = new OfflineAudioContext(options); Parameters You can specify the parameters for the OfflineAudioContext
() constructor as either the same set of parameters as are inputs into the AudioContext.createBuffer
() method, or by passing those parameters in an options object. Either way, the individual parameters are the same. numberOfChannels An integer specifying the number of channels the resulting AudioBuffer should have. length An integer specifying the size of the buffer to create for the audio con...
...240000 sample-frames. sampleRate The sample-rate of the linear audio data in sample-frames per second. All user agents are required to support a range of 22050Hz to 96000Hz, and may support a wider range than that. The most commonly-used rate is 44100Hz, which is the sample rate used by CD audio. It is important to note that, whereas you can create a new AudioContext using the new AudioContext
() constructor with no arguments, the OfflineAudioContext
() constructor requires three arguments, since it needs to create an AudioBuffer. This works in exactly the same way as when you create a new AudioBuffer with the AudioContext.createBuffer
() method. For more detail, read Audio buffers: frames, samples and channels from our Basic concepts guide. Return value A new OfflineAudioContext object w...
... value A new OfflineAudioContext object whose associated AudioBuffer is configured as requested. Like a regular AudioContext, an OfflineAudioContext can be the target of events, therefore it implements the EventTarget interface. Example const offlineCtx = new OfflineAudioContext({ numberOfChannels: 2, length: 44100 * 40, sampleRate: 44100, }); const source = offlineCtx.createBufferSource
(); // etc... For a full working example, see our offline-audio-context-promise Github repo (see the source code too.) Specifications Specification Status Comment Web Audio APIThe definition of 'OfflineAudioContext
()' in that specification. Working Draft ...
PaymentResponse.complete() - Web APIs
Syntax completePromise = paymentRequest.complete(result); Parameters result Optional A DOMString indicating the state of the payment operation upon completion. It must be one of the following: success The payment was successfully processed. The user agent may or may not present some form of "payment successful" indication to the user. fail The payment was not successfully processed. ...
...value A Promise which resolves with no input value once the payment interface has been fully closed. If an error occurs, the promise instead rejects, returning one of the exceptions listed below. Exceptions AbortError The document in which the payment request is taking place became inactive while the user interface was shown. InvalidStateError The payment has already completed, or complete
() was called while a request to retry the payment is pending. You can't treat a payment as complete after requesting that the payment be tried again. Examples The following example sends payment information to a secure server using the Fetch API. It calls complete
() with an answer appropriate to the status in the response. // Initialization of PaymentRequest arguments are excerpted for the // ...
...requesting that the payment be tried again. Examples The following example sends payment information to a secure server using the Fetch API. It calls complete
() with an answer appropriate to the status in the response. // Initialization of PaymentRequest arguments are excerpted for the // sake of brevity. ...
...n. 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. ...
performance.clearMarks() - Web APIs
The clearMarks
() method removes the named mark from the browser's performance entry buffer. If the method is called with no arguments, all performance entries with an entry type of "mark" will be removed from the performance entry buffer. Note: This feature is available in Web Workers. Syntax performance.clearMarks
(); performance.clearMarks(name); Arguments name Optional A DOMString representing the name of the timestamp. If this argument is omitted, all performance entries with an entry type of "mark" will be removed. Return value void Example The following example shows both uses of the clearMarks
() method. // Create a small helper to show how many PerformanceMark entries there are. ...
...learMarks(name); Arguments name Optional A DOMString representing the name of the timestamp. If this argument is omitted, all performance entries with an entry type of "mark" will be removed. Return value void Example The following example shows both uses of the clearMarks
() method. // Create a small helper to show how many PerformanceMark entries there are. ...
... small helper to show how many PerformanceMark entries there are. function logMarkCount
() { console.log( "Found this many entries: " + performance.getEntriesByType("mark").length ); } // Create a bunch of marks. performance.mark("squirrel"); performance.mark("squirrel"); performance.mark("monkey"); performance.mark("monkey"); performance.mark("dog"); performance.mark("dog"); logMarkCount
() // "Found this many entries: 6" // Delete just the "squirrel" PerformanceMark entries. performance.clearMarks('squirrel'); logMarkCount
() // "Found this many entries: 4" // Delete all of the PerformanceMark entries. ...
...rrel"); performance.mark("squirrel"); performance.mark("monkey"); performance.mark("monkey"); performance.mark("dog"); performance.mark("dog"); logMarkCount
() // "Found this many entries: 6" // Delete just the "squirrel" PerformanceMark entries. performance.clearMarks('squirrel'); logMarkCount
() // "Found this many entries: 4" // Delete all of the PerformanceMark entries. performance.clearMarks
(); logMarkCount
() // "Found this many entries: 0" Specifications Specification Status Comment User Timing Level 2The definition of 'clearMarks
()' in that specification. Working Draft Clarifies clearMarks
(). User TimingThe definition of 'clearMarks
()' in that specification. Recommendation Basic definition. ...
PerformanceObserver() - Web APIs
Syntax var observer = new PerformanceObserver(callback); Parameters callback A PerformanceObserverCallback callback that will be invoked when observed performance events are recorded. When the callback is invoked, its first parameter is a list of performance observer entries and the second parameter is the observer object. Return value A new PerformanceObserver object which will call the specified callback when observed performance events occur. ...
...ormance events are recorded. When the callback is invoked, its first parameter is a list of performance observer entries and the second parameter is the observer object. Return value A new PerformanceObserver object which will call the specified callback when observed performance events occur. ...
... ...
... ...
PerformanceObserverEntryList.getEntries() - Web APIs
The getEntries
() method of the PerformanceObserverEntryList interface returns a list of explicitly observed performance entry objects for a given filter. The list's members are determined by the set of entry types specified in the call to the observe
() method. The list is available in the observer's callback function (as the first parameter in the callback). This method is exposed to Window and Worker interfaces. Syntax General syntax: entries = list.getEntries
(); entries = list.getEntries(PerformanceEntryFilterOptions); Specific usage: entries = list.getEntries({name: "entry_name", entryType: "mark"}); Parameters PerformanceEntryFilterOptionsOptional Is a PerformanceEntryFilterOptions dictionary, having the following fields: "name", the name of a performance entry. "...
...int_perf_entry(pe) { console.log("name: " + pe.name + "; entryType: " + pe.entryType + "; startTime: " + pe.startTime + "; duration: " + pe.duration); } // Create observer for all performance event types var observe_all = new PerformanceObserver(function(list, obs) { var perfEntries; // Print all entries perfEntries = list.getEntries
(); for (var i=0; i < perfEntries.length; i++) { print_perf_entry(perfEntries[i]); } // Print entries named "Begin" with type "mark" perfEntries = list.getEntriesByName("Begin", "mark"); for (var i=0; i < perfEntries.length; i++) { print_perf_entry(perfEntries[i]); } // Print entries with type "mark" perfEntries = list.getEntriesByType("mark"); for (var i=0; i < perfEntri...
... Candidate Recommendation ...
...unction(list, obs) { var perfEntries = list.getEntries
(); // Should only have 'frame' entries for (var i=0; i < perfEntries.length; i++) { print_perf_entry(perfEntries[i]); } }); // subscribe to frame event only observe_frame.observe({entryTypes: ['frame']}); Specifications Specification Status Comment Performance Timeline Level 2The definition of 'getEntries
()' in that specification. Candidate Recommendation Initial definition. ...
PerformanceObserverEntryList.getEntriesByName() - Web APIs
The list is available in the observer's callback function (as the first parameter in the callback). This method is exposed to Window and Worker interfaces. Syntax entries = list.getEntriesByName(name, type); Parameters name A DOMString representing the name of the entry to retrieve. type Optional A DOMString representing the type of entry to retrieve such as "mark". The valid entry types are listed in PerformanceEntry.entryType. ...
...int_perf_entry(pe) { console.log("name: " + pe.name + "; entryType: " + pe.entryType + "; startTime: " + pe.startTime + "; duration: " + pe.duration); } // Create observer for all performance event types var observe_all = new PerformanceObserver(function(list, obs) { var perfEntries; // Print all entries perfEntries = list.getEntries
(); for (var i=0; i < perfEntries.length; i++) { print_perf_entry(perfEntries[i]); } // Print entries named "Begin" with type "mark" perfEntries = list.getEntriesByName("Begin", "mark"); for (var i=0; i < perfEntries.length; i++) { print_perf_entry(perfEntries[i]); } // Print entries with type "mark" perfEntries = list.getEntriesByType("mark"); for (var i=0; i < perfEntri...
... Candidate Recomm...
..., obs) { var perfEntries = list.getEntries
(); // Should only have 'frame' entries for (var i=0; i < perfEntries.length; i++) { print_perf_entry(perfEntries[i]); } }); // subscribe to only the 'frame' event observe_frame.observe({entryTypes: ['frame']}); Specifications Specification Status Comment Performance Timeline Level 2The definition of 'getEntriesByName
()' in that specification. Candidate Recommendation Initial definition of getEntriesByName
() method. ...
PerformanceObserverEntryList.getEntriesByType() - Web APIs
The list is available in the observer's callback function (as the first parameter in the callback). This method is exposed to Window and Worker interfaces. Syntax entries = list.getEntriesByType(type); Parameters type The type of entry to retrieve such as "frame". The valid entry types are listed in PerformanceEntry.entryType. Return value A list of explicitly observed PerformanceEntry objects that have the specified type. ...
...int_perf_entry(pe) { console.log("name: " + pe.name + "; entryType: " + pe.entryType + "; startTime: " + pe.startTime + "; duration: " + pe.duration); } // Create observer for all performance event types var observe_all = new PerformanceObserver(function(list, obs) { var perfEntries; // Print all entries perfEntries = list.getEntries
(); for (var i=0; i < perfEntries.length; i++) { print_perf_entry(perfEntries[i]); } // Print entries named "Begin" with type "mark" perfEntries = list.getEntriesByName("Begin", "mark"); for (var i=0; i < perfEntries.length; i++) { print_perf_entry(perfEntries[i]); } // Print entries with type "mark" perfEntries = list.getEntriesByType("mark"); for (var i=0; i < perfEntri...
... Candidate Recomm...
..., obs) { var perfEntries = list.getEntries
(); // Should only have 'frame' entries for (var i=0; i < perfEntries.length; i++) { print_perf_entry(perfEntries[i]); } }); // subscribe to only the 'frame' event observe_frame.observe({entryTypes: ['frame']}); Specifications Specification Status Comment Performance Timeline Level 2The definition of 'getEntriesByType
()' in that specification. Candidate Recommendation Initial definition of getEntriesByType
() method. ...
PushManager.subscribe() - Web APIs
It returns a Promise that resolves to a PushSubscription object containing details of a push subscription. A new push subscription is created if the current service worker does not have an existing subscription. Syntax PushManager.subscribe(options).then(function(pushSubscription) { ... } ); Parameters options Optional An object containing optional configuration parameters. It can have the following properties: userVisibleOnly: A boolean indicating that the returned push subscription will only be used for messages whose effect is made visible to the user. ...
... to it using, // for example, an XMLHttpRequest. }, function(error) { // During development it often helps to log errors to the // console. In a production environment it might make sense to // also report information about errors back to the // application server. ...
...g errors to the // console. In a production environment it might make sense to // also report information about errors back to the // application server. console.log(error); } ); }); Responding to user gestures subscribe
() calls should be done in response to a user gesture, such as clicking a button, for example: btn.addEventListener('click', function
() { serviceWorkerRegistration.pushManager.subscribe(options) .then(function(pushSubscription) { // handle subscription }); }) This is not only best practice -- you should not be spamming users with notifications they didn't agree to -- but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. Firefox is already doing this from version ...
... Working Draft Initial definition. ...
PushMessageData.json() - Web APIs
Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
... Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
... Working Draft Initial definition. ...
... Working Draft Initial definition. ...
PushSubscription.getKey() - Web APIs
The getKey
() method of the PushSubscription interface returns an ArrayBuffer representing a client public key, which can then be sent to a server and used in encrypting push message data. Syntax var key = subscription.getKey(name); Parameters name A DOMString representing the encryption method used to generate a client key. The value can be: p256dh: An Elliptic curve Diffie-Hellman public key on the P-256 curve (that is, the NIST secp256r1 elliptic curve). The resulting key is an uncompressed point in ANSI X9.62 format. auth: An authentication secret, as described in Message Encryption for Web Push. Returns An ArrayBuffer. ...
... method used to generate a client key. The value can be: p256dh: An Elliptic curve Diffie-Hellman public key on the P-256 curve (that is, the NIST secp256r1 elliptic curve). The resulting key is an uncompressed point in ANSI X9.62 format. auth: An authentication secret, as described in Message Encryption for Web Push. Returns An ArrayBuffer. Example reg.pushManager.getSubscription
() .then(function(subscription) { // Enable any UI which subscribes / unsubscribes from // push messages. subBtn.disabled = false; if (!subscription) { console.log('Not yet subscribed to Push') // We aren't subscribed to push, so set UI // to allow the user to enable push return; } // Set your UI to show they have subscribed for // push messages subBtn.textConten...
...initialize status, which includes setting UI elements for subscribed status // and updating Subscribers list via push var endpoint = subscription.endpoint; var key = subscription.getKey('p256dh'); var auth = subscription.getKey('auth'); ... Specifications Specification Status Comment Push API Working Draft This is the Push API spec, but note that getKey
() is not currently specified in here. It is currently Firefox-only experimental. 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 And...
...tal. 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. ...
RTCDataChannel.send() - Web APIs
This can be done any time except during the initial process of creating the underlying transport channel. Data sent before connecting is buffered if possible (or an error occurs if it's not possible), and is also buffered if sent while the connection is closing or closed. Different browsers have different limitations on the size of the message you can send. Specifications exist to define how to automatically fragment large messages, but not all browsers implement them, and those that do have various additional restrictions. This will get less complicated over time, but for now, if you have questions, see Understanding message size limits in Using WebRTC data channels. ...
... other peer to receive. Since there are multiple techniques for breaking up large data into smaller pieces for transfer, it's possible to encounter scenarios in which the other peer does not support the same ones. For example, if one peer is a modern browser that supports using the EOR (End of Record) flag to indicate when a received message is the last piece of a multi-part object sent using send
(). ...
...oes not support the same ones. For example, if one peer is a modern browser that supports using the EOR (End of Record) flag to indicate when a received message is the last piece of a multi-part object sent using send
(). For more information about message size restrictions, see Understanding message size limits in Using WebRTC data channels. Example In this example, a routine called sendMessage
() is created; it accepts an object as input and sends to the remote peer, over the RTCDataChannel, a JSON string with the specified object and a time stamp. ...
...-part object sent using send
(). For more information about message size restrictions, see Understanding message size limits in Using WebRTC data channels. Example In this example, a routine called sendMessage
() is created; it accepts an object as input and sends to the remote peer, over the RTCDataChannel, a JSON string with the specified object and a time stamp. var pc = new RTCPeerConnection
(); var dc = pc.createDataChannel("BackChannel"); function sendMessage(msg) { let obj = { "message": msg, "timestamp": new Date
() } dc.send(JSON.stringify(obj)); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.send
()' in that specification. Candidate Recommendation ...
RTCIceTransport.getSelectedCandidatePair() - Web APIs
Return value A RTCIceCandidatePair object describing the configurations of the currently-selected candidate pair's two endpoints. local describes the configuration of the local end of the connection, while remote describes the remote peer's configuration. The return value is null if no pair of candidates has been selected yet. ...
...ion of a RTCPeerConnection, it gathers and analyzes candidate configurations from each the two peers. As soon as it finds an acceptable matching pair of candidates, meeting the requirements for the connection, a selectedcandidatepairchange event is fired at the RTCIceTransport. From that time forward, the best matching pair of candidates will always be available by calling getSelectedCandidatePair
(). As ICE negotiation continues, any time a pair of candidates is discovered that is better than the currently-selected pair, the new pair is selected, replacing the previous pairing, and the selectedcandidatepairchange event is fired again. Note: It's possible for one of the configurations in the selected candidate pair to remain unchanged when a new pairing is chosen. Example In this exampl...
...lectedcandidatepairchange event is fired again. Note: It's possible for one of the configurations in the selected candidate pair to remain unchanged when a new pairing is chosen. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. ...
...p to update an on-screen display showing the protocol used by the currently selected candidate pair. var iceTransport = pc.getSenders
()[0].transport.iceTransport; var localProto = document.getElementById("local-protocol"); var remoteProto = document.getElementById("remote-protocol"); iceTransport.onselectedcandidatepairchange = function(event) { var pair = iceTransport.getSelectedCandidatePair
(); localProtocol.innerText = pair.local.protocol.toUpperCase
(); remoteProtocol.innerText = pair.remote.protocol.toUpperCase
(); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCIceTransport.getSelectedCandidatePair
()' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection() - Web APIs
Syntax pc = new RTCPeerConnection([configuration]); Parameters configuration Optional An RTCConfiguration dictionary providing options to configure the new connection. RTCConfiguration dictionary bundlePolicy Optional Specifies how to handle negotiation of candidates when the remote peer is not compatible with the SDP BUNDLE standard. This must be one of the values from the enum RTCBundlePolicy. If this value isn't included in the dictionary, "balanced" is assumed. certificates Optional An Array of objects of type RTCCertificate which are used by the connection for authentication. ...
...cate is used by a given connection, providing certificates for multiple algorithms may improve the odds of successfully connecting in some circumstances. See Using certificates below for additional information. This configuration option cannot be changed after it is first specified; once the certificates have been set, this property is ignored in future calls to RTCPeerConnection.setConfiguration
(). iceCandidatePoolSize Optional An unsigned 16-bit integer value which specifies the size of the prefetched ICE candidate pool. The default value is 0 (meaning no candidate prefetching will occur). You may find in some cases that connections can be established more quickly by allowing the ICE agent to start fetching ICE candidates before you start trying to connect, so that they're already ava...
...alue which specifies the size of the prefetched ICE candidate pool. The default value is 0 (meaning no candidate prefetching will occur). You may find in some cases that connections can be established more quickly by allowing the ICE agent to start fetching ICE candidates before you start trying to connect, so that they're already available for inspection when RTCPeerConnection.setLocalDescription
() is called. Changing the size of the ICE candidate pool may trigger the beginning of ICE gathering. iceServers Optional An array of RTCIceServer objects, each describing one server which may be used by the ICE agent; these are typically STUN and/or TURN servers. If this isn't specified, the connection attempt will be made with no STUN or TURN server available, which limits the connection to l...
... be one of those from the RTCRtcpMuxPolicy enum. The default is "require". Return value A newly-created RTCPeerConnection object, configured as described by configuration, if specified; otherwise, configured to appropriate basic defaults. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection
()' in that specification. Candidate Recommendation Initial definition. ...
RTCPeerConnection.addIceCandidate() - Web APIs
When a web site or app using RTCPeerConnection receives a new ICE candidate from the remote peer over its signaling channel, it delivers the newly-received candidate to the browser's ICE agent by calling RTCPeerConnection.addIceCandidate
(). This adds this new remote candidate to the RTCPeerConnection's remote description, which describes the state of the remote end of the connection. If the candidate parameter is missing or a value of null is given when calling addIceCandidate
(), the added ICE candidate is an "end-of-candidates" indicator. The same is the case if the value of the specified object's candidate is either missing or an empty string (""), it signals that all remote candidates have been delivered. The end-of-candidates notification is transmitted to the remote peer using a cand...
...d-of-candidates signal is sent to the remote peer using the end-of-candidates a-line, formatted simply like this: a=end-of-candidates Deprecated parameters In older code and documentation, you may see a callback-based version of this function. This has been deprecated and its use is strongly discouraged. You should update any existing code to use the Promise-based version of addIceCandidate
() instead. The parameters for this form of addIceCandidate
() are described below, to aid in updating existing code. successCallback A function to be called when the ICE candidate has been successfully added. This function receives no input parameters and doesn't return a value. failureCallback A function to be called if attempting to add the ICE candidate fails. Receives as input a DOMExc...
...Out of interest, end-of-candidates may be manually indicated as follows: pc.addIceCandidate({candidate:''}); However, in most cases you won't need to look for this explicitly, s...
... Candidate Recommendation Initial specification. ...
RTCPeerConnection.getStreamById() - Web APIs
The RTCPeerConnection.getStreamById
() method returns the MediaStream with the given id that is associated with local or remote end of the connection. If no stream matches, it returns null. This property has been replaced with the RTCPeerConnection.getLocalStreams and RTCPeerConnection.getRemoteStreams properties. If you have code that uses stream, you will need to update, since browsers have begun to remove support for stream. Syntax var mediaStream = pc.getStream(id); Parameters id Is a DOMString corresponding to the stream to return. ...
...ce browsers have begun to remove support for stream. Syntax var mediaStream = pc.getStream(id); Parameters id Is a DOMString corresponding to the stream to return. ...
...f (stream) { console.log("Found stream: " + stream.id); } Polyfill Running the following code before any other code will create RTCPeerConnection.prototype.getStreamById
() if it's not natively available. ...
...eam.id); } Polyfill Running the following code before any other code will create RTCPeerConnection.prototype.getStreamById
() if it's not natively available. ...
RTCRtpReceiver.getCapabilities() static function - Web APIs
Syntax let rtpCapabilities = RTCRtpReceiver.getCapabilities(kind); Parameters kind A DOMString indicating the type of media for which you wish to get the device's capability to receive. All browsers support the primary media kinds: audio and video. Return value An RTCRtpCapabilities object stating what capabilities the browser has for receiving the specified media kind over an RTCPeerConnection. ...
...iven media kind, the returned value is null. Description As a static function, this is always called using the form: capabilities = RTCRtpReceiver.getCapabilities("audio"); The returned set of capabilities is the most optimistic possible list. It is entirely possible that certain combinations of options may fail to work when you actually try to use them. Calling RTCRtpReceiver.getCapabilities
() doesn't prime the browser in any way to handle media. Nothing is loaded, fetched, or otherwise prepared. It's simply a means of determining what might be usable before starting to try to access media. Because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part ...
...ss-origin method for identifying a user. For that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations. Example The function below returns a Boolean indicating whether or not the device supports receiving H.264 video on a WebRTC connection. ...
...ving out rarely-used codec configurations. Example The function below returns a Boolean indicating whether or not the device supports receiving H.264 video on a WebRTC connection. Since RTCRtpReceiver.getCapabilities
() actually only indicates probable support, attempting to receive H.264 video might still fail even after getting a positive response from this function. function canReceiveH264
() { let capabilities = RTCRtpReceiver.getCapabilities("video"); capabilities.codecs.forEach((codec) => { if (codec.mimeType === "video/H264") { return true; } }); return false; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpReceiver.getCapabilities
()' in that specification. ...
RTCRtpSender.getCapabilities() static function - Web APIs
Syntax let rtpCapabilities = RTCRtpSender.getCapabilities(kind); Parameters kind A DOMString indicating the type of media for which you wish to get the sender's capability to receive. All browsers support the primary media kinds: audio and video. Return value An RTCRtpCapabilities object stating what capabilities the browser has for sending the specified media kind over an RTCPeerConnection. ...
...he given media kind, the returned value is null. Description As a static function, this is always called using the form: capabilities = RTCRtpSender.getCapabilities("audio"); The returned set of capabilities is the most optimistic possible list. It is entirely possible that certain combinations of options may fail to work when you actually try to use them. Calling RTCRtpSender.getCapabilities
() doesn't prime the browser in any way to handle media. Nothing is loaded, fetched, or otherwise prepared. It's simply a means of determining what might be usable before starting to try to access media. Because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part ...
...de a cross-origin method for identifying a user. For that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations. Example The function below returns a Boolean indicating whether or not the device supports sending H.264 video on an RTCRtpSender. ...
...ht be done, for example, by leaving out rarely-used codec configurations. Example The function below returns a Boolean indicating whether or not the device supports sending H.264 video on an RTCRtpSender. Since RTCRtpSender.getCapabilities
() actually only indicates probable support, H.264 support might still fail even after getting a positive response from this function. function canSendH264
() { let capabilities = RTCRtpSender.getCapabilities("video"); capabilities.codecs.forEach((codec) => { if (codec.mimeType === "video/H264") { return true; } }); return false; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpSender.getCapabilities
()' in that specification. C...
RTCRtpSender.setStreams() - Web APIs
It doesn't remove the track from any streams; it simply adds it to new ones. ...
.....]); Parameters mediaStream or [mediaStream...] Optional An MediaStream object--or an array of multiple MediaStream objects--identifying the streams to which the RTCRtpSender's track belongs. If this parameter isn't specified, no new streams will be associated with the track. Return value None. Exceptions InvalidStateError The sender's connection is closed. Description setStreams
() is purely additive. It doesn't remove the track from any streams; it simply adds it to new ones. If you specify streams to which the track already belongs, that stream is unaffected. Once the track has been added to all of the streams, renegotiation of the connection will be triggered by the negotiationneeded event being dispatched to the RTCPeerConnection to which the sender belongs. Example ...
... belongs, that stream is unaffected. Once the track has been added to all of the streams, renegotiation of the connection will be triggered by the negotiationneeded event being dispatched to the RTCPeerConnection to which the sender belongs. Example This example adds all of an RTCPeerConnection's tracks to the specified stream. function addTracksToStream(stream) { let senders = pc.getSenders
(); senders.forEach((sender) => { if (sender.track && (sender.transport.state === connected)) { sender.setStreams(stream); } }); } After calling the RTCPeerConnection method getSenders
() to get the list of the connection's senders, the addTracksToStream
() function iterates over the list. For each sender, if the sender's track is non-null and its transport's state is connected, w...
...ach((sender) => { if (sender.track && (sender.transport.state === connected)) { sender.setStreams(stream); } }); } After calling the RTCPeerConnection method getSenders
() to get the list of the connection's senders, the addTracksToStream
() function iterates over the list. For each sender, if the sender's track is non-null and its transport's state is connected, we call setStreams
() to add the track to the stream specified. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpSender.setStreams
()' in that specification. Candidate Recommendation ...
RTCRtpTransceiver.setCodecPreferences() - Web APIs
A guide to codecs supported by WebRTC--and each codec's positive and negative characteristics--can be found in Codecs used by WebRTC. ...
...cs given a list of RTCRtpCodecCapability objects specifying the new preferences for each codec. The specified set of codecs and configurations will be used for all future connections including this transceiver until this method is called again. When preparing to open an RTCPeerConnection, you can change the codec parameters from the user agent's default configuration by calling setCodecParameters
() before calling either RTCPeerConnection.createOffer
() or createAnswer
(). A guide to codecs supported by WebRTC--and each codec's positive and negative characteristics--can be found in Codecs used by WebRTC. Syntax rtcRtpTransceiver.setCodecPreferences(codecs) Parameters codecs An array of RTCRtpCodecCapability objects, in order of preference, each providing the parameters for one of the...
... RTCRtpSender or the RTCRtpReceiver needs to support every codec in the list. If any unsupported codecs are listed, the browser will throw an InvalidAccessError exception when you call this method. A good approach to setting codec preferences is to first get the list of codecs that are actually supported, then modify that list to match what you want. Pass the altered list into setCodecPreferences
() to specify your preferences. To determine which codecs are supported by the transceiver, call the sender's getCapabilities
() and the receiver's getCapabilities
() methods and get the codecs list from the results of each. The following code snippet demonstrates how to get both the list of codecs supported by the transceiver's RTCRtpSender and RTCRtpReceiver. var availSendCodecs = transceiver.sen...
...cs supported by the transceiver's RTCRtpSender and RTCRtpReceiver. var availSendCodecs = transceiver.sender.getCapabilities("video").codecs; var availReceiveCodecs = transceiver.receiver.getCapabilities("video").codecs; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpTransceiver.setCodecPreferences
()' in that specification. Candidate Recommendation ...
Range() - Web APIs
The Range
() constructor returns a newly created Range object whose start and end is the global Document object. Syntax range = new Range
() Example In this example we create a new range with the Range
() constructor, and set its beginning and end positions using the Range.setStartBefore
() and Range.setEndAfter
() methods. We then select the range using window.getSelection
() and Selection.addRange
(). ...
..., and set its beginning and end positions using the Range.setStartBefore
() and Range.setEndAfter
() methods. We then select the range using window.getSelection
() and Selection.addRange
(). ...
... Living Standard Initial definition. ...
...range = new Range
(); // Start range at second paragraph range.setStartBefore(paragraphs[1]); // End range at third paragraph range.setEndAfter(paragraphs[2]); // Get window selection const selection = window.getSelection
(); // Add range to window selection selection.addRange(range); Result Specification Specification Status Comment DOMThe definition of 'Range.Range
()' in that specification. Living Standard Initial definition. ...
Range.extractContents() - Web APIs
The Range.extractContents
() method moves contents of the Range from the document tree into a DocumentFragment. Event listeners added using DOM Events are not retained during extraction. HTML attribute events are retained or duplicated as they are for the Node.cloneNode
() method. HTML id attributes are also cloned, which can lead to an invalid document if a partially-selected node is extracted and appended to the document. Partially selected nodes are cloned to include the parent tags necessary to make the document fragment valid. ...
...HTML attribute events are retained or duplicated as they are for the Node.cloneNode
() method. HTML id attributes are also cloned, which can lead to an invalid document if a partially-selected node is extracted and appended to the document. Partially selected nodes are cloned to include the parent tags necessary to make the document fragment valid. Syntax documentFragment = range.extractContents
(); Example Basic example var range = document.createRange
(); range.selectNode(document.getElementsByTagName("div").item(0)); var documentFragment = range.extractContents
(); document.body.appendChild(documentFragment); Moving items between containers This example lets you move items between two containers. Select one or more item, and then click "swap" to move them to the opposite container. ...
...body { pointer-events: none; } p { border: 1px solid; font-size: 2em; padding: .3em; } button { font-size: 1.2em; padding: .5em; pointer-events: auto; } JavaScript const list1 = document.getElementById('list1'); const list2 = document.getElementById('list2'); const button = document.getElementById('swap'); button.addEventListener('click', e => { selection = window.getSelection
(); for (let i = 0; i < selection.rangeCount; i++) { const range = selection.getRangeAt(i); if (range.commonAncestorContainer === list1 || range.commonAncestorContainer.parentNode === list1) { const documentFragment = range.extractContents
(); list2.appendChild(documentFragment); } else if (range.commonAncestorContainer === list2 || range.commonAncestorCont...
...getRangeAt(i); if (range.commonAncestorContainer === list1 || range.commonAncestorContainer.parentNode === list1) { const documentFragment = range.extractContents
(); list2.appendChild(documentFragment); } else if (range.commonAncestorContainer === list2 || range.commonAncestorContainer.parentNode === list2) { const documentFragment = range.extractContents
(); list1.appendChild(documentFragment); } } }); Result Specifications Specification Status Comment DOMThe definition of 'Range.extractContents
()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.extractContents
()' in that specification. Obsolete ...
Range.selectNodeContents() - Web APIs
The Range.selectNodeContents
() method sets the Range to contain the contents of a Node. The parent Node of the start and end of the Range will be the reference node. The startOffset is 0, and the endOffset is the number of child Nodes or number of characters contained in the reference node. Syntax range.selectNodeContents(referenceNode); Parameters referenceNode The Node whose contents will be selected within a Range. Example range = document.createRange
(); referenceNode = document.getElementsByTagName("div")[0]; range.selectNodeContents(referenceNode); Live sample This example lets the user select and deselect a paragraph with buttons. Document.createRange
(), Range.selectNodeContents
(), and Selection.addRange
() are used to select the content. ...
... contents will be selected within a Range. Example range = document.createRange
(); referenceNode = document.getElementsByTagName("div")[0]; range.selectNodeContents(referenceNode); Live sample This example lets the user select and deselect a paragraph with buttons. Document.createRange
(), Range.selectNodeContents
(), and Selection.addRange
() are used to select the content. Window.getSelection
() and Selection.removeAllRanges
() are used to deselect it. HTML <p id="p"><b>Use the buttons below</b> to select or deselect the contents of this paragraph.</p> <button id="select-button">Select paragraph</button> <button id="deselect-button">Deselect paragraph</button> JavaScript const p = document.getElementById('p'); const selectButton = document.getElementById('select-button'); const desel...
...elect-button">Select paragraph</button> <button id="deselect-button">Deselect paragraph</button> JavaScript const p = document.getElementById('p'); const selectButton = document.getElementById('select-button'); const deselectButton = document.getElementById('deselect-button'); selectButton.addEventListener('click', e => { // Clear any current selection const selection = window.getSelection
(); selection.removeAllRanges
(); // Select paragraph const range = document.createRange
(); range.selectNodeContents(p); selection.addRange(range); }); deselectButton.addEventListener('click', e => { const selection = window.getSelection
(); selection.removeAllRanges
(); }); Result Specifications Specification Status Comment DOMThe definition of 'Range.selec...
....removeAllRanges
(); // Select paragraph const range = document.createRange
(); range.selectNodeContents(p); selection.addRange(range); }); deselectButton.addEventListener('click', e => { const selection = window.getSelection
(); selection.removeAllRanges
(); }); Result Specifications Specification Status Comment DOMThe definition of 'Range.selectNodeContents
()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.selectNodeContents
()' in that specification. Obsolete Initial specification. ...
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
The ReadableStreamDefaultReader
() constructor creates and returns a ReadableStreamDefaultReader object instance. Note: You generally wouldn't use this constructor manually; instead, you'd use the ReadableStream.getReader
() method. Syntax var readableStreamDefaultReader = new ReadableStreamDefaultReader(stream); Parameters stream The ReadableStream to be read. Return value An instance of the ReadableStreamDefaultReader object. Exceptions TypeError The supplied stream parameter is not a ReadableStream, or it is already locked for reading by another reader. Examples In the following simple example, a previously-created custom ReadableStream is read using a ReadableStreamDefaultReader created using getReader
(). (see our Simple random stream example for the full code). Each ...
... a previously-created custom ReadableStream is read using a ReadableStreamDefaultReader created using getReader
(). (see our Simple random stream example for the full code). Each chunk is read sequentially and output to the UI, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the UI. function fetchStream
() { const reader = stream.getReader
(); let charsReceived = 0; // read
() returns a promise that resolves // when a value has been received reader.read
().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) {...
... Living Standard Initial definition. ...
...ment('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.appendChild(listItem); result += chunk; // Read some more, and call this function again return reader.read
().then(processText); }); } Specifications Specification Status Comment StreamsThe definition of 'ReadableStreamDefaultReader
()' in that specification. Living Standard Initial definition. ...
ServiceWorkerContainer.startMessages() - Web APIs
The startMessages
() method of the ServiceWorkerContainer interface explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via Client.postMessage
()). This can be used to react to sent messages earlier, even before that page's content has finished loading. Explanation By default, all messages sent from a page's controlling service worker to the page (using Client.postMessage
()) are queued while the page is loading, and get dispatched once the page's HTML document has been loaded and parsed (i.e. after the DOMContentLoaded event fires). ...
...oading. Explanation By default, all messages sent from a page's controlling service worker to the page (using Client.postMessage
()) are queued while the page is loading, and get dispatched once the page's HTML document has been loaded and parsed (i.e. after the DOMContentLoaded event fires). It's possible to start dispatching these messages earlier by calling ServiceWorkerContainer.startMessages
(), for example if you've invoked a message handler using EventTarget.addEventListener
() before the page has finished loading, but want to start processing the messages right away. ...
...s earlier by calling ServiceWorkerContainer.startMessages
(), for example if you've invoked a message handler using EventTarget.addEventListener
() before the page has finished loading, but want to start processing the messages right away. Note: The messages start being sent automatically when setting the handler directly using ServiceWorkerContainer.onmessage. In this you don't need startMessages
(). Syntax serviceWorkerContainer.startMessages
(); Parameters None. Return value undefined. Examples if('serviceWorker' in navigator) { navigator.serviceWorker .register('/sw.js') .then(function
() { console.log('Service Worker Registered'); }); } // ... navigator.serviceWorker.addEventListener('message', (e) => { // ... }); navigator.serviceWorker.startMessages(...
...navigator.serviceWorker .register('/sw.js') .then(function
() { console.log('Service Worker Registered'); }); } // ... navigator.serviceWorker.addEventListener('message', (e) => { // ... }); navigator.serviceWorker.startMessages
(); Specifications Specification Status Comment Service WorkersThe definition of 'ServiceWorkerContainer: startMessages
()' in that specification. Working Draft Initial definition. ...
ServiceWorkerRegistration.showNotification() - Web APIs
Note: This feature is available in Web Workers. Syntax serviceWorkerRegistration.showNotification(title, [options]); Parameters title The title that must be shown within the notification options Optional An object that allows configuring the notification. It can have the following properties: actions: An array of actions to display in the notification. The members of the array should be an object literal. It may contain the following values: action: A DOMString identifying a user action to be displayed on the notification. title: A DOMString containing action text to be shown to the user. ...
...ith as few as one member. The values are times in milliseconds where the even indices (0, 2, 4, etc.) indicate how long to vibrate and the odd indices indicate how long to pause. For example, [300, 100, 400] would vibrate 300ms, pause 100ms, then vibrate 400ms. Return value A Promise that resolves to undefined. ...
... Living Standard Initial definition. ...
...the above function at an appropriate time, you could use the ServiceWorkerGlobalScope.onnotificationclick event handler. 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.unregister() - Web APIs
Return value Promise resolves with a boolean indicating whether the service worker has unregistered or not. ...
... Return value Promise resolves with a boolean indicating whether the service worker has unregistered or not. ...
... Return value Promise resolves with a boolean indicating whether the service worker has unregistered or not. ...
...the service worker has unregistered or not. Example The following simple example registers a service worker example, but then immediately unregisters it again: if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw-test/sw.js', {scope: 'sw-test'}).then(function(registration) { // registration worked console.log('Registration succeeded.'); registration.unregister
().then(function(boolean) { // if boolean = true, unregister is successful }); }).catch(function(error) { // registration failed console.log('Registration failed with ' + error); }); }; Specifications Specification Status Comment Service WorkersThe definition of 'ServiceWorkerRegistration.unregister
()' in that specification. Working Draft Initial...
SourceBuffer.changeType() - Web APIs
This makes it possible to change codecs or container type mid-stream. One scenario in which this is helpful is to support adapting the media source to changing bandwidth availability, by transitioning from one codec to another as resource constraints change. Syntax sourceBuffer.changeType(type); Parameters type A DOMString specifying the MIME type that future buffers will conform to. Return value undefined. Exceptions TypeError The specified string is empty, rather than indicating a valid MIME type. ...
...ameters type A DOMString specifying the MIME type that future buffers will conform to. Return value undefined. Exceptions TypeError The specified string is empty, rather than indicating a valid MIME type. ...
...ype A DOMString specifying the MIME type that future buffers will conform to. Return value undefined. Exceptions TypeError The specified string is empty, rather than indicating a valid MIME type. ...
... sourceBuffers list, or the buffer's updating property indicates that a previously queued appendBuffer
() or remove
() is still being processed. NotSupportedError The specified MIME type is not supported, or is not supported with the types of SourceBuffer objects present in the MediaSource.sourceBuffers list. Usage notes If the parent MediaSource is in its "ended" readyState, calling changeType
() will transition the media source to the "open" readyState and fire a simple event named sourceopen at the parent media source. ...
SpeechGrammarList.addFromString() - Web APIs
stored in a variable) and adds it to the SpeechGrammarList as a new SpeechGrammar object. Syntax speechGrammarListInstance.addFromString(string,weight); Returns Void. Parameters string A DOMString representing the grammar to be added. weight Optional A float representing the weight of the grammar relative to other grammars present in the SpeechGrammarList. The weight means the importance of this grammar, or the likelihood that it will be recognised by the speech recognition service. The value can be between 0.0 and 1.0; If not specified, the default used is 1.0. ...
... Draft ...
... Draft ...
... Draft ...
SpeechRecognition() - Web APIs
The SpeechRecognition
() constructor creates a new SpeechRecognition object instance. Syntax var myRecognition = new SpeechRecognition
(); Parameters None. Examples This code is excerpted from our Speech color changer example. ...
... Specifications Specification Status Comment Web Speech APIThe definition of 'SpeechRecog...
... Draft ...
...speechRecognitionList = new SpeechGrammarList
(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; //recognition.continuous = false; recognition.lang = 'en-US'; recognition.interimResults = false; recognition.maxAlternatives = 1; ... Specifications Specification Status Comment Web Speech APIThe definition of 'SpeechRecognition
()' in that specification. Draft ...
Storage.clear() - Web APIs
Specifications Specification Status Comment HTML Living StandardThe definition of 'Storage.clear' in that specification. ...
... Specifications Specification Status Comment HTML Living StandardThe definition of 'Storage.clear' in that specification. ...
... Specifications Specification Status Comment HTML Living StandardThe definition of 'Storage.clear' in that specification. ...
... all keys stored in a given Storage object. Syntax storage.clear
(); Return value undefined. Examples The following function creates three data entries in local storage, and then deletes them by using clear
(). function populateStorage
() { localStorage.setItem('bgcolor', 'red'); localStorage.setItem('font', 'Helvetica'); localStorage.setItem('image', 'miGato.png'); localStorage.clear
(); } Note: For a real world example, see our Web Storage Demo. Specifications Specification Status Comment HTML Living StandardThe definition of 'Storage.clear' in that specification. Living Standard ...
StylePropertyMapReadOnly.get() - Web APIs
The get
() method of the StylePropertyMapReadOnly interface returns a CSSStyleValue object for the first value of the specified property. Syntax var declarationBlock = StylePropertyMapReadOnly.get(property) Parameters property The name of the property to retrieve the value of. Return value A CSSStyleValue object. Examples Let's get just a few properties and values. ...
...start by creating a link inside a paragraph in our HTML, and adding a definition list which we will populate with JavaScript: <p> <a href="https://example.com">Link</a> </p> <dl id="regurgitation"></dl> We add a bit of CSS, including a custom property and an inhertable property: p { font-weight: bold; } a { --colour: red; color: var(--colour); } We use the Element's computedStyleMap
() to return a StylePropertyMapReadOnly object. We create an array of properties of interest and use the StylePropertyMapReadOnly's get
() method to get only those values. // get the element const myElement = document.querySelector('a'); // get the <dl> we'll be populating const stylesList = document.querySelector('#regurgitation'); // Retrieve all computed styles with computedStyleMap
() const sty...
...nly object. We create an array of properties of interest and use the StylePropertyMapReadOnly's get
() method to get only those values. ...
... Working Draft Initial definition. ...
SubtleCrypto.decrypt() - Web APIs
To use RSA-OAEP, pass an RsaOaepParams object. To use AES-CTR, pass an AesCtrParams object. To use AES-CBC, pass an AesCbcParams object. ...
...nown as "ciphertext"). It returns a Promise which will be fulfilled with the decrypted data (also known as "plaintext"). Syntax const result = crypto.subtle.decrypt(algorithm, key, data); Parameters algorithm is an object specifying the algorithm to be used, and any extra parameters as required. The values given for the extra parameters must match those passed into the corresponding encrypt
() call. To use RSA-OAEP, pass an RsaOaepParams object. To use AES-CTR, pass an AesCtrParams object. To use AES-CBC, pass an AesCbcParams object. To use AES-GCM, pass an AesGcmParams object. key is a CryptoKey containing the key to be used for decryption. If using RSA-OAEP, this is the privateKey property of the CryptoKeyPair object. data is a BufferSource containing the data ...
...: InvalidAccessError Raised when the requested operation is not valid for the provided key (e.g. invalid encryption algorithm, or invalid key for the specified encryption algorithm). OperationError Raised when the operation failed for an operation-specific reason (e.g. algorithm parameters of invalid sizes, or there was an error decrypting the ciphertext). Supported algorithms The decrypt
() method supports the same algorithms as the encrypt
() method. Examples Note: You can try the working examples on GitHub. RSA-OAEP This code decrypts ciphertext using RSA-OAEP. See the complete code on GitHub. function decryptMessage(privateKey, ciphertext) { return window.crypto.subtle.decrypt( { name: "RSA-OAEP" }, privateKey, ciphertext ); } AES-CTR This code d...
... GCM mode. Note that iv must match the value that was used for encryption. See the complete code on GitHub. function decryptMessage(key, ciphertext) { return window.crypto.subtle.decrypt( { name: "AES-GCM", iv: iv }, key, ciphertext ); } Specifications Specification Status Comment Web Cryptography APIThe definition of 'SubtleCrypto.decrypt
()' in that specification. Recommendation Initial definition. ...
TransitionEvent() - Web APIs
type Is a DOMString representing the name of the type of the TransitionEvent. It is case-sensitive and can only be: 'transitionend'. propertyName Optional Is a DOMString containing the value of the property-name CSS property associated with the transition. It defaults to "". ...
... type Is a DOMString representing the name of the type of the TransitionEvent. It is case-sensitive and can only be: 'transitionend'. propertyName Optional Is a DOMString containing the value of the property-name CSS property associated with the transition. It defaults to "". ...
... newly created TransitionEvent, representing an event in relation with an transition. Syntax transitionEvent = new TransitionEvent(type, {propertyName: aPropertyName, elapsedTime : aFloat, pseudoElement: aPseudoElementName}); Arguments The TransitionEvent
() constructor also inherits arguments from Event
(). type Is a DOMString representing the name of the type of the TransitionEvent. It is case-sensitive and can only be: 'transitionend'. propertyName Optional Is a DOMString containing the value of the property-name CSS property associated with the transition. It defaults to "". elapsedTime Optional Is float giving the amount of time the animation has been running, in seconds, when this ...
...ining (-1 * delay). It defaults to 0.0. pseudoElement Optional Is a DOMString, starting with "::", containing the name of the pseudo-element the animation runs on. If the animation doesn't run on a pseudo-element but on the element, an empty string: "". It defaults to "". Specifications Specification Status Comment CSS TransitionsThe definition of 'TransitionEvent
()' in that specification. Working Draft Initial definition. ...
URL.createObjectURL() - Web APIs
Note: This feature is available in Web Workers. Note: This feature is not available in Service Workers due to its potential to create memory leaks. Syntax const objectURL = URL.createObjectURL(object) Parameters object A File, Blob, or MediaSource object to create an object URL for. Return value A DOMString containing an object URL that can be used to reference the contents of the specified source object. ...
...aks. Syntax const objectURL = URL.createObjectURL(object) Parameters object A File, Blob, or MediaSource object to create an object URL for. Return value A DOMString containing an object URL that can be used to reference the contents of the specified source object. Examples See Using object URLs to display images. Usage notes Memory management Each time you call createObjectURL
(), a new object URL is created, even if you've already created one for the same object. Each of these must be released by calling URL.revokeObjectURL
() when you no longer need them. Browsers will release object URLs automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so. Using ob...
... are safe times when you can explicitly unload them, you should do so. Using object URLs for media streams In older versions of the Media Source specification, attaching a stream to a <video> element required creating an object URL for the MediaStream. This is no longer necessary, and browsers are removing support for doing this. Important: If you still have code that relies on createObjectURL
() to attach streams to media elements, you need to update your code to simply set srcObject to the MediaStream directly. Specifications Specification Status Comment File APIThe definition of 'createObjectURL
()' in that specification. Working Draft Initial definition. Media Source ExtensionsThe definition of 'URL' in that specification. Recommendation ...
... to the MediaStream directly. Specifications Specification Status Comment File APIThe definition of 'createObjectURL
()' in that specification. Working Draft Initial definition. Media Source ExtensionsThe definition of 'URL' in that specification. Recommendation MediaSource extension. Older versions of this specification used createObjectURL
() for MediaStream objects; this is no longer supported. ...
WebGL2RenderingContext.endTransformFeedback() - Web APIs
Editor's Draft Initial definition for WebGL. OpenGL ES 3.0The definition of 'glEndTransformFeedback' in that specification. ...
... Editor's Draft Initial definition for WebGL. OpenGL ES 3.0The definition of 'glEndTransformFeedback' in that specification. ...
... Editor's Draft Initial definition for WebGL. OpenGL ES 3.0The definition of 'glEndTransformFeedback' in that specification. ...
... Editor's Draft Initial definition for WebGL. OpenGL ES 3.0The definition of 'glEndTransformFeedback' in that specification. ...
WebGLRenderingContext.getContextAttributes() - Web APIs
The WebGLRenderingContext.getContextAttributes
() method returns a WebGLContextAttributes object that contains the actual context parameters. Might return null, if the context is lost. Syntax gl.getContextAttributes
(); Return value A WebGLContextAttributes object that contains the actual context parameters, or null if the context is lost. ...
...null, if the context is lost. Syntax gl.getContextAttributes
(); Return value A WebGLContextAttributes object that contains the actual context parameters, or null if the context is lost. ...
... Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLRenderingContext.getContextAttributes' in that specification. Recommendation Initial definition. ...
... Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLRenderingContext.getContextAttributes' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.getSupportedExtensions() - Web APIs
WebGL extensions Extensions for the WebGL API are registered in the WebGL Extension Registry. ...
... WebGL extensions Extensions for the WebGL API are registered in the WebGL Extension Registry. ...
... WebGL extensions Extensions for the WebGL API are registered in the WebGL Extension Registry. ...
... WebGL extensions Extensions for the WebGL API are registered in the WebGL Extension Registry. ...
Window.captureEvents() - Web APIs
The Window.captureEvents
() method registers the window to capture all events of the specified type. Syntax window.captureEvents(eventType) eventType is a combination of the following values: Event.ABORT, Event.BLUR, Event.CLICK, Event.CHANGE, Event.DBLCLICK, Event.DRAGDDROP, Event.ERROR, Event.FOCUS, Event.KEYDOWN, Event.KEYPRESS, Event.KEYUP, Event.LOAD, Event.MOUSEDOWN, Event.MOUSEMOVE, Event.MOUSEOUT, Event.MOUSEOVER, Event.MOUSEUP, Event.MOVE, Event.RESET, Event.RESIZE, Event.SELECT, Event.SUBMIT, Event.UNLOAD. Example <!DOCTYPE html> <html lang="en"> <head> <!-- ... ...
...vent.BLUR, Event.CLICK, Event.CHANGE, Event.DBLCLICK, Event.DRAGDDROP, Event.ERROR, Event.FOCUS, Event.KEYDOWN, Event.KEYPRESS, Event.KEYUP, Event.LOAD, Event.MOUSEDOWN, Event.MOUSEMOVE, Event.MOUSEOUT, Event.MOUSEOVER, Event.MOUSEUP, Event.MOVE, Event.RESET, Event.RESIZE, Event.SELECT, Event.SUBMIT, Event.UNLOAD. Example <!DOCTYPE html> <html lang="en"> <head> <!-- ... ...
..., Event.KEYDOWN, Event.KEYPRESS, Event.KEYUP, Event.LOAD, Event.MOUSEDOWN, Event.MOUSEMOVE, Event.MOUSEOUT, Event.MOUSEOVER, Event.MOUSEUP, Event.MOVE, Event.RESET, Event.RESIZE, Event.SELECT, Event.SUBMIT, Event.UNLOAD. Example <!DOCTYPE html> <html lang="en"> <head> <!-- ... --> <script> function reg
() { window.captureEvents(Event.CLICK); window.onclick = page_click; } function page_click
() { alert('page click event detected!'); } </script> </head> <body onload="reg
();"> <p>click anywhere on this page.</p> </body> </html> Notes Events raised in the DOM by user activity (such as clicking buttons or shifting focus away from the current document) generally pass through the high-level window and document objects first before arriving at the object that initiated the event. When y...
...ent detected!'); } </script> </head> <body onload="reg
();"> <p>click anywhere on this page.</p> </body> </html> Notes Events raised in the DOM by user activity (such as clicking buttons or shifting focus away from the current document) generally pass through the high-level window and document objects first before arriving at the object that initiated the event. When you call the captureEvents
() method on the window, events of the type you specify (for example, Event.CLICK) no longer pass through to "lower" objects in the hierarchy. In order for events to "bubble up" in the way that they normally do, you must call window.releaseEvents
() ( ) on the window to keep it from trapping events. Note that you can pass a list of events to this method using the following syntax: window.captureEven...
Window.stop() - Web APIs
Living Standard HTML5The definition of 'Window.stop' in that specification. Recommendation Browser Compatibility The compatibility table in this page is generated from structured data. ...
... Living Standard HTML5The definition of 'Window.stop' in that specification. Recommendation Browser Compatibility The compatibility table in this page is generated from structured data. ...
... Living Standard HTML5The definition of 'Window.stop' in that specification. Recommendation Browser Compatibility The compatibility table in this page is generated from structured data. ...
... Living Standard HTML5The definition of 'Window.stop' in that specification. ...
WindowClient.focus() - Web APIs
The focus
() method of the WindowClient interface gives user input focus to the current client and returns a Promise that resolves to the existing WindowClient. Syntax windowClient.focus
().then(function(windowClient) { // do something with your WindowClient once it has been focused }); Parameters None. Return value A Promise that resolves to the existing WindowClient. ...
...ting WindowClient. Syntax windowClient.focus
().then(function(windowClient) { // do something with your WindowClient once it has been focused }); Parameters None. Return value A Promise that resolves to the existing WindowClient. ...
... Working Draft Initial definition. ...
... Working Draft Initial definition. ...
WindowOrWorkerGlobalScope.atob() - Web APIs
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. ...
... 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. ...
... 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. ...
...ta = 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 Standard. Cre...
Worklet.addModule() - Web APIs
Syntax addPromise = worklet.addModule(moduleURL); addPromise = worklet.addModule(moduleURL, options); Parameters moduleURL A String containing the URL of a JavaScript file with the module to add. options Optional An object with any of the following options: credentials: A RequestCredentials value that indicates whether to send credentials (e.g. cookies and HTTP authentification) when loading the module. Can be one of "omit", "same-origin", or "include". Defaults to "same-origin". See also Request.credentials. Return value A Promise that resolves once the module from the given URL has been added. ...
...RequestCredentials value that indicates whether to send credentials (e.g. cookies and HTTP authentification) when loading the module. Can be one of "omit", "same-origin", or "include". Defaults to "same-origin". See also Request.credentials. Return value A Promise that resolves once the module from the given URL has been added. The promise doesn't return any value. ...
...nce the module from the given URL has been added. The promise doesn't return any value. Exceptions If addModule
() fails, it rejects the promise, delivering one of the following errors to the rejection handler. AbortError The specified script is invalid or could not be loaded. SyntaxError The specified moduleURL is invalid. ...
...ed moduleURL is invalid. Examples AudioWorklet example const audioCtx = new AudioContext
(); const audioWorklet = audioCtx.audioWorklet; await audioWorklet.addModule('modules/bypassFilter.js', { credentials: 'omit', }); PaintWorklet example CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/worklets/hilite.js'); Once a paintWorklet is included, the CSS paint
() function can be used to include the image created by the worklet: @supports (background-image: paint(id)) { h1 { background-image: paint(hollowHighlights, filled, 3px); } } Specifications Specification Status Comment Worklets Level 1The definition of 'addModule
()' in that specification. Working Draft ...
XMLHttpRequest.abort() - Web APIs
The XMLHttpRequest.abort
() method aborts the request if it has already been sent. When a request is aborted, its readyState is changed to XMLHttpRequest.UNSENT (0) and the request's status code is set to 0. Syntax XMLHttpRequest.abort
() Parameters None. Return value undefined Example This example begins loading content from the MDN home page, then due to some condition, aborts the transfer by calling abort
(). ...
...st if it has already been sent. When a request is aborted, its readyState is changed to XMLHttpRequest.UNSENT (0) and the request's status code is set to 0. Syntax XMLHttpRequest.abort
() Parameters None. Return value undefined Example This example begins loading content from the MDN home page, then due to some condition, aborts the transfer by calling abort
(). ...
...ENT (0) and the request's status code is set to 0. Syntax XMLHttpRequest.abort
() Parameters None. Return value undefined Example This example begins loading content from the MDN home page, then due to some condition, aborts the transfer by calling abort
(). ...
...Request.abort
() Parameters None. Return value undefined Example This example begins loading content from the MDN home page, then due to some condition, aborts the transfer by calling abort
(). ...
XMLHttpRequest.getResponseHeader() - Web APIs
The XMLHttpRequest method getResponseHeader
() returns the string containing the text of a particular header's value. If there are multiple response headers with the same name, then their values are returned as a single concatenated string, where each value is separated from the previous one by a pair of comma and space. The getResponseHeader
() method returns the value as a UTF byte sequence. Note: The search for the header name is case-insensitive. If you need to get the raw string of all of the headers, use the getAllResponseHeaders
() method, which returns the entire raw header string. Syntax var myHeader = XMLHttpRequest.getResponseHeader(headerName); Parameters headerName A ByteString indicating the name of the header you want to return the text value of. Return value A Byt...
...n received or the header doesn't exist in the response. Example In this example, a request is created and sent, and a readystatechange handler is established to look for the readyState to indicate that the headers have been received; when that is the case, the value of the Content-Type header is fetched. If the Content-Type isn't the desired value, the XMLHttpRequest is canceled by calling abort
(). ...
...st in the response. Example In this example, a request is created and sent, and a readystatechange handler is established to look for the readyState to indicate that the headers have been received; when that is the case, the value of the Content-Type header is fetched. If the Content-Type isn't the desired value, the XMLHttpRequest is canceled by calling abort
(). ...
...ent, and a readystatechange handler is established to look for the readyState to indicate that the headers have been received; when that is the case, the value of the Content-Type header is fetched. If the Content-Type isn't the desired value, the XMLHttpRequest is canceled by calling abort
(). var client = new XMLHttpRequest
(); client.open("GET", "unicorns-are-teh-awesome.txt", true); client.send
(); client.onreadystatechange = function
() { if(this.readyState == this.HEADERS_RECEIVED) { var contentType = client.getResponseHeader("Content-Type"); if (contentType != my_expected_type) { client.abort
(); } } } Specifications Specification Status Comment XMLHttpRequestThe definition of 'getResponseHeader
()' in that specification. Living Stand...
XPathExpression.evaluate() - Web APIs
Syntax XPathResult node.evaluate(contextNode, type, result); Parameters contextNode A Node representing the context to use for evaluating the expression. type Optional Specifies the type of result to be returned by evaluating the expression. This must be one of the XPathResult.Constants. result Optional Allows to specify a result object which may be reused and returned by this method. If this is specified as null or the implementation does not reuse the specified result, a new result object will be returned. Return value An XPathResult object representing the result of evaluating the XPath expression. ...
...ontext node is from a document that is not supported by the XPathEvaluator, a DOMException of type WRONG_DOCUMENT_ERR is raised. NOT_SUPPORTED_ERR If the provided context node is not a type permitted as an XPath context node or the request type is not permitted by the XPathEvaluator, a DOMException of type NOT_SUPPORTED_ERR is raised. ...
...context node is not a type permitted as an XPath context node or the request type is not permitted by the XPathEvaluator, a DOMException of type NOT_SUPPORTED_ERR is raised. Example The following example shows the use of the evaluate
() method. ...
...Evaluator
(); var expression = evaluator.createExpression("//div"); var result = expression.evaluate(document, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE); document.querySelector("output").textContent = result.snapshotLength; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathExpression.evaluate
()' in that specification. Recommendation Initial definition ...
XRInputSourceArray.entries() - Web APIs
The XRInputSourceArray interface's entries
() method returns a JavaScript iterator which can then be used to iterate over the key/value pairs in the input source array. Each item in the array is an XRInputSource object. Most frequently, you will use this in tandem with statements such as for...of. Syntax let inputSourceIterator = xrInputSourceArray.entries
(); for (let entry of xrInputSourceArray.entries
()) { /* ... */ } Parameters None. Return value An iterator which can be used to walk through the list of XRInputSource objects included in the input source array. Examples This example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using. ...
...utSourceArray.entries
()) { /* ... */ } Parameters None. Return value An iterator which can be used to walk through the list of XRInputSource objects included in the input source array. Examples This example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using. ...
...sources.entries
()) { if (input.gamepad) { checkGamepad(input.gamepad); } else { if (input.targetRayMode === "tracked-pointer" && input.handedness === player.handedness) { /* Handle main hand controller */ handleMainHandInput(input); } else { /* Handle other inputs */ } } } For each input in the llist, gamepad inputs are dispatched to a checkGamepad
() with the input's Gamepad object, taken from its gamepad property, as an input For other devices, we look for tracked-pointer devices in the player's main hand, dispatching those to a handleMainHandInput
() method. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRInputSourceArray' in that specification.1 Working Draft XRInputSourc...
... handleMainHandInput
() method. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRInputSourceArray' in that specification.1 Working Draft XRInputSourceArray interface [1] See Iterator-like methods in Information contained in a WebIDL file for information on how an iterable declaration in an interface definition causes entries
(), forEach
(), keys
(), and values
() methods to be exposed from objects that implement the interface. ...
XRInputSourceArray.forEach() - Web APIs
Syntax xrInputSourceArray.forEach(callback, thisArg); Parameters callback A function to execute once for each entry in the array xrInputSourceArray. The callback accepts up to three parameters: currentValue A XRInputSource object which is the value of the item from within the xrInputSourceArray which is currently being processed. currentIndex Optional An integer value providing the index into the array at which the element given by currentValue is located. If you don't need to know the index number, you can omit this. ...
... Specifications Specification Status Comment WebXR Device APIThe definition of 'XRInputSourceArray' in that specification.1 Working Draft XRInputSourc...
...controller */ handleMainHandInput(input); } else { /* Handle other inputs */ } } }); For each input in the llist, the callback dispatches gamepad inputs to a checkGamepad
() with the input's Gamepad object, taken from its gamepad property, as an input For other devices, we look for tracked-pointer devices in the player's main hand, dispatching those to a handleMainHandInput
() method. ...
... handleMainHandInput
() method. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRInputSourceArray' in that specification.1 Working Draft XRInputSourceArray interface [1] See Iterator-like methods in Information contained in a WebIDL file for information on how an iterable declaration in an interface definition causes entries
(), forEach
(), keys
(), and values
() methods to be exposed from objects that implement the interface. ...
:host() - CSS: Cascading Style Sheets
Note: This has no effect when used outside a shadow DOM. ...
... given as the function's parameter matches the shadow host. The most obvious use of this is to put a class name only on certain custom element instances, and then include the relevant class selector as the function argument. You can't use this with a descendant selector expression to select only instances of the custom element that are inside a particular ancestor. That's the job of :host-context
(). Note: This has no effect when used outside a shadow DOM. /* Selects a shadow root host, only if it is matched by the selector argument */ :host(.special-custom-element) { font-weight: bold; } Syntax :host( <compound-selector-list> )where <compound-selector-list> = <compound-selector>#where <compound-selector> = [ <type-selector>? <subclass-selector>* [ <pseudo-element-selector> <pseu...
...; }'; The :host(.footer) { color : red; } rule styles all instances of the <context-span> element (the shadow host in this instance) in the document that have the footer class set on them -- we've used it to give instances of the element inside the <footer> a special color. ...
... a special color. Specifications Specification Status Comment CSS Scoping Module Level 1The definition of ':host
()' in that specification. Working Draft Initial definition. ...
conic-gradient() - 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. ...
... 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 As with any gradient, a conic gradient has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. Its concrete size will match the size of the element it applies to, or size of the <image> is set to something other than the element size. To create a conic gradient that repeats so as to fill a 360 degree rotation, use the repeating-conic-gradient
() function instead. Because <gradient>s belong to the <image> data type, they can only be used where <image>s can be used. For this reason, conic-gradient
() won't work on background-color and other properties that use the <color> data type. Why is it called a "conic" gradient? If the color stops are much lighter on one side than the other, it can look like a cone from above. Composition of a c...
... Working Draft ...
counters() - CSS: Cascading Style Sheets
It is generally used with pseudo-elements, but can be used, theoretically, anywhere a <string> value is supported. The generated text is the value of all counters with the given name, from outermost to innermost, separated by the specified string. The counters are rendered in the style indicated, defaulting to decimal if no style is specified. ...
...ounters with the given name, from outermost to innermost, separated by the specified string. The counters are rendered in the style indicated, defaulting to decimal if no style is specified. /* Simple usage - style defaults to decimal */ counters(countername, '-'); /* changing the counter display */ counters(countername, '.', upper-roman) A counter has no visible effect by itself. The counters
() function (and counter
() function) is what makes it useful by returning developer defined content. Note: The counters
() function can be used with any CSS property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse. Check the Browser compatibility table carefully before using this in production. Syntax Values <custom-ident> ...
...unit parameter is sparse. Check the Browser compatibility table carefully before using this in production. Syntax Values <custom-ident> A name identifying the counters, which is the same case-sensitive name used for the counter-reset and counter-increment. The name cannot start with two dashes and can't be none, unset, initial, or inherit. <counter-style> A counter style name or symbols
() function, where a counter style name is a numeric, alphabetic, or symbolic simple predefined counter style, a complex longhand east Asian or Ethiopic predefined counter style, or other predefined counter style. If omitted, the counter-style defaults to decimal <string> Any number of text characters. Non-Latin characters must be encoded using their Unicode escape sequences: for example, \000A9 r...
...ined counter style, or other predefined counter style. If omitted, the counter-style defaults to decimal <string> Any number of text characters. Non-Latin characters must be encoded using their Unicode escape sequences: for example, \000A9 represents the copyright symbol. ...
fit-content() - 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. The function can be used as a track size in CSS Grid properties, where the maximum size is defined by max-content and the minimum size by auto, which is calculated similar to auto (i.e., minmax(auto, max-content)), except that the track size is clamped at argument if it is greater than the auto minimum. ...
...t and the minimum size by auto, which is calculated similar to auto (i.e., minmax(auto, max-content)), except that the track size is clamped at argument if it is greater than the auto minimum. The function can also be used as laid out box size for width, height, min-width, min-height, max-width and max-height, where the maximum and minimum sizes refer to the content size. Syntax The fit-content
() function accepts a <length> or a <percentage> as an argument. /* <length> values */ fit-content(200px) fit-content(5cm) fit-content(30vw) fit-content(100ch) /* <percentage> value */ fit-content(40%) Values <length> An absolute length. <percentage> A percentage relative to the available space in the given axis. In grid properties it is relative to the inline size of the grid container i...
... Candidate Recommendation Defines the function when used as a track size. ...
...background-color: #8ca0ff; padding: 5px; } Result Specifications Specification Status Comment CSS Box Sizing Module Level 3The definition of 'fit-content
()' in that specification. Working Draft Defines the function as laid out box size for width, height, min-width, min-height, max-width and max-height. CSS Grid LayoutThe definition of 'fit-content
()' in that specification. Candidate Recommendation Defines the function when used as a track size. ...
linear-gradient() - CSS: Cascading Style Sheets
Its result is an object of the <gradient> data type, which is a special kind of <image>. 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. ...
...e to set the html height property to 100% or 100vh to render as depicted. Description As with any gradient, a linear gradient has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. Its concrete size will match the size of the element it applies to. To create a linear gradient that repeats so as to fill its container, use the repeating-linear-gradient
() function instead. Because <gradient>s belong to the <image> data type, they can only be used where <image>s can be used. For this reason, linear-gradient
() won't work on background-color and other properties that use the <color> data type. Composition of a linear gradient A linear gradient is defined by an axis--the gradient line--and two or more color-stop points. Each point on the axis is a ...
... The gradient line is defined by the center of the box containing the gradient image and by an angle. ...
... Candidate Recommendation Initial definition. ...
radial-gradient() - CSS: Cascading Style Sheets
Its shape may be a circle or an ellipse. The function's result is an object of the <gradient> data type, which is a special kind of <image>. 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. ...
...the midpoint of the color transition is the midpoint between two color stops. Description As with any gradient, a radial gradient has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. Its concrete size will match the size of the element it applies to. To create a radial gradient that repeats so as to fill its container, use the repeating-radial-gradient
() function instead. Because <gradient>s belong to the <image> data type, they can only be used where <image>s can be used. For this reason, radial-gradient
() won't work on background-color and other properties that use the <color> data type. Composition of a radial gradient A radial gradient is defined by a center point, an ending shape, and two or more color-stop points. To create a smooth gra...
...The ending shape may be either a circle or an ellipse. ...
... Candidate Recommendation Initial definition. ...
repeating-conic-gradient() - CSS: Cascading Style Sheets
{{EmbedInteractiveExample("pages/css/function-repeating-conic-gradient.html")}} 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. ...
...two color stops the gradient color should reach the midpoint of the color transition. If omitted, the midpoint of the color transition is the midpoint between two color stops. Note: Rendering of color stops in CSS gradients follows the same rules as color stops in SVG gradients. Description Example repeating conic gradients include starbursts. The result of the repeating-conic-gradient
() function is an object of the <gradient> data type, which is a special kind of <image>. If neither the first nor the last color stops include include a a color stop angle greater than 0deg or less than 360 degrees respectively, the conic-gradient will not repeat. As with any gradient, a repeating-conic gradient has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferr...
...t has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. Its concrete size will match the size of the element it applies to, or the size the <image> is set to if it's set to something other than the element's size. Because <gradient>s belong to the <image> data type, they can only be used where <image>s can be used. For this reason, repeating-conic-gradient
() won't work on background-color and other properties that use the <color> data type. To create a conic gradient that doe not repeat, make the gradient a full 360 degree rotation, or use the conic-gradient
() function instead. Understanding repeating conic gradients The repeating-conic-gradient syntax is similar to the conic-gradient
() and repeating-radial-gradient
() syntax. Like the non-repea...
... Working Draft ...
symbols() - CSS: Cascading Style Sheets
numeric: The system interprets the given values as the successive units of a place-value numbering system. ...
... numeric: The system interprets the given values as the successive units of a place-value numbering system. ...
... numeric: The system interprets the given values as the successive units of a place-value numbering system. ...
...c.). fixed: The system cycles through the given values once, then falls back to Arabic numerals. Examples HTML <ol> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Five</li> </ol> CSS ol { list-style: symbols(cyclic "*" "+" "?"); } Result Specifications Specification Status Comment CSS Counter Styles Level 3The definition of 'symbols
()' in that specification. Candidate Recommendation Initial defintion. ...
matrix3d() - CSS: Cascading Style Sheets
They are described in the column-major order. matrix3d(a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3, a4, b4, c4, d4) Values a1 b1 c1 d1 a2 b2 c2 d2 a3 b3 c3 d3 Are <number>s describing the linear transformation. a4 b4 c4 d4 Are <number>s describing the translation to apply. Note: Until Firefox 16, Gecko accepted a <length> value for a4, b4 and c4. Cartesian coordinates on R2 Homogeneous coordinates on RP2 Cartesian coordinates on R3 Homogeneous coordinates on RP3 This transformation applies to the 3D space and can't be represented on the plane. ...
... 3D space and can't be represented on the plane. A generic 3D affine transformation can't be represented using a Cartesian-coordinate matrix, as translations are not linear transformations. a1a2a3a4b1b2b3b4c1c2c3c4d1d2d3d4 Examples Cube squashing example The following example shows a 3D cube created from DOM elements and transforms, which can be hovered/focused to apply a matrix3d
() transform to it. HTML <section id="example-element" tabindex="0"> <div class="face front">1</div> <div class="face back">2</div> <div class="face right">3</div> <div class="face left">4</div> <div class="face top">5</div> <div class="face bottom">6</div> </section> CSS #example-element { width: 100px; height: 100px; transform-style: preserve-3d; transition: transform 1.5s...
... HTML <div class="foo"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos quaerat sit soluta, quisquam exercitationem delectus qui unde in facere necessitatibus aut quia porro dolorem nesciunt enim, at consequuntur aliquam esse? </div> CSS html { width: 100%; } body { height: 100vh; /* Centering content */ ...
... Editor's Draft Initial definition ...
Array.prototype.reduceRight() - JavaScript
Syntax arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue]) Parameters callback Function to execute on each value in the array, taking four arguments: accumulator The value previously returned in the last invocation of the callback, or initialValue, if supplied. ...
... Syntax arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue]) Parameters callback Function to execute on each value in the array, taking four arguments: accumulator The value previously returned in the last invocation of the callback, or initialValue, if supplied. ...
... callback Function to execute on each value in the array, taking four arguments: accumulator The value previously returned in the last invocation of the callback, or initialValue, if supplied. (See below.) currentValue The current element being processed in the array. indexOptional The index of the current element being processed in the array. arrayOptional The array reduceRight
() was called upon. initialValueOptional Value to use as accumulator to the first call of the callback. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduce or reduceRight on an empty array without an initial value creates a TypeError. Return value The value that results from the reduction. Description reduceRight executes the callback fu...
... return a.concat(b); }, []); // flattened is [4, 5, 2, 3, 0, 1] Run a list of asynchronous functions with callbacks in series each passing their results to the next const waterfall = (...functions) => (callback, ...args) => functions.reduceRight( (composition, fn) => (...results) => fn(composition, ...results), callback )(...args); const randInt = max => Math.floor(Math.random
() * max) const add5 = (callback, x) => { setTimeout(callback, randInt(1000), x + 5); }; const mult3 = (callback, x) => { setTimeout(callback, randInt(1000), x * 3); }; const sub2 = (callback, x) => { setTimeout(callback, randInt(1000), x - 2); }; const split = (callback, x) => { setTimeout(callback, randInt(1000), x, x); }; const add = (callback, x, y) => { setTimeout(callback, randInt(1...
Array.prototype.every() - JavaScript
It returns a Boolean 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 arr.every(callback(element[, index[, array]])[, thisArg]) Parameters callback A function to test for each element, taking three arguments: element The current element being processed in the array. index Optional The index of the current element being processed in the array. array Optional The array every was called upon. thisArg Optional A value to use as this when executing callback. ...
... // 2. Let lenValue be the result of calling the Get internal method // of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. if (typeof callbackfn !== 'function' && Object.prototype.toString.call(callbackfn) !== '[object Function]') { throw new TypeError
(); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let k be 0. k = 0; // 7. Repeat, while k < len while (k < len) { var kValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of callin...
... ...
... ...
Array.prototype.indexOf() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax arr.indexOf(searchElement[, fromIndex]) Parameters searchElement Element to locate in the array. fromIndex Optional The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. ...
...d. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the provided index is 0, then the whole array will be searched. Default: 0 (entire array is searched). Return value The first index of the element in the array; -1 if not found. Description indexOf
() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator). Note: For the String method, see String.prototype.indexOf
(). Polyfill indexOf
() was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all browsers. You can work around this by utilizing the following code at the beginning of you...
...ray using strict equality (the same method used by the === or triple-equals operator). Note: For the String method, see String.prototype.indexOf
(). Polyfill indexOf
() was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all browsers. You can work around this by utilizing the following code at the beginning of your scripts. This will allow you to use indexOf
() when there is still no native support. This algorithm matches the one specified in ECMA-262, 5th edition, assuming TypeError and Math.abs
() have their original values. // This version tries to optimize by only checking for "in" when looking for undefined and // skipping the definitely fruitless NaN search. Other parts are merely cosmetic conciseness. // Whether it is actually faster remains to b...
...of calling the Get // internal method of o with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in o && o[k] === searchElement) return k; } return -1; }; } Examples Using indexOf
() The following example uses indexOf
() to locate values in an array. var array = [2, 9, 9]; array.indexOf(2); // 0 array.indexOf(7); // -1 array.indexOf(9, 2); // 2 array.indexOf(2, -1); // -1 array.indexOf(2, -3); // 0 Finding all the occurrences of an element var indices = []; var array = ['a', 'b', 'a', 'c', 'a', 'd']; var element = 'a'; var idx = array.indexOf(element); while (idx...
Array.prototype.map() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax let new_array = arr.map(function callback( currentValue[, index[, array]]) { // return element for new_array }[, thisArg]) Parameters callback Function that is called for every element of arr. Each time callback executes, the returned value is added to new_array. The callback function accepts the following arguments: currentValue The current element being processed in the array. ...
...d callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values (including undefined). It is not called for missing elements of the array; that is: indexes that have never been set; which have been deleted; or which have never been assigned a value. When not to use map
() Since map builds a new array, using it when you aren't using the returned array is an anti-pattern; use forEach or for-of instead. You shouldn't be using map if: you're not using the array it returns; and/or you're not returning a value from the callback. Parameters in Detail callback is invoked with three arguments: the value of the element, the index of the element, and the array objec...
...collection of objects collected by querySelectorAll. This is because querySelectorAll returns a NodeList (which is a collection of objects). In this case, we return all the selected options' values on the screen: let elems = document.querySelectorAll('select option:checked') let values = Array.prototype.map.call(elems, function(obj) { return obj.value }) An easier way would be the Array.from
() method. Tricky use case (inspired by this blog post) It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors. Consider: ["1", "2", "3"].map(parseInt) While one might expect [1, 2, 3], the actual result is [1, ...
...tion returnInt(element) { return parseInt(element, 10) } ['1', '2', '3'].map(returnInt); // [1, 2, 3] // Actual result is an array of numbers (as expected) // Same as above, but using the concise arrow function syntax ['1', '2', '3'].map( str => parseInt(str) ) // A simpler way to achieve the above, while avoiding the "gotcha": ['1', '2', '3'].map(Number) // [1, 2, 3] // But unlike parseInt
(), Number
() will also return a float or (resolved) exponential notation: ['1.1', '2.2e2', '3e300'].map(Number) // [1.1, 220, 3e+300] // For comparison, if we use parseInt
() on the array above: ['1.1', '2.2e2', '3e300'].map( str => parseInt(str) ) // [1, 2, 3] One alternative output of the map method being called with parseInt as a parameter runs as follows: let xs = ['10', '10', '10'] xs = xs...
BigInt.prototype.toString() - JavaScript
The toString
() method returns a string representing the specified BigInt object. The trailing "n" is not part of the string. 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 bigIntObj.toString([radix]) Parameters radixOptional Optional. An integer in the range 2 through 36 specifying the base to use for representing numeric values. Return value A string representing the specified BigInt object. Exceptions RangeError If toString
() is given a radix less than 2 or greater than 36, a RangeError is thrown. ...
...igIntObj.toString([radix]) Parameters radixOptional Optional. An integer in the range 2 through 36 specifying the base to use for representing numeric values. Return value A string representing the specified BigInt object. Exceptions RangeError If toString
() is given a radix less than 2 or greater than 36, a RangeError is thrown. Description The BigInt object overrides the toString
() method of the Object object; it does not inherit Object.prototype.toString
(). For BigInt objects, the toString
() method returns a string representation of the object in the specified radix. The toString
() method parses its first argument, and attempts to return a string representation in the specified radix (base). For radixes above 10, the letters of the alphabet indicate numerals greater than ...
... hexadecimal numbers (base 16) a through f are used. If the radix is not specified, the preferred radix is assumed to be 10. If the bigIntObj is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the bigIntObj preceded by a - sign, not the two's complement of the bigIntObj. ...
...igIntObj. Examples Using toString 17n.toString
(); // '17' 66n.toString(2); // '1000010' 254n.toString(16); // 'fe' -10n.toString(2); // -1010' -0xffn.toString(2); // '-11111111' Negative-zero BigInt There is no negative-zero BigInt as there are no negative zeros in integers. -0.0 is an IEEE floating-point concept that only appears in the JavaScript Number type. (-0n).toString
(); // '0' BigInt(-0).toString
(); // '0' Specifications Specification ECMAScript (ECMA-262)The definition of 'BigInt.prototype.toString
()' in that specification. ...
BigInt64Array() constructor - JavaScript
The BigInt64Array
() typed array constructor creates a new BigInt64Array object, which is, an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0n. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). Syntax new BigInt64Array
(); new BigInt64Array(length); new BigInt64Array(typedArray); new BigInt64Array(object); new BigInt64Array(buffer [, byteOffset [, length]]); Parameters length When called with a length argument, an internal array buffer is created in memory, of size length multiplied by BYTES_PER_ELEMENT bytes, containing zeros. typedArray When called with a typedArray ar...
...array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the typedArray argument. object When called with an object argument, a new typed array is created as if by the TypedArray.from
() method. buffer, byteOffset, length When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified ArrayBuffer. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is view...
... ...
... ...
BigUint64Array() constructor - JavaScript
The BigUint64Array
() typed array constructor creates a new BigUint64Array object, which is, an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0n. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). Syntax new BigUint64Array
(); new BigUint64Array(length); new BigUint64Array(typedArray); new BigUint64Array(object); new BigUint64Array(buffer [, byteOffset [, length]]); Parameters length When called with a length argument, an internal array buffer is created in memory, of size length multiplied by BYTES_PER_ELEMENT bytes, containing zeros. typedArray When called with a type...
...array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the typedArray argument. object When called with an object argument, a new typed array is created as if by the TypedArray.from
() method. buffer, byteOffset, length When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified ArrayBuffer. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is view...
... ...
... ...
Date.prototype.getDay() - JavaScript
December 25, 1995, is a Monday. ...
...December 25, 1995, is a Monday. ...
...he day of the week for the specified date according to local time, where 0 represents Sunday. For the day of the month, see Date.prototype.getDate
(). 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 dateObj.getDay
() Return value An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Examples Using getDay
() The second statement below assigns the value 1 to weekday, based on the value of the Date object Xmas95. December 25, 1995, is a Monday. var Xmas95 = new Date('December 25, 1995 23:15:...
..., between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Examples Using getDay
() The second statement below assigns the value 1 to weekday, based on the value of the Date object Xmas95. December 25, 1995, is a Monday. var Xmas95 = new Date('December 25, 1995 23:15:30'); var weekday = Xmas95.getDay
(); console.log(weekday); // 1 Note: If needed, the full name of a day ("Monday" for example) can be obtained by using Intl.DateTimeFormat with an options parameter. Using this method, the internationalization is made easier: var options = { weekday: 'long'}; console.log(new Intl.DateTimeFormat('en-US', options).format(Xmas95)); // Monday console.log(new Intl.DateTimeFormat('de-DE', options).fo...
Date.prototype.setSeconds() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dateObj.setSeconds(secondsValue[, msValue]) Versions prior to JavaScript 1.3 dateObj.setSeconds(secondsValue) Parameters secondsValue An integer between 0 and 59, representing the seconds. msValue Optional. A number between 0 and 999, representing the milliseconds. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ...
... dateObj.setSeconds(secondsValue) Parameters secondsValue An integer between 0 and 59, representing the seconds. msValue Optional. A number between 0 and 999, representing the milliseconds. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ...
... representing the seconds. msValue Optional. A number between 0 and 999, representing the milliseconds. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If you do not specify the msValue parameter, the value returned from the getMilliseconds
() method is used. If a parameter you specify is outside of the expected range, setSeconds
() attempts to update the date information in the Date object accordingly. ...
...e msValue parameter, the value returned from the getMilliseconds
() method is used. If a parameter you specify is outside of the expected range, setSeconds
() attempts to update the date information in the Date object accordingly. For example, if you use 100 for secondsValue, the minutes stored in the Date object will be incremented by 1, and 40 will be used for seconds. Examples Using setSeconds
() var theBigDay = new Date
(); theBigDay.setSeconds(30); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.setSeconds' in that specification. ...
Date.prototype.toDateString() - JavaScript
The toDateString
() method returns the date portion of a Date object in English in the following format separated by spaces: First three letters of the week day name First three letters of the month name Two digit day of the month, padded on the left a zero if necessary Four digit year (at least), padded on the left with zeros if necessary E.g. "Thu Jan 01 1970". 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 dateObj.toDateString
() Return value A string representing the date portion of the given Date object in human readable form in English. Description Date instances refer to a specific point ...
...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 dateObj.toDateString
() Return value A string representing the date portion of the given Date object in human readable form in English. Description Date instances refer to a specific point in time. Calling toString
() will return the date formatted in a human readable form in English. ...
...te instances refer to a specific point in time. Calling toString
() will return the date formatted in a human readable form in English. In SpiderMonkey, this consists of the date portion (day, month, and year) followed by the time portion (hours, minutes, seconds, and time zone). Sometimes it is desirable to obtain a string of the time portion; such a thing can be accomplished with the toTimeString
() method. The toDateString
() method is especially useful because compliant engines implementing ECMA-262 may differ in the string obtained from toString
() for Date objects, as the format is implementation-dependent and simple string slicing approaches may not produce consistent results across multiple engines. ...
...hing can be accomplished with the toTimeString
() method. The toDateString
() method is especially useful because compliant engines implementing ECMA-262 may differ in the string obtained from toString
() for Date objects, as the format is implementation-dependent and simple string slicing approaches may not produce consistent results across multiple engines. Examples A basic usage of toDateString
() var d = new Date(1993, 5, 28, 14, 39, 7); console.log(d.toString
()); // logs Mon Jun 28 1993 14:39:07 GMT-0600 (PDT) console.log(d.toDateString
()); // logs Mon Jun 28 1993 Note: Month are 0-indexed when used as an argument of Date (thus 0 corresponds to January and 11 to December). Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.to...
Generator.prototype.throw() - JavaScript
The throw
() method resumes the execution of a generator by throwing an error into it and returns an object with two properties done and value. Syntax gen.throw(exception) Parameters exception The exception to throw. For debugging purposes, it is useful to make it an instanceof Error. Return value An Object with two properties: done (boolean) Has the value true if the iterator is past the end of the iterated sequence. In this case value optionally specifies the return value of the iterator. Has the value false if the iterator was able to produce the next value in the sequence. This is equivalent of not specifying the done property altogether. value Any JavaScript value returned by the iterator. Can be omitted when done is true. ...
...e iterator is past the end of the iterated sequence. In this case value optionally specifies the return value of the iterator. Has the value false if the iterator was able to produce the next value in the sequence. This is equivalent of not specifying the done property altogether. value Any JavaScript value returned by the iterator. Can be omitted when done is true. ...
... to produce the next value in the sequence. This is equivalent of not specifying the done property altogether. value Any JavaScript value returned by the iterator. Can be omitted when done is true. Examples Using throw
() The following example shows a simple generator and an error that is thrown using the throw method. An error can be caught by a try...catch block as usual. ...
...JavaScript value returned by the iterator. Can be omitted when done is true. Examples Using throw
() The following example shows a simple generator and an error that is thrown using the throw method. An error can be caught by a try...catch block as usual. function* gen
() { while(true) { try { yield 42; } catch(e) { console.log('Error caught!'); } } } const g = gen
(); g.next
(); // { value: 42, done: false } g.throw(new Error('Something went wrong')); // "Error caught!" // { value: 42, done: false } Specifications Specification ECMAScript (ECMA-262)The definition of 'Generator.prototype.throw' in that specification. ...
Int16Array() constructor - JavaScript
The Int16Array
() typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). Syntax new Int16Array
(); // new in ES2017 new Int16Array(length); new Int16Array(typedArray); new Int16Array(object); new Int16Array(buffer [, byteOffset [, length]]); Parameters length When called with a length argument, an internal array buffer is created in memory, of size length multiplied by BYTES_PER_ELEMENT bytes, containing zeros. typedArray When called with a typedArray argument, which can be an obj...
...array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the typedArray argument. object When called with an object argument, a new typed array is created as if by the TypedArray.from
() method. buffer, byteOffset, length When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified ArrayBuffer. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is vie...
... ...
... ...
Int32Array() constructor - JavaScript
The Int32Array
() typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). Syntax new Int32Array
(); // new in ES2017 new Int32Array(length); new Int32Array(typedArray); new Int32Array(object); new Int32Array(buffer [, byteOffset [, length]]); Parameters length When called with a length argument, an internal array buffer is created in memory, of size length multiplied by BYTES_PER_ELEMENT bytes, containing zeros. typedArray When called with a typedArray argument, which can be an obj...
...array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the typedArray argument. object When called with an object argument, a new typed array is created as if by the TypedArray.from
() method. buffer, byteOffset, length When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified ArrayBuffer. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is vie...
... ...
... ...
Int8Array() constructor - JavaScript
The Int8Array
() constructor creates a typed array of twos-complement 8-bit signed integers. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). Syntax new Int8Array
(); // new in ES2017 new Int8Array(length); new Int8Array(typedArray); new Int8Array(object); new Int8Array(buffer [, byteOffset [, length]]); Parameters length When called with a length argument, an internal array buffer is created in memory, of size length multiplied by BYTES_PER_ELEMENT bytes, containing zeros. typedArray When called with a typedArray argument, which can be an object of any of the typed array types (such as Int32Array), the typedArray gets copied into a new typed...
...array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the typedArray argument. object When called with an object argument, a new typed array is created as if by the TypedArray.from
() method. buffer, byteOffset, length When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified ArrayBuffer. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is vie...
... ...
... ...
Intl.DateTimeFormat() constructor - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax new Intl.DateTimeFormat([locales[, options]]) Parameters locales Optional A string with a BCP 47 language tag, or an array of such strings. To use the browser's default locale, omit this argument or pass undefined. Unicode extension are supported (for example "en-US-u-ca-buddhist"). For the general form and interpretation of the locales argument, see the Intl page. ...
... Calendar. Possible values include: "buddhist", "chinese", "coptic", "ethiopia", "ethiopic", "gregory", "hebrew", "indian", "islamic", "iso8601", "japanese", "persian", "roc". hc Hour cycle. Possible values include: "h11", "h12", "h23", "h24". options Optional An object with some or all of the following properties: dateStyle The date formatting style to use when calling format
(). Possible values include: "full" "long" "medium" "short" timeStyle The time formatting style to use when calling format
(). Possible values include: "full" "long" "medium" "short" fractionalSecondDigits The number of fractional seconds to apply when calling format
(). Valid values are 0-3. calendar Calendar. Possible values include: "buddhist", ...
...then year, month, and day are assumed to be "numeric". Examples Using DateTimeFormat In basic use without specifying a locale, DateTimeFormat uses the default locale and default options. ...
...); // toLocaleString without arguments depends on the implementation, // the default locale, and the default time zone console.log(new Intl.DateTimeFormat
().format(date)); // -> "12/19/2012" if run with en-US locale (language) and time zone America/Los_Angeles (UTC-0800) Using timeStyle and dateStyle let o = new Intl.DateTimeFormat("en" , { timeStyle: "short" }); console.log(o.format(Date.now
())); // "13:31 AM" let o = new Intl.DateTimeFormat("en" , { dateStyle: "short" }); console.log(o.format(Date.now
())); // "07/07/20" let o = new Intl.DateTimeFormat("en" , { timeStyle: "medium", dateStyle: "short" }); console.log(o.format(Date.now
())); // "07/07/20, 13:31:55 AM" Specifications Specification ECMAScript Internationalization API (ECMA-402)The definition ...
Intl.DateTimeFormat.prototype.format() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dateTimeFormat.format(date) Parameters date The date to format. Description The format getter formats a date into a string according to the locale and formatting options of this Intl.DateTimeFormat object. ...
...ts a date into a string according to the locale and formatting options of this Intl.DateTimeFormat object. Examples Using format Use the format getter function for formatting a single date, here for Serbia: var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var dateTimeFormat = new Intl.DateTimeFormat('sr-RS', options); console.log(dateTimeFormat.format(new Date
())); // -> "??????, 7. ????? 2013." Using format with map Use the format getter function for formatting all dates in an array. Note that the function is bound to the Intl.DateTimeFormat from which it was obtained, so it can be passed directly to Array.prototype.map
(). var a = [new Date(2012, 08), new Date(2012, 11), new Date(2012, 03)]; var options = { year: 'numeric', month: 'long' }; var date...
...However, this might change in the future and isn't guaranteed for all the languages -- output variations are by design and allowed by the specification. Most notably, the IE and Edge browsers insert bidirectional control characters around dates, so the output text will flow properly when concatenated with other text. For this reason you cannot expect to be able to compare the resu...
...t. However, this might change in the future and isn't guaranteed for all the languages -- output variations are by design and allowed by the specification. Most notably, the IE and Edge browsers insert bidirectional control characters around dates, so the output text will flow properly when concatenated with other text. ...
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
The Intl.DateTimeFormat.prototype.formatToParts
() method allows locale-aware formatting of strings produced by DateTimeFormat formatters. Syntax dateTimeFormat.formatToParts(date) Parameters date Optional The date to format. Return value An Array of objects containing the formatted date in parts. Description The formatToParts
() method is useful for custom formatting of date strings. It returns an Array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. The structure the formatToParts
() method returns, looks like this: [ { type: 'day', value: '17' }, { type: 'weekday', value: 'Monday' } ] Possible types are the following: day The string used for the day, for example "17". dayPeriod...
...minute', value: '00' }, { type: 'literal', value: ':' }, { type: 'second', value: '42' }, { type: 'fractionalSecond', value: '000' }, { type: 'literal', value: ' ' }, { type: 'dayPeriod', value: 'AM' } ] Now the information is available separately and it can be formatted and concatenated again in a customized way. For example by using Array.prototype.map
(), arrow functions, a switch statement, template literals, and Array.prototype.reduce
(). var dateString = formatter.formatToParts(date).map(({type, value}) => { switch (type) { case 'dayPeriod': return `<b>${value}</b>`; default : return value; } }).reduce((string, part) => string + part); This will make the day period bold, when using the formatToParts
() method. console.log(formatt...
...42.000 AM" console.log(dateString); // "Monday, 12/17/2012, 3:00:42.000 <b>AM</b>" Named Years and Mixed calendars In some cases, calendars use named years. Chinese and Tibetan calendars, for example, use a 60-year sexagenary cycle of named years. These years are disambiguated by relationship to corresponding years on the Gregorian calendar. When this is the case, the result of formatToParts
() will contain an entry for relatedYear when a year would normally be present, containing the 4-digit Gregorian year, instead of an entry for year. Setting an entry in the bag for year (with any value) will yield both the and the yearName Gregorian relatedYear: let opts = { year: "numeric", month: "numeric", day: "numeric" }; let df = new Intl.DateTimeFormat("zh-u-ca-chinese", opts); df.formatTo...
... This also makes it possible to mix locale and calendar in both format: let df = new Intl.DateTimeFormat("en-u-ca-chinese", {year: "numeric"}); let date = Date.UTC(2012, 11, 17, 3, 0, 42); df.format(date); /...
Intl​.ListFormat.prototype​.format() - JavaScript
Examples Using format The following example shows how to create a List formatter using the English language. ...
... Examples Using format The following example shows how to create a List formatter using the English language. ...
... the list. Syntax listFormat.format([list]); Parameters list An iterable object, such as an Array Return value A language-specific formatted string representing the elements of the list Description The format
() method returns a string that has been formatted based on parameters provided in the Intl.ListFormat object. The locales and options parameters customize the behavior of format
() and let applications specify the language conventions that should be used to format the list. Examples Using format The following example shows how to create a List formatter using the English language. const list = ['Motorcycle', 'Bus', 'Car']; console.log(new Intl.ListFormat('en-GB', { style: 'long', type: 'conjunction' }).format(list)); // > Motorcycle, Bus and Car console.log(new Intl...
... ...
Intl​.List​Format​.prototype​.resolvedOptions() - JavaScript
If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. ...
...If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. ...
...hod returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current ListFormat object. Syntax listFormat.resolvedOptions
() Return value An object with properties reflecting the locale and formatting options computed during the construction of the given ListFormat object. Description The object returned by resolvedOptions
() has the following properties: locale The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. style The value provided for this property in the options argument of the constructor or the defaul...
...value ("long"). Its value is either "long", "short", or "narrow". type The value provided for this property in the options argument of the constructor or the default value ("conjunction"). Its value is either "conjunction", "disjunction", or "unit". Examples Using resolvedOptions const deListFormatter = new Intl.ListFormat("de-DE", { style: "short" }); const usedOptions = de.resolvedOptions
(); console.log(usedOptions.locale); // "de-DE" console.log(usedOptions.style); // "short" console.log(usedOptions.type); // "conjunction" (the default value) Specifications Specification Intl.ListFormatThe definition of 'resolvedOptions
()' in that specification. ...
Intl.Locale.prototype.minimize() - JavaScript
The Intl.Locale.prototype.minimize
() method attempts to remove information about the locale that would be added by calling Locale.maximize
(). 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 locale.minimize
() Return value A Locale instance whose baseName property returns the result of the Remove Likely Subtags algorithm executed against locale.baseName. Description This method carries out the reverse of maximize
(), removing any language, script, or region subtags from the locale language identifier (essentially the contents of baseName). This is useful when there are superfluous subtags in the language...
...locale.baseName. Description This method carries out the reverse of maximize
(), removing any language, script, or region subtags from the locale language identifier (essentially the contents of baseName). This is useful when there are superfluous subtags in the language identifier; for instance, "en-Latn" can be simplified to "en", since "Latn" is the only script used to write English. minimize
() only affects the main subtags that comprise the language identifier: language, script, and region subtags. Other subtags after the "-u" in the locale indentifier are called extension subtags and are not affected by the minimize
() method. Examples of these subtags include Locale.hourCycle, Locale.calendar, and Locale.numeric. Examples Using minimize let myLocale = new Intl.Locale("fr-Latn-FR", ...
...r the "-u" in the locale indentifier are called extension subtags and are not affected by the minimize
() method. Examples of these subtags include Locale.hourCycle, Locale.calendar, and Locale.numeric. Examples Using minimize let myLocale = new Intl.Locale("fr-Latn-FR", {hourCycle: "h24", calendar: "gregory"}); console.log(myLocale.baseName); // Prints "fr-Latn-FR" console.log(myLocale.toString
()); // Prints "fr-Latn-FR-u-ca-gregory-hc-h24" let myLocMinimized = myLocale.minimize
(); // Prints "fr", since French is only written in the Latin script // and is most likely to be spoken in France. console.log(myLocMinimized.baseName); // Prints "fr-u-ca-gregory-hc-h24". ...
...le.log(myLocale.toString
()); // Prints "fr-Latn-FR-u-ca-gregory-hc-h24" let myLocMinimized = myLocale.minimize
(); // Prints "fr", since French is only written in the Latin script // and is most likely to be spoken in France. console.log(myLocMinimized.baseName); // Prints "fr-u-ca-gregory-hc-h24". // Note that the extension tags (after "-u") remain unchanged. ...
JSON.parse() - JavaScript
An optional reviver function can be provided to perform a transformation on the resulting object before it is returned. 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 JSON.parse(text[, reviver]) Parameters text The string to parse as JSON. See the JSON object for a description of JSON syntax. reviver Optional If a function, this prescribes how the value originally produced by parsing is transformed, before being returned. ...
...us.test(text)) { text = text.replace(rx_dangerous, function(a) { return ( "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4) ); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with "
()" and "new" // because they can cause invocation, and "=" because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with "@" (a non-JS...
... // each name/value pair to a reviver function for possible transformation. return (typeof reviver === "function") ? walk({ "": j }, "") : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError("JSON.parse"); }; } Examples Using JSON.parse
() JSON.parse('{}'); // {} JSON.parse('true'); // true JSON.parse('"foo"'); // "foo" JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] JSON.parse('null'); // null Using the reviver parameter If a reviver is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value and all its properties (beginning ...
... value === 'number' ? value * 2 // return value * 2 for numbers : value // return everything else unchanged ); // { p: 10 } JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => { console.log(key); // log the current property name, the last is "". return value; // return the unchanged property value. }); // 1 // 2 // 4 // 6 // 5 // 3 // "" JSON.parse
() does not allow trailing commas // both will throw a SyntaxError JSON.parse('[1, 2, 3, 4, ]'); JSON.parse('{"foo" : 1, }'); JSON.parse
() does not allow single quotes // will throw a SyntaxError JSON.parse("{'foo': 1}"); Specifications Specification ECMAScript (ECMA-262)The definition of 'JSON.parse' in that specification. ...
Math.acos() - JavaScript
The Math.acos
() function returns the arccosine (in radians) of a number, that is ?x?[-1;1],Math.acos(x)=arccos(x)= the unique y?[0;?]such thatcos(y)=x\forall x \in [{-1};1],\;\mathtt{\operatorname{Math.acos}(x)} = \arccos(x) = \text{ the unique } \; y \in [0; \pi] \, \text{such that} \; \cos(y) = x The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.acos(x) Parameters x A number representing a cosine, where x is between -1 and 1. Return value The arccosine (angle in radians) of the given number if it's between -1 and 1; otherwise, NaN. ...
...epository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.acos(x) Parameters x A number representing a cosine, where x is between -1 and 1. Return value The arccosine (angle in radians) of the given number if it's between -1 and 1; otherwise, NaN. ...
...request. Syntax Math.acos(x) Parameters x A number representing a cosine, where x is between -1 and 1. Return value The arccosine (angle in radians) of the given number if it's between -1 and 1; otherwise, NaN. Description The Math.acos
() method returns a numeric value between 0 and ? ...
...resenting a cosine, where x is between -1 and 1. Return value The arccosine (angle in radians) of the given number if it's between -1 and 1; otherwise, NaN. Description The Math.acos
() method returns a numeric value between 0 and ? radians for x between -1 and 1. If the value of x is outside this range, it returns NaN. Because acos
() is a static method of Math, you always use it as Math.acos
(), rather than as a method of a Math object you created (Math is not a constructor). Examples Using Math.acos
() Math.acos(-2); // NaN Math.acos(-1); // 3.141592653589793 Math.acos(0); // 1.5707963267948966 Math.acos(0.5); // 1.0471975511965979 Math.acos(1); // 0 Math.acos(2); // NaN For values less than -1 or greater than 1, Math.acos
() returns NaN. Specifications Specificat...
Math.asin() - JavaScript
The Math.asin
() function returns the arcsine (in radians) of a number, that is ?x?[-1;1],Math.asin(x)=arcsin(x)= the unique y?[-?2;?2]such thatsin(y)=x\forall x \in [{-1};1],\;\mathtt{\operatorname{Math.asin}(x)} = \arcsin(x) = \text{ the unique } \; y \in \left[-\frac{\pi}{2}; \frac{\pi}{2}\right] \, \text{such that} \; \sin(y) = x The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.asin(x) Parameters x A number. Return value The arcsine (in radians) of the given number if it's between -1 and 1; otherwise, NaN. ...
...source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.asin(x) Parameters x A number. Return value The arcsine (in radians) of the given number if it's between -1 and 1; otherwise, NaN. ...
...-examples and send us a pull request. Syntax Math.asin(x) Parameters x A number. Return value The arcsine (in radians) of the given number if it's between -1 and 1; otherwise, NaN. Description The Math.asin
() method returns a numeric value between -?2-\frac{\pi}{2} and ?2\frac{\pi}{2} radians for x between -1 and 1. If the value of x is outside this range, it returns NaN. Because asin
() is a static method of Math, you always use it as Math.asin
(), rather than as a method of a Math object you created (Math is not a constructor). ...
...; otherwise, NaN. Description The Math.asin
() method returns a numeric value between -?2-\frac{\pi}{2} and ?2\frac{\pi}{2} radians for x between -1 and 1. If the value of x is outside this range, it returns NaN. Because asin
() is a static method of Math, you always use it as Math.asin
(), rather than as a method of a Math object you created (Math is not a constructor). Examples Using Math.asin
() Math.asin(-2); // NaN Math.asin(-1); // -1.5707963267948966 (-pi/2) Math.asin(0); // 0 Math.asin(0.5); // 0.5235987755982989 Math.asin(1); // 1.5707963267948966 (pi/2) Math.asin(2); // NaN For values less than -1 or greater than 1, Math.asin
() returns NaN. Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.asin' in that specification. ...
Math.floor() - JavaScript
The Math.floor
() function returns the largest integer less than or equal to a given number. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.floor(x) Parameters x A number. Return value A number representing the largest integer less than or equal to the specified number. Description Because floor
() is a static method of Math, you always use it as Math.floor
(), rather than as a method of a Math object you created (Math is not a constructor). Note: Math.floor(null) returns 0, not a NaN. ...
...ntax Math.floor(x) Parameters x A number. Return value A number representing the largest integer less than or equal to the specified number. Description Because floor
() is a static method of Math, you always use it as Math.floor
(), rather than as a method of a Math object you created (Math is not a constructor). Note: Math.floor(null) returns 0, not a NaN. Examples Using Math.floor
() Math.floor( 45.95); // 45 Math.floor( 45.05); // 45 Math.floor( 4 ); // 4 Math.floor(-45.05); // -46 Math.floor(-45.95); // -46 Decimal adjustment /** * Decimal adjustment of a number. * * @param {String} type The type of adjustment. * @param {Number} value The number. * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). * @returns {Number} The adju...
...value. */ function decimalAdjust(type, value, exp) { // If the exp is undefined or zero... if (typeof exp === 'undefined' || +exp === 0) { return Math[type](value); } value = +value; exp = +exp; // If the value is not a number or the exp is not an integer... ...
...== 0) { return Math[type](value); } value = +value; exp = +exp; // If the value is not a number or the exp is not an integer... ...
Math.log10() - JavaScript
The Math.log10
() function returns the base 10 logarithm of a number, that is ?x>0,Math.log10(x)=log10(x)=the uniqueysuch that10y=x\forall x > 0, \mathtt{\operatorname{Math.log10}(x)} = \log_10(x) = \text{the unique} \; y \; \text{such that} \; 10^y = x The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.log10(x) Parameters x A number. Return value The base 10 logarithm of the given number. If the number is negative, NaN is returned. Description If the value of x is less than 0, the return value is always NaN. ...
.... If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.log10(x) Parameters x A number. Return value The base 10 logarithm of the given number. If the number is negative, NaN is returned. Description If the value of x is less than 0, the return value is always NaN. ...
...ect, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.log10(x) Parameters x A number. Return value The base 10 logarithm of the given number. If the number is negative, NaN is returned. Description If the value of x is less than 0, the return value is always NaN. ...
...escription If the value of x is less than 0, the return value is always NaN. Because log10
() is a static method of Math, you always use it as Math.log10
(), rather than as a method of a Math object you created (Math is not a constructor). This function is the equivalent of Math.log(x) / Math.log(10). For log10(e) use the constant Math.LOG10E which is 1 / Math.LN10. ...
Math.log2() - JavaScript
The Math.log2
() function returns the base 2 logarithm of a number, that is ?x>0,Math.log2(x)=log2(x)=the uniqueysuch that2y=x\forall x > 0, \mathtt{\operatorname{Math.log2}(x)} = \log_2(x) = \text{the unique} \; y \; \text{such that} \; 2^y = x The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.log2(x) Parameters x A number. Return value The base 2 logarithm of the given number. If the number is negative, NaN is returned. Description If the value of x is less than 0, the return value is always NaN. ...
...ory. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.log2(x) Parameters x A number. Return value The base 2 logarithm of the given number. If the number is negative, NaN is returned. Description If the value of x is less than 0, the return value is always NaN. Because log2
() is a static method of Math, you always use it as Math.log2
(), rather than as a method of a Math object you created (Math is not a constructor). This function is the equivalent of Math.log(x) / Math.log(2). For log2(e) use the constant Math.LOG2E which is 1 / Math.LN2. Polyfill This Polyfill emulates the Math.log2 function. Note that it returns imprecise values on some inputs (like 1 << 29),...
...f Math, you always use it as Math.log2
(), rather than as a method of a Math object you created (Math is not a constructor). This function is the equivalent of Math.log(x) / Math.log(2). For log2(e) use the constant Math.LOG2E which is 1 / Math.LN2. Polyfill This Polyfill emulates the Math.log2 function. Note that it returns imprecise values on some inputs (like 1 << 29), wrap into Math.round
() if working with bit masks. ...
... is the equivalent of Math.log(x) / Math.log(2). For log2(e) use the constant Math.LOG2E which is 1 / Math.LN2. Polyfill This Polyfill emulates the Math.log2 function. Note that it returns imprecise values on some inputs (like 1 << 29), wrap into Math.round
() if working with bit masks. if (!Math.log2) Math.log2 = function(x) { return Math.log(x) * Math.LOG2E; }; Examples Using Math.log2
() Math.log2(3); // 1.584962500721156 Math.log2(2); // 1 Math.log2(1); // 0 Math.log2(0); // -Infinity Math.log2(-2); // NaN Math.log2(1024); // 10 Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.log2' in that specification. ...
Math.sign() - JavaScript
Note that if the number is positive, an explicit (+) will not be returned. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.sign(x) Parameters x A number. If this argument is not a number, it is implicitly converted to one. Return value A number representing the sign of the given argument: If the argument is positive, returns 1. If the argument is negative, returns -1. ...
...Parameters x A number. If this argument is not a number, it is implicitly converted to one. Return value A number representing the sign of the given argument: If the argument is positive, returns 1. If the argument is negative, returns -1. If the argument is positive zero, returns 0. If the argument is negative zero, returns -0. Otherwise, NaN is returned. Description Because sign
() is a static method of Math, you always use it as Math.sign
(), rather than as a method of a Math object you created (Math is not a constructor). Polyfill if (!Math.sign) { Math.sign = function(x) { // If x is NaN, the result is NaN. // If x is -0, the result is -0. // If x is +0, the result is +0. // If x is negative and not -0, the result is -1. // If x is positive and no...
... ...
...}; } In the above polyfill, no extra type-coercing is needed to make (x > 0) or (x < 0) numbers because subtracting them from each other forces a type conversion from booleans to numbers. Examples Using Math.sign
() Math.sign(3); // 1 Math.sign(-3); // -1 Math.sign('-3'); // -1 Math.sign(0); // 0 Math.sign(-0); // -0 Math.sign(NaN); // NaN Math.sign('foo'); // NaN Math.sign
(); // NaN Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.sign' in that specification. ...
Math.trunc() - JavaScript
The Math.trunc
() function returns the integer part of a number by removing any fractional digits. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.trunc(x) Parameters x A number. Return value The integer part of the given number. Description Unlike the other three Math methods: Math.floor
(), Math.ceil
() and Math.round
(), the way Math.trunc
() works is very simple. It truncates (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. The argument passed to this method will be converted to number type implicitly. ...
... integer part of the given number. Description Unlike the other three Math methods: Math.floor
(), Math.ceil
() and Math.round
(), the way Math.trunc
() works is very simple. It truncates (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. The argument passed to this method will be converted to number type implicitly. Because trunc
() is a static method of Math, you always use it as Math.trunc
(), rather than as a method of a Math object you created (Math is not a constructor). Polyfill if (!Math.trunc) { Math.trunc = function(v) { v = +v; if (!isFinite(v)) return v; return (v - v % 1) || (v < 0 ? -0 : v === 0 ? v : 0); // returns: // 0 -> 0 // -0 -> -0 // 0.2 -> 0 // -0.2 ...
... ...
... ...
Number.prototype.toFixed() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax numObj.toFixed([digits]) Parameters digits Optional The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0. Return value A string representing the given number using fixed-point notation. Exceptions RangeError If digits is too small or too large. ...
...s treated as 0. Return value A string representing the given number using fixed-point notation. Exceptions RangeError If digits is too small or too large. Values between 0 and 100, inclusive, will not cause a RangeError. Implementations are allowed to support larger and smaller values as chosen. TypeError If this method is invoked on an object that is not a Number. ...
...scription toFixed
() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of numObj is greater or equal to 1e+21, this method simply calls Number.prototype.toString
() and returns a string in exponential notation. Warning: Floating point numbers cannot represent all decimals precisely in binary. This can lead to unexpected results, such as 0.1 + 0.2 === 0.3 returning false . ...
...ength. If the absolute value of numObj is greater or equal to 1e+21, this method simply calls Number.prototype.toString
() and returns a string in exponential notation. Warning: Floating point numbers cannot represent all decimals precisely in binary. This can lead to unexpected results, such as 0.1 + 0.2 === 0.3 returning false . Examples Using toFixed let numObj = 12345.6789 numObj.toFixed
() // Returns '12346': note rounding, no fractional part numObj.toFixed(1) // Returns '12345.7': note rounding numObj.toFixed(6) // Returns '12345.678900': note added zeros (1.23e+20).toFixed(2) // Returns '123000000000000000000.00' (1.23e-10).toFixed(2) // Returns '0.00' 2.34.toFixed(1) // Returns '2.3' 2.35.toFixed(1) // Returns '2.4'. Note it rounds up 2.55.toFixed...
Number.prototype.toPrecision() - JavaScript
If the precision argument is a non-integer value, it is rounded to the nearest integer. Exceptions RangeError If precision is not between 1 and 100 (inclusive), a RangeError is thrown. ...
...ting the Number object to the specified precision. Syntax numObj.toPrecision([precision]) Parameters precision Optional An integer specifying the number of significant digits. Return value A string representing a Number object in fixed-point or exponential notation rounded to precision significant digits. See the discussion of rounding in the description of the Number.prototype.toFixed
() method, which also applies to toPrecision
(). If the precision argument is omitted, behaves as Number.prototype.toString
(). If the precision argument is a non-integer value, it is rounded to the nearest integer. Exceptions RangeError If precision is not between 1 and 100 (inclusive), a RangeError is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 on...
...n argument is a non-integer value, it is rounded to the nearest integer. Exceptions RangeError If precision is not between 1 and 100 (inclusive), a RangeError is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits. ...
...er values as well. ECMA-262 only requires a precision of up to 21 significant digits. ...
Object.getOwnPropertyDescriptors() - JavaScript
The Object.getOwnPropertyDescriptors
() method returns all own property descriptors of a given object. Syntax Object.getOwnPropertyDescriptors(obj) Parameters obj The object for which to get all own property descriptors. Return value An object containing all own property descriptors of an object. Might be an empty object, if there are no properties. Description This method permits examination of the precise description of all own properties of an object. A property in JavaScript consists of either a string-valued name or a Symbol and a property descriptor. Further information about property descriptor types and their attributes can be found in Object.defineProperty
(). A property descriptor is a record with some of the following attributes: value The value associated with t...
... undefined if there is no setter (accessor descriptors only). configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. ...
...ged and if the property may be deleted from the corresponding object. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. Examples Creating a shallow clone Whereas the Object.assign
() method will only copy enumerable and own properties from a source object to a target object, you are able to use this method and Object.create
() for a shallow copy between two unknown objects: Object.create( Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj) ); Creating a subclass A typical way of creating a subclass is to define the subclass, set its prototype to an instance of the superclass, and then define properties on that instance. This can get awkward especially for getters and setters. Instead, you can use ...
...ject.create( Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj) ); Creating a subclass A typical way of creating a subclass is to define the subclass, set its prototype to an instance of the superclass, and then define properties on that instance. This can get awkward especially for getters and setters. Instead, you can use this code to set the prototype: function superclass
() {} superclass.prototype = { // Define your methods and properties here }; function subclass
() {} subclass.prototype = Object.create( superclass.prototype, { // Define your methods and properties here } ); Specifications Specification ECMAScript (ECMA-262)The definition of 'Object.getOwnPropertyDescriptors' in that specification. ...
Object.seal() - JavaScript
Values of present properties can still be changed as long as they are writable. 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 Object.seal(obj) Parameters obj The object which should be sealed. Return value The object being sealed. Description By default, objects are extensible (new properties can be added to them). Sealing an object prevents new properties from being added and marks all existing properties as non-configurable. ...
...es of data properties from being changed. Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a TypeError (most commonly, although not exclusively, when in strict mode code). The prototype chain remains untouched. However, the __proto__ property is sealed as well. Comparison to Object.freeze
() Existing properties in objects frozen with Object.freeze
() are made immutable. Objects sealed with Object.seal
() can have their existing properties changed. Examples Using Object.seal var obj = { prop: function
() {}, foo: 'bar' }; // New properties may be added, existing properties // may be changed or removed. obj.foo = 'baz'; obj.lumpy = 'woof'; delete obj.prop; var o = Object.seal(ob...
... added, existing properties // may be changed or removed. obj.foo = 'baz'; obj.lumpy = 'woof'; delete obj.prop; var o = Object.seal(obj); o === obj; // true Object.isSealed(obj); // === true // Changing property values on a sealed object // still works. obj.foo = 'quux'; // But you can't convert data properties to accessors, // or vice versa. ...
...o accessors, // or vice versa. Object.defineProperty(obj, 'foo', { get: function
() { return 'g'; } }); // throws a TypeError // Now any changes, other than to property values, // will fail. obj.quaxxor = 'the friendly duck'; // silently doesn't add the property delete obj.foo; // silently doesn't delete the property // ...and in strict mode such attempts // will throw TypeErrors. function fail
() { 'use strict'; delete obj.foo; // throws a TypeError obj.sparky = 'arf'; // throws a TypeError } fail
(); // Attempted additions through // Object.defineProperty will also throw. Object.defineProperty(obj, 'ohai', { value: 17 }); // throws a TypeError Object.defineProperty(obj, 'foo', { value: 'eit' }); // changes existing property value Non-object coercion In ES5, if the argument t...
Promise.allSettled() - JavaScript
Syntax Promise.allSettled(iterable); Parameters iterable An iterable object, such as an Array, in which each member is a Promise. ...
... promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise. It is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. In comparison, the Promise returned by Promise.all
() may be more appropriate if the tasks are dependent on each other / if you'd like to immediately reject upon any of them rejecting. Syntax Promise.allSettled(iterable); Parameters iterable An iterable object, such as an Array, in which each member is a Promise. Return value A pending Promise that will be asynchronously fulfilled once every promise in the specified collection of promise...
...will be asynchronously fulfilled once every promise in the specified collection of promises has completed, either by successfully being fulfilled or by being rejected. At that time, the returned promise's handler is passed as input an array containing the outcome of each promise in the original set of promises. However, if and only if an empty iterable is passed as an argument, Promise.allSettled
() returns a Promise object that has already been resolved as an empty array. For each outcome object, a status string is present. If the status is fulfilled, then a value is present. If the status is rejected, then a reason is present. The value (or reason) reflects what value each promise was fulfilled (or rejected) with. Examples Using Promise.allSettled Promise.allSettled([ Promise.resolve...
... been resolved as an empty array. For each outcome object, a status string is present. If the status is fulfilled, then a value is present. If the status is rejected, then a reason is present. The value (or reason) reflects what value each promise was fulfilled (or rejected) with. ...
Promise.prototype.finally() - JavaScript
The finally
() method returns a Promise. When the promise is settled, i.e either fulfilled or rejected, the specified callback function is executed. This provides a way for code to be run whether the promise was fulfilled successfully or rejected once the Promise has been dealt with. This helps to avoid duplicating code in both the promise's then
() and catch
() handlers. Syntax p.finally(onFinally); p.finally(function
() { // settled (fulfilled or rejected) }); Parameters onFinally A Function called when the Promise is settled. Return value Returns a Promise whose finally handler is set to the specified function, onFinally. Description The finally
() method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The f...
...finally(function
() { // settled (fulfilled or rejected) }); Parameters onFinally A Function called when the Promise is settled. Return value Returns a Promise whose finally handler is set to the specified function, onFinally. Description The finally
() method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The finally
() method is very similar to calling .then(onFinally, onFinally) however there are a couple of differences: When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it A finally callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected. This use case is...
...forced to either declare it twice, or create a variable for it A finally callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected. This use case is for precisely when you do not care about the rejection reason, or the fulfillment value, and so there's no need to provide it. So for example: Unlike Promise.resolve(2).then(
() => {},
() => {}) (which will be resolved with undefined), Promise.resolve(2).finally(
() => {}) will be resolved with 2. Similarly, unlike Promise.reject(3).then(
() => {},
() => {}) (which will be fulfilled with undefined), Promise.reject(3).finally(
() => {}) will be rejected with 3. Note: A throw (or returning a rejected promise) in the finally callback will reject the new promise with...
...ote: A throw (or returning a rejected promise) in the finally callback will reject the new promise with the rejection reason specified when calling throw. Examples Using finally let isLoading = true; fetch(myRequest).then(function(response) { var contentType = response.headers.get("content-type"); if(contentType && contentType.includes("application/json")) { return response.json
(); } throw new TypeError("Oops, we haven't got JSON!"); }) .then(function(json) { /* process your JSON further */ }) .catch(function(error) { console.error(error); /* this line can also throw, e.g. when console = {} */ }) .finally(function
() { isLoading = false; }); Please do not add polyfills on MDN pages. For more details, refer to: https://discourse.mozilla.org/t/mdn-rfc-001-...
handler.setPrototypeOf() - JavaScript
The handler.setPrototypeOf
() method is a trap for Object.setPrototypeOf
(). 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 p = new Proxy(target, { setPrototypeOf: function(target, prototype) { } }); Parameters The following parameters are passed to the setPrototypeOf
() method. this is bound to the handler. target The target object. prototype The object's new prototype or null. Return value The setPrototypeOf
() method returns true if the [[Prototype]] was successfully changed, otherwise false. Description The handler.setPrototypeOf
() method is a trap for Object.setPrototypeOf
(). Int...
...this is bound to the handler. target The target object. prototype The object's new prototype or null. Return value The setPrototypeOf
() method returns true if the [[Prototype]] was successfully changed, otherwise false. Description The handler.setPrototypeOf
() method is a trap for Object.setPrototypeOf
(). Interceptions This trap can intercept these operations: Object.setPrototypeOf
() Reflect.setPrototypeOf
() Invariants If the following invariants are violated, the proxy will throw a TypeError: If target is not extensible, the prototype parameter must be the same value as Object.getPrototypeOf(target). ...
... trap can intercept these operations: Object.setPrototypeOf
() Reflect.setPrototypeOf
() Invariants If the following invariants are violated, the proxy will throw a TypeError: If target is not extensible, the prototype parameter must be the same value as Object.getPrototypeOf(target). Examples If you want to disallow setting a new prototype for your object, your handler's setPrototypeOf
() method can either return false, or it can throw an exception. Approach 1: Returning false This approach means that any mutating operation that throws an exception on failure to mutate, must create the exception itself. For example, Object.setPrototypeOf
() will create and throw a TypeError itself. If the mutation is performed by an operation that doesn't ordinarily throw in case of failure, su...
...lse, or it can throw an exception. Approach 1: Returning false This approach means that any mutating operation that throws an exception on failure to mutate, must create the exception itself. For example, Object.setPrototypeOf
() will create and throw a TypeError itself. If the mutation is performed by an operation that doesn't ordinarily throw in case of failure, such as Reflect.setPrototypeOf
(), no exception will be thrown. const handlerReturnsFalse = { setPrototypeOf(target, newProto) { return false; } }; const newProto = {}, target = {}; const p1 = new Proxy(target, handlerReturnsFalse); Object.setPrototypeOf(p1, newProto); // throws a TypeError Reflect.setPrototypeOf(p1, newProto); // returns false Approach 2: Throwing an Exception The latter approach will cause...
Reflect.apply() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.apply(target, thisArgument, argumentsList) Parameters target The target function to call. thisArgument The value of this provided for the call to target. argumentsList An array-like object specifying the arguments with which target should be called. Return value The result of calling the given target function with the specified this value and arguments. Exceptions A TypeError, if the target is not callable. ...
.... thisArgument The value of this provided for the call to target. argumentsList An array-like object specifying the arguments with which target should be called. Return value The result of calling the given target function with the specified this value and arguments. Exceptions A TypeError, if the target is not callable. ...
...alling the given target function with the specified this value and arguments. Exceptions A TypeError, if the target is not callable. Description In ES5, you typically use the Function.prototype.apply
() method to call a function with a given this value and arguments provided as an array (or an array-like object). Function.prototype.apply.call(Math.floor, undefined, [1.75]); With Reflect.apply
() this becomes less verbose and easier to understand. ...
...ions A TypeError, if the target is not callable. Description In ES5, you typically use the Function.prototype.apply
() method to call a function with a given this value and arguments provided as an array (or an array-like object). Function.prototype.apply.call(Math.floor, undefined, [1.75]); With Reflect.apply
() this becomes less verbose and easier to understand. Examples Using Reflect.apply
() Reflect.apply(Math.floor, undefined, [1.75]); // 1; Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]) // "hello" Reflect.apply(RegExp.prototype.exec, /ab/, ['confabulation']).index // 4 Reflect.apply(''.charAt, 'ponies', [3]) // "i" Specifications Specification ECMAScript (ECMA-262)The definition of 'Reflect.apply' in that specification. ...
Reflect.getOwnPropertyDescriptor() - JavaScript
It returns a property descriptor of the given property if it exists on the object, undefined otherwise. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.getOwnPropertyDescriptor(target, propertyKey) Parameters target The target object in which to look for the property. propertyKey The name of the property to get an own property descriptor for. Return value A property descriptor object if the property exists in target object; otherwise, undefined. ...
...y descriptor for. Return value A property descriptor object if the property exists in target object; otherwise, undefined. Exceptions A TypeError, if target is not an Object. Description The Reflect.getOwnPropertyDescriptor method returns a property descriptor of the given property if it exists in the target object, undefined otherwise. ...
...rget object; otherwise, undefined. Exceptions A TypeError, if target is not an Object. Description The Reflect.getOwnPropertyDescriptor method returns a property descriptor of the given property if it exists in the target object, undefined otherwise. The only difference to Object.getOwnPropertyDescriptor
() is how non-object targets are handled. ...
...With Object.getOwnPropertyDescriptor, a non-object first argument will be coerced to an object at first. ...
RegExp.prototype[@@replace]() - JavaScript
The [@@replace]
() method replaces some or all matches of a this pattern in a string by a replacement, and returns the result of the replacement as a new string. The replacement can be a string or a function to be called for each match. 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 regexp[Symbol.replace](str, newSubStr|function) Parameters str A String that is a target of the replacement. newSubStr (replacement) The String that replaces the substring. A number of special replacement patterns are supported; see the Specifying a string as a parameter section in String.prototype.replace
() page. funct...
...nt) The String that replaces the substring. A number of special replacement patterns are supported; see the Specifying a string as a parameter section in String.prototype.replace
() page. function (replacement) A function to be invoked to create the new substring. The arguments supplied to this function are described in the Specifying a function as a parameter section in String.prototype.replace
() page. Return value A new string with some or all matches of a pattern replaced by a replacement. Description This method is called internally in String.prototype.replace
() if the pattern argument is a RegExp object. For example, following two examples return same result. 'abc'.replace(/a/, 'A'); /a/[Symbol.replace]('abc', 'A'); This method exists for customizing replace behavior in RegEx...
...d by a replacement. Description This method is called internally in String.prototype.replace
() if the pattern argument is a RegExp object. For example, following two examples return same result. 'abc'.replace(/a/, 'A'); /a/[Symbol.replace]('abc', 'A'); This method exists for customizing replace behavior in RegExp subclass. If pattern argument is not a RegExp object, String.prototype.replace
() doesn't call this method, nor creates a RegExp object. Examples Direct call This method can be used in almost the same way as String.prototype.replace
(), except the different this and the different arguments order. var re = /-/g; var str = '2016-01-01'; var newstr = re[Symbol.replace](str, '.'); console.log(newstr); // 2016.01.01 Using @@replace in subclasses Subclasses of RegExp can over...
... class MyRegExp extends RegExp { constructor(pattern, flags, count) { super(pattern, flags); this.count = count; } [Symbol.replace](str, replacement) { // Perform @@replace |count| times. ...
RegExp.prototype[@@split]() - JavaScript
Return value An Array containing substrings as its elements. ...
... 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 regexp[Symbol.split](str[, limit]) Parameters str The target of the split operation. limit Optional Integer specifying a limit on the number of splits to be found. ...
...teger specifying a limit on the number of splits to be found. The [@@split]
() method still splits on every match of this RegExp pattern (or, in the Syntax above, regexp), until the number of split items match the limit or the string falls short of this pattern. Return value An Array containing substrings as its elements. Description This method is called internally in String.prototype.split
() if its separator argument is an object that has a @@split method, such as a RegExp. For example, the following two examples return the same result. 'a-b-c'.split(/-/); /-/[Symbol.split]('a-b-c'); This method exists for customizing the behavior of split
() in RegExp subclass. ...
... String.prototype.split
() if its separator argument is an object that has a @@split method, such as a RegExp. For example, the following two examples return the same result. 'a-b-c'.split(/-/); /-/[Symbol.split]('a-b-c'); This method exists for customizing the behavior of split
() in RegExp subclass. Examples Direct call This method can be used in almost the same way as String.prototype.split
(), except the different this and the different order of arguments. let re = /-/g; let str = '2016-01-02'; let result = re[Symbol.split](str); console.log(result); // ["2016", "01", "02"] Using @@split in subclasses Subclasses of RegExp can override the [@@split]
() method to modify the default behavior. class MyRegExp extends RegExp { [Symbol.split](str, limit) { let result = RegExp.prot...
RegExp.prototype.exec() - JavaScript
The exec
() method executes a search for a match in a specified string. Returns a result array, or null. JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g. /foo/g or /foo/y). They store a lastIndex from the previous match. Using this internally, exec
() can be used to iterate over multiple matches in a string of text (with capture groups), as opposed to getting just the matching strings with String.prototype.match
(). A newer function has been proposed to simplify matching multiple parts of a string (with capture groups): String.prototype.matchAll
(). If you are executing a match simply to find true or false, use RegExp.prototype.test
() method or String.prototype.search
() instead. The source for this interactive example is stored in a GitHub reposit...
...e.search
() instead. 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 regexObj.exec(str) Parameters str The string against which to match the regular expression. Return value If the match succeeds, the exec
() method returns an array (with extra properties index and input; see below) and updates the lastIndex property of the regular expression object. The returned array has the matched text as the first item, and then one item for each parenthetical capture group of the matched text. If the match fails, the exec
() method returns null, and sets lastIndex to 0. Description Consider the following examp...
... was used to ignore case. true global Indicates if the g flag was used for a global match. true multiline Indicates if the m flag was used to search across multiple lines. false source The text of the pattern. "quick\s(brown).+?(jumps)" Examples Finding successive matches If your regular expression uses the "g" flag, you can use the exec
() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test
() will also advance the lastIndex property). Note that the lastIndex property will not be reset when searching a different string, it will start its search at its existing lastIndex . For example, assume you...
...xt: Found abb. Next match starts at 3 Found ab. Next match starts at 9 Warning: Do not place the regular expression literal (or RegExp constructor) within the while condition! It will create an infinite loop if there is a match, due to the lastIndex property being reset upon each iteration. Also, be sure that the global flag ("g") is set, or it will also cause an infinite loop. Using exec
() with RegExp literals You can also use exec
() without creating a RegExp object explicitly: let matches = /(hello \S+)/.exec('This is a hello world!'); console.log(matches[1]); This will log a message containing 'hello world!'. Specifications Specification ECMAScript (ECMA-262)The definition of 'RegExp.exec' in that specification. ...
Set.prototype.forEach() - JavaScript
The forEach
() method executes a provided function once for each value in the Set object, in insertion order. 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 mySet.forEach(callback[, thisArg]) Parameters callback Function to execute for each element, taking three arguments: currentValue, currentKey The current element being processed in the Set. As there are no keys in Set, the value is passed for both arguments. set The Set object which forEach
() was called upon. thisArg Value to use as this when executing callback. Return value undefined. ...
...meters callback Function to execute for each element, taking three arguments: currentValue, currentKey The current element being processed in the Set. As there are no keys in Set, the value is passed for both arguments. set The Set object which forEach
() was called upon. thisArg Value to use as this when executing callback. Return value undefined. Description The forEach
() method executes the provided callback once for each value which actually exists in the Set object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value undefined. callback is invoked with three arguments: the element value the element key the Set object being traversed There are no keys in Set objects, however, so th...
...t invoked for values which have been deleted. However, it is executed for values which are present but have the value undefined. callback is invoked with three arguments: the element value the element key the Set object being traversed There are no keys in Set objects, however, so the first two arguments are both values contained in the Set. This is to make it consistent with other forEach
() methods for Map and Array. If a thisArg parameter is provided to forEach
(), it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. Each value is visited once, except in ...
...rovided to forEach
(), it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. Each value is visited once, except in the case when it was deleted and re-added before forEach
() has finished. callback is not invoked for values deleted before being visited. New values added before forEach
() has finished will be visited. forEach
() executes the callback function once for each element in the Set object; it does not return a value. Examples Logging the contents of a Set object The following code logs a line for each element in a Set object: function logSetElements(value1...
String.prototype.big() - JavaScript
The big
() method creates a <big> HTML element that causes a string to be displayed in a big font. Usage note: The <big> element has been removed in HTML5 and shouldn't be used anymore. Instead web developers should use CSS properties. Syntax str.big
() Return value A string containing a <big> HTML element. Description The big
() method embeds a string in a <big> tag: "<big>str</big>". ...
...d creates a <big> HTML element that causes a string to be displayed in a big font. Usage note: The <big> element has been removed in HTML5 and shouldn't be used anymore. Instead web developers should use CSS properties. Syntax str.big
() Return value A string containing a <big> HTML element. Description The big
() method embeds a string in a <big> tag: "<big>str</big>". ...
...d shouldn't be used anymore. Instead web developers should use CSS properties. Syntax str.big
() Return value A string containing a <big> HTML element. Description The big
() method embeds a string in a <big> tag: "<big>str</big>". ...
...properties. Syntax str.big
() Return value A string containing a <big> HTML element. Description The big
() method embeds a string in a <big> tag: "<big>str</big>". ...
String.prototype.charAt() - JavaScript
The String object's charAt
() method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string. 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 character = str.charAt(index) Parameters index An integer between 0 and str.length - 1. If the index cannot be converted to the integer or no index is provided, the default is 0, so the first character of str is returned. Return value A string representing the character (exactly one UTF-16 code unit) at the specified index. If index is out of range, charAt
() returns an empty string. Description Chara...
... the specified index. If index is out of range, charAt
() returns an empty string. Description Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character--in a string called stringName--is stringName.length - 1. If the index you supply is out of this range, JavaScript returns an empty string. If no index is provided to charAt
(), the default is 0. ...
...e index you supply is out of this range, JavaScript returns an empty string. If no index is provided to charAt
(), the default is 0. ...
...'Low surrogate without preceding high surrogate' } let prev = str.charCodeAt(i - 1) // (could change last hex to 0xDB7F to treat high private surrogates // as single characters) if (0xD800 > prev || prev > 0xDBFF) { throw 'Low surrogate without preceding high surrogate' } // Return the next character instead (and increment) return [str.charAt(i + 1), i + 1] } Fixing charAt
() to support non-Basic-Multilingual-Plane (BMP) characters While the previous example may be more useful for programs that must support non-BMP characters (since it does not require the caller to know where any non-BMP character might appear), in the event that one does wish, in choosing a character by index, to treat the surrogate pairs within a string as the single characters they represent, one...
String.prototype.fontsize() - JavaScript
The fontsize
() method creates a <font> HTML element that causes a string to be displayed in the specified font size. Usage note: The <font> element has been removed in HTML5 and shouldn't be used anymore. Instead web developers should use CSS properties. Syntax str.fontsize(size) Parameters size An integer between 1 and 7, a string representing a signed integer between 1 and 7. Return value A string containing a <font> HTML element. Description When you specify size as an integer, you set the font size of str to one of the 7 defined sizes. When you specify size as a string such as "-2", you adjust the font size of str relative to the size set in the <basefont> tag. ...
...ger between 1 and 7, a string representing a signed integer between 1 and 7. Return value A string containing a <font> HTML element. Description When you specify size as an integer, you set the font size of str to one of the 7 defined sizes. When you specify size as a string such as "-2", you adjust the font size of str relative to the size set in the <basefont> tag. ...
...ption When you specify size as an integer, you set the font size of str to one of the 7 defined sizes. When you specify size as a string such as "-2", you adjust the font size of str relative to the size set in the <basefont> tag. ...
...f str to one of the 7 defined sizes. When you specify size as a string such as "-2", you adjust the font size of str relative to the size set in the <basefont> tag. ...
String.fromCodePoint() - JavaScript
The static String.fromCodePoint
() method returns a string created by using the specified sequence of code points. 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 String.fromCodePoint(num1[, ...[, numN]]) Parameters num1, ..., numN A sequence of code points. Return value A string created by using the specified sequence of code points. Exceptions A RangeError is thrown if an invalid Unicode code point is given (e.g. "RangeError: NaN is not a valid code point"). Description This method returns a string (and not a String object). ...
...fromCodePoint(num1[, ...[, numN]]) Parameters num1, ..., numN A sequence of code points. Return value A string created by using the specified sequence of code points. Exceptions A RangeError is thrown if an invalid Unicode code point is given (e.g. "RangeError: NaN is not a valid code point"). Description This method returns a string (and not a String object). Because fromCodePoint
() is a static method of String, you must call it as String.fromCodePoint
(), rather than as a method of a String object you created. Polyfill The String.fromCodePoint
() method has been added to ECMAScript 2015 and may not be supported in all web browsers or environments yet. Use the code below for a polyfill: if (!String.fromCodePoint) (function(stringFromCharCode) { var fromCodePoint = fun...
... return result + stringFromCharCode.apply(null, codeUnits); }; try { // IE 8 only supports `Object.defineProperty` on DOM elements Object.defineProperty(String, "fromCodePoint", { "value": fromCodePoint, "configurable": true, "writable": true }); } catch(e) { String.fromCodePoint = fromCodePoint; } }(String.fromCharCode)); Examples Using fromCodePoint
() Valid input: String.fromCodePoint(42); // "*" String.fromCodePoint(65, 90); // "AZ" String.fromCodePoint(0x404); // "\u0404" == "?" String.fromCodePoint(0x2F804); // "\uD87E\uDC04" String.fromCodePoint(194564); // "\uD87E\uDC04" String.fromCodePoint(0x1D306, 0x61, 0x1D307); // "\uD834\uDF06a\uD834\uDF07" Invalid input: String.fromCodePoint('_'); // RangeError String.fromCo...
...4" String.fromCodePoint(0x1D306, 0x61, 0x1D307); // "\uD834\uDF06a\uD834\uDF07" Invalid input: String.fromCodePoint('_'); // RangeError String.fromCodePoint(Infinity); // RangeError String.fromCodePoint(-1); // RangeError String.fromCodePoint(3.14); // RangeError String.fromCodePoint(3e-2); // RangeError String.fromCodePoint(NaN); // RangeError Compared to fromCharCode
() String.fromCharCode
() cannot return supplementary characters (i.e. code points 0x010000 - 0x10FFFF) by specifying their code point. Instead, it requires the UTF-16 surrogate pair in order to return a supplementary character: String.fromCharCode(0xD83C, 0xDF03); // Code Point U+1F303 "Night with String.fromCharCode(55356, 57091); // Stars" == "\uD83C\uDF03" String.fromCodePoint
(), on the oth...
String.raw() - JavaScript
This is similar to the r prefix in Python, or the @ prefix in C# for string literals. (But it is not identical; see explanations in this issue.) It's used to get the raw string form of template strings, that is, substitutions (e.g. ${foo}) are processed, but escapes (e.g. \n) are not. Syntax String.raw(callSite, ...substitutions) String.raw`templateString` Parameters callSite Well-formed template call site object, like { raw: ['foo', 'bar', 'baz'] }. ...substitutions Contains substitution values. templateString A template string, optionally with substitutions (${...}). Return value The raw string form of a given template string. ...
...-formed template call site object, like { raw: ['foo', 'bar', 'baz'] }. ...substitutions Contains substitution values. templateString A template string, optionally with substitutions (${...}). Return value The raw string form of a given template string. Exceptions TypeError A TypeError is thrown if the first argument is not a well-formed object. Description In most cases, String.raw
() is used with template strings. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other tag functions). String.raw
() is the only built-in tag function of template strings. It works just like the default template function and performs concatenation. You can even re-implement it with normal JavaScript c...
...The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other tag functions). String.raw
() is the only built-in tag function of template strings. It works just like the default template function and performs concatenation. You can even re-implement it with normal JavaScript code. Examples Using String.raw
() String.raw`Hi\n${2+3}!`; // 'Hi\n5!', the character after 'Hi' // is not a newline character, // '\' and 'n' are two characters. String.raw`Hi\u000A!`; // 'Hi\u000A!', same here, this time we will get the // \, u, 0, 0, 0, A, 6 characters. // All kinds of escape characters will be ineffective // and backslashes will be present in the output string. // You can confirm this by checking the .leng...
...\u000A!', same here, this time we will get the // \, u, 0, 0, 0, A, 6 characters. // All kinds of escape characters will be ineffective // and backslashes will be present in the output string. // You can confirm this by checking the .length property // of the string. let name = 'Bob'; String.raw`Hi\n${name}!`; // 'Hi\nBob!', substitutions are processed. // Normally you would not call String.raw
() as a function, // but to simulate `foo${2 + 3}bar${'Java' + 'Script'}baz` you can do: String.raw({ raw: ['foo', 'bar', 'baz'] }, 2 + 3, 'Java' + 'Script'); // 'foo5barJavaScriptbaz' // Notice the first argument is an object with a 'raw' property, // whose value is an iterable representing the separated strings // in the template literal. // The rest of the arguments are the substitutions. // T...
String.prototype.repeat() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.repeat(count) Parameters count An integer between 0 and +Infinity, indicating the number of times to repeat the string. Return value A new string containing the specified number of copies of the given string. Exceptions RangeError: repeat count must be non-negative. RangeError: repeat count must be less than infinity and not overflow maximum string size. ...
...ining the specified number of copies of the given string. Exceptions RangeError: repeat count must be non-negative. RangeError: repeat count must be less than infinity and not overflow maximum string size. Polyfill This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet. However, you can polyfill String.prototype.repeat
() with the following snippet: if (!String.prototype.repeat) { String.prototype.repeat = function(count) { 'use strict'; if (this == null) throw new TypeError('can\'t convert ' + this + ' to object'); var str = '' + this; // To convert string to integer. count = +count; // Check NaN if (count != count) count = 0; if (count < 0) throw new RangeEr...
... ...
... ...
String.prototype.small() - JavaScript
The small
() method creates a <small> HTML element that causes a string to be displayed in a small font. Syntax str.small
() Return value A string containing a <small> HTML element. Description The small
() method embeds a string in a <small> tag: "<small>str</small>". ...
... The small
() method creates a <small> HTML element that causes a string to be displayed in a small font. Syntax str.small
() Return value A string containing a <small> HTML element. Description The small
() method embeds a string in a <small> tag: "<small>str</small>". ...
...TML element that causes a string to be displayed in a small font. Syntax str.small
() Return value A string containing a <small> HTML element. Description The small
() method embeds a string in a <small> tag: "<small>str</small>". ...
...Syntax str.small
() Return value A string containing a <small> HTML element. Description The small
() method embeds a string in a <small> tag: "<small>str</small>". ...
String.prototype.substr() - JavaScript
The substr
() method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.substr(start[, length]) Parameters start The index of the first character to include in the returned substring. length Optional. The number of characters to extract. Return value A new string containing the specified part of the given string. Description substr
() extracts length characters from a str, counting from the start index. If start is a positive number, the index starts counting at the star...
...dex. If start is a positive number, the index starts counting at the start of the string. Its value is capped at str.length. If start is a negative number, the index starts counting from the end of the string. Its value is capped at -str.length. Note: In Microsoft JScript, negative values of the start argument are not considered to refer to the end of the string. If length is omitted, substr
() extracts characters to the end of the string. If length is undefined, substr
() extracts characters to the end of the string. If length is a negative number, it is treated as 0. For both start and length, NaN is treated as 0. Polyfill Microsoft's JScript does not support negative values for the start index. To use this feature in JScript, you can use the following code: // only run when the...
...ts characters to the end of the string. If length is undefined, substr
() extracts characters to the end of the string. If length is a negative number, it is treated as 0. For both start and length, NaN is treated as 0. Polyfill Microsoft's JScript does not support negative values for the start index. ...
...nction(substr) { return function(start, length) { // call the original method return substr.call(this, // did we get a negative start, calculate how much it is from the beginning of the string // adjust the start parameter for negative value start < 0 ? ...
Symbol() constructor - JavaScript
The Symbol
() constructor returns a value of type symbol, but is incomplete as a constructor because it does not support the syntax "new Symbol
()" and it is not intended to be subclassed. It may be used as the value of an extends clause of a class definition but a super call to it will cause an exception. 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 Symbol([description]) Parameters description Optional A string. A description of the symbol which can be used for debugging but not to access the symbol itself. ...
...u'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Symbol([description]) Parameters description Optional A string. A description of the symbol which can be used for debugging but not to access the symbol itself. Examples Creating symbols To create a new primitive symbol, you write Symbol
() with an optional string as its description: let sym1 = Symbol
() let sym2 = Symbol('foo') let sym3 = Symbol('foo') The above code creates three new symbols. Note that Symbol("foo") does not coerce the string "foo" into a symbol. It creates a new symbol each time: Symbol('foo') === Symbol('foo') // false new Symbol(...) The following syntax with the new operator will throw a TypeError: let...
... string as its description: let sym1 = Symbol
() let sym2 = Symbol('foo') let sym3 = Symbol('foo') The above code creates three new symbols. Note that Symbol("foo") does not coerce the string "foo" into a symbol. It creates a new symbol each time: Symbol('foo') === Symbol('foo') // false new Symbol(...) The following syntax with the new operator will throw a TypeError: let sym = new Symbol
() // TypeError This prevents authors from creating an explicit Symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new Boolean, new String and new Number). ...
...row a TypeError: let sym = new Symbol
() // TypeError This prevents authors from creating an explicit Symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new Boolean, new String and new Number). If you really want to create a Symbol wrapper object, you can use the Object
() function: let sym = Symbol('foo'); let symObj = Object(sym); typeof sym // => "symbol" typeof symObj // => "object" Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol constructor' in that specification. ...
TypedArray.prototype.map() - JavaScript
TypedArray is one of the typed array types here. 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 typedArray.map(mapFn[, thisArg]) Parameters mapFn A callback function that produces an element of the new typed array, taking three arguments: currentValue The current element being processed in the typed array. index Optional The index of the current element being processed in the typed array. ...
...e-examples and send us a pull request. Syntax typedArray.map(mapFn[, thisArg]) Parameters mapFn A callback function that produces an element of the new typed array, taking three arguments: currentValue The current element being processed in the typed array. index Optional The index of the current element being processed in the typed array. array Optional The typed array map
() was called upon. thisArg Optional Value to use as this when executing mapFn. Return value A new typed array. Description The map
() method calls a provided callback function (mapFn) once for each element in a typed array, in order, and constructs a new typed array from the results. mapFn is invoked only for indexes of the typed array which have assigned values; it is not invoked for in...
...rom the results. mapFn is invoked only for indexes of the typed array which have assigned values; it is not invoked for indexes that are undefined, those which have been deleted, or which have never been assigned values. mapFn is invoked with three arguments: the value of the element, the index of the element, and the typed array object being traversed. If a thisArg parameter is provided to map
(), it will be passed to mapFn when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by mapFn is determined according to the usual rules for determining the this seen by a function. map
() does not mutate the typed array on which it is called (although mapFn, if invoked, may do so). The range of element...
...d to mapFn when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by mapFn is determined according to the usual rules for determining the this seen by a function. map
() does not mutate the typed array on which it is called (although mapFn, if invoked, may do so). The range of elements processed by map
() is set before the first invocation of mapFn. Elements which are appended to the array after the call to map
() begins will not be visited by mapFn. If existing elements of the typed array are changed, or deleted, their value as passed to mapFn will be the value at the time map
() visits them; elements that are deleted are not visited. Examples Mapping a typed array to a typed array of square root...
TypedArray.prototype.toLocaleString() - JavaScript
TypedArray is one of the typed array types here. Syntax typedarray.toLocaleString([locales [, options]]); Parameters The locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. ...
...TypedArray is one of the typed array types here. Syntax typedarray.toLocaleString([locales [, options]]); Parameters The locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. ...
...y.toLocaleString([locales [, options]]); Parameters The locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. ...
...he locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. See the Intl.NumberFormat
() constructor for details on these parameters and how to use them. Return value A string representing the elements of the typed array. Examples Using toLocaleString var uint = new Uint32Array([2000, 500, 8123, 12, 4212]); uint.toLocaleString
(); // if run in a de-DE locale // "2.000,500,8.123,12,4.212" uint.toLocaleString('en-US'); // "2,000,500,8,123,12,4,212" uint.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }); // "?2,000,?500,?8,123,?12,?4,212" Specifications Specification ECMAScript (ECMA-262)The definition of 'TypedArray.prototype.toLocaleString' in that specification. ...
TypedArray.prototype.toString() - JavaScript
Examples The TypedArray objects override the toString method of Object. For TypedArray objects, the toString method joins the array and returns one string containing each typed array element separated by commas. ...
... Examples The TypedArray objects override the toString method of Object. For TypedArray objects, the toString method joins the array and returns one string containing each typed array element separated by commas. ...
...the typed array. Examples The TypedArray objects override the toString method of Object. For TypedArray objects, the toString method joins the array and returns one string containing each typed array element separated by commas. For example, the following code creates a typed array and uses toString to convert the array to a string. ...
...eates a typed array and uses toString to convert the array to a string. var numbers = new Uint8Array([2, 5, 8, 1, 4]) numbers.toString
(); // "2,5,8,1,4" JavaScript calls the toString method automatically when a typed array is to be represented as a text value or when an array is referred to in a string concatenation. Compatibility If a browser doesn't support the TypedArray.prototype.toString
() method yet, JavaScript will call the toString method of Object: var numbers = new Uint8Array([2, 5, 8, 1, 4]) numbers.toString
(); // "[object Uint8Array]" Specifications Specification ECMAScript (ECMA-262)The definition of 'Array.prototype.toString' in that specification. ...
Uint32Array() constructor - JavaScript
The Uint32Array
() typed array constructor creates an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). Syntax new Uint32Array
(); // new in ES2017 new Uint32Array(length); new Uint32Array(typedArray); new Uint32Array(object); new Uint32Array(buffer [, byteOffset [, length]]); Parameters length When called with a length argument, an internal array buffer is created in memory, of size length multiplied by BYTES_PER_ELEMENT bytes, containing zeros. typedArray When called with a typedArray argument, which can be an object of a...
...array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the typedArray argument. object When called with an object argument, a new typed array is created as if by the TypedArray.from
() method. buffer, byteOffset, length When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified ArrayBuffer. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is vie...
... ...
... ...
Uint8Array() constructor - JavaScript
The Uint8Array
() constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). Syntax new Uint8Array
(); // new in ES2017 new Uint8Array(length); new Uint8Array(typedArray); new Uint8Array(object); new Uint8Array(buffer [, byteOffset [, length]]); Parameters length When called with a length argument, an internal array buffer is created in memory, of size length multiplied by BYTES_PER_ELEMENT bytes, containing zeros. typedArray When called with a typedArray argument, which can be an object of any of the typed array types (such as Int32Array), the typedArray gets copied into a new typed array. ...
...array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the typedArray argument. object When called with an object argument, a new typed array is created as if by the TypedArray.from
() method. buffer, byteOffset, length When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified ArrayBuffer. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is vie...
... ...
... ...
WebAssembly.Table.prototype.get() - JavaScript
It then retrieves the references stored in the exported table. ...
...eference -- this is an exported WebAssembly function, a JavaScript wrapper for an underlying wasm function. Exceptions If index is greater than or equal to Table.prototype.length, a RangeError is thrown. ...
...es Using get The following example (see table.html on GitHub, and view it live also) compiles and instantiates the loaded table.wasm byte code using the WebAssembly.instantiateStreaming
() method. It then retrieves the references stored in the exported table. WebAssembly.instantiateStreaming(fetch('table.wasm')) .then(function(obj) { var tbl = obj.instance.exports.tbl; console.log(tbl.get(0)
()); // 13 console.log(tbl.get(1)
()); // 42 }); Note how you've got to include a second function invocation operator at the end of the accessor to actually retrieve the value stored inside the reference (e.g. ...
...references stored in the exported table. WebAssembly.instantiateStreaming(fetch('table.wasm')) .then(function(obj) { var tbl = obj.instance.exports.tbl; console.log(tbl.get(0)
()); // 13 console.log(tbl.get(1)
()); // 42 }); Note how you've got to include a second function invocation operator at the end of the accessor to actually retrieve the value stored inside the reference (e.g. get(0)
() rather than get(0)) -- it is a function rather than a simple value. Specifications Specification WebAssembly JavaScript InterfaceThe definition of 'get
()' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compa...
Array.unobserve() - Archive of obsolete content
The Array.unobserve
() method was used to remove observers set by Array.observe
(), but has been deprecated and removed from Browsers. You can use the more general Proxy object instead. Syntax Array.unobserve(arr, callback) Parameters arr The array to stop observing. callback The reference to the observer to stop calling each time changes are made on the array arr. Description Array.unobserve
() should be called after Array.observe
() in order to remove an observer from an array. The callback should be a reference to a function and not an anonymous function, because this reference will be used to unset the previous observer. It's useless to call Array.unobserve
() with an anonymous function as callback, it will not remove any observer. Examples Unobserving an array var ...
...s observer. It's useless to call Array.unobserve
() with an anonymous function as callback, it will not remove any observer. ...
...tion(changes) { console.log(changes); } Array.observe(arr, observer); arr.push(4); // [{type: "splice", object: <arr>, index: 3, removed:[], addedCount: 1}] Array.unobserve(arr, observer); arr.pop
(); // The callback wasn't called Using an anonymous function var persons = ['Khalid', 'Ahmed', 'Mohammed']; Array.observe(persons, function (changes) { console.log(changes); }); persons.shift
(); // [{type: "splice", object: <arr>, index: 0, removed: [ "Khalid" ], addedCount: 0 }] Array.unobserve(persons, function (changes) { console.log(changes); }); persons.push('Abdullah'); // [{type: "splice", object: <arr>, index: 2, removed: [], addedCount: 1 }] // The callback will always be called ...
Object.observe() - Archive of obsolete content
It provided a stream of changes in the order in which they occur. However, this API has been deprecated and removed from browsers. You can use the more general Proxy object instead. Syntax Object.observe(obj, callback[, acceptList]) Parameters obj The object to be observed. callback The function called each time changes are made, with the following argument: changes An array of objects each representing a change. The properties of these change objects are: name: The name of the property which was changed. object: The changed object after the change was made. type: A string indicating the type of change taking place. ...
...ct: <obj>, type: 'setPrototype', oldValue: <prototype>}] Object.seal(obj); // [ // {name: 'foo', object: <obj>, type: 'reconfigure'}, // {name: 'bar', object: <obj>, type: 'reconfigure'}, // {object: <obj>, type: 'preventExtensions'} // ] Data Binding // A user model var user = { id: 0, name: 'Brendan Eich', title: 'Mr.' }; // Create a greeting for the user function updateGreeting
() { user.greeting = 'Hello, ' + user.title + ' ' + user.name + '!'; } updateGreeting
(); Object.observe(user, function(changes) { changes.forEach(function(change) { // Any time name or title change, update the greeting if (change.name === 'name' || change.name === 'title') { updateGreeting
(); } }); }); Custom change type // A point on a 2D plane var point = {x: 0, y: 0, d...
...Strawma...
HTMLIFrameElement.getCanGoBack()
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The getCanGoBack
() method of the HTMLIFrameElement interface is used to indicate whether it's possible to go back in the navigation history of the browser <iframe>. ...
...on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The getCanGoBack
() method of the HTMLIFrameElement interface is used to indicate whether it's possible to go back in the navigation history of the browser <iframe>. Syntax instanceOfHTMLIframeElement.getCanGoBack
() .then(function(result) { ... }); Returns A Promise that resolves with a boolean that equals true if the history can be navigated backward or false if not. Parameters None. ...
...hod of the HTMLIFrameElement interface is used to indicate whether it's possible to go back in the navigation history of the browser <iframe>. Syntax instanceOfHTMLIframeElement.getCanGoBack
() .then(function(result) { ... }); Returns A Promise that resolves with a boolean that equals true if the history can be navigated backward or false if not. Parameters None. Example function canMoveBwd
() { browser.getCanGoBack
().then(function(result) { if (result) { back.disabled = false; console.log("It's possible to navigate the history backward."); } else { back.disabled = true; console.log("It's not possible to navigate the history backward."); } }); } Specification Not part of any specification. ...
HTMLIFrameElement.getCanGoForward()
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The getCanGoForward
() method of the HTMLIFrameElement is used to indicate whether it's possible to go forward in the navigation history of the browser <iframe>. ...
... on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The getCanGoForward
() method of the HTMLIFrameElement is used to indicate whether it's possible to go forward in the navigation history of the browser <iframe>. Syntax instanceOfHTMLIframeElement.getCanGoForward
() .then(function(result) { ... }); Returns A Promise that resolves with a boolean that equals true if the history can be navigated forward or false if not. Parameters None. ...
...) method of the HTMLIFrameElement is used to indicate whether it's possible to go forward in the navigation history of the browser <iframe>. Syntax instanceOfHTMLIframeElement.getCanGoForward
() .then(function(result) { ... }); Returns A Promise that resolves with a boolean that equals true if the history can be navigated forward or false if not. Parameters None. Example function canMoveFwd
() { browser.getCanGoForward
().then(function(result) { if (result) { fwd.disabled = false; console.log("It's possible to navigate the history forward."); } else { fwd.disabled = true; console.log("It's not possible to navigate the history forward."); } }); } Specification Not part of any specification. ...
HTMLIFrameElement.getScreenshot()
It won't wait more than 2000ms (this delay is defined by the Gecko dom.browserElement.maxScreenshotDelayMS preference). Syntax var instanceOfDOMRequest = instanceOfHTMLIframeElement.getScreenshot(maxWidth, maxHeight, mimeType); Returns A DOMRequest for handling the screenshot request. ...
...It won't wait more than 2000ms (this delay is defined by the Gecko dom.browserElement.maxScreenshotDelayMS preference). Syntax var instanceOfDOMRequest = instanceOfHTMLIframeElement.getScreenshot(maxWidth, maxHeight, mimeType); Returns A DOMRequest for handling the screenshot request. ...
...ying the format of the image to be returned; if not specified, the default used is image/jpeg. Use image/png to capture the alpha channel of the rendered result by returning a PNG-format image. This lets you get a transparent background for the content <iframe>. Examples var browser = document.querySelector('iframe'); var request = browser.getScreenshot(100, 100); request.onsuccess = function
() { var blob = request.result; var url = URL.createObjectURL(blob); } Specification Not part of any specification. ...
AbortController.AbortController() - Web APIs
The AbortController
() constructor creates a new AbortController object instance. Syntax var controller = new AbortController
(); Parameters None. Examples In the following snippet, we aim to download a video using the Fetch API. We first create a controller using the AbortController
() constructor, then grab a reference to its associated AbortSignal object using the AbortController.signal property. When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). This associates the signal and controller with the fetch request and allows us to abort it by calling AbortController.abort
(), as seen below in the second event listener. ...
...gnal object using the AbortController.signal property. When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). This associates the signal and controller with the fetch request and allows us to abort it by calling AbortController.abort
(), as seen below in the second event listener. var controller = new AbortController
(); var signal = controller.signal; var downloadBtn = document.querySelector('.download'); var abortBtn = document.querySelector('.abort'); downloadBtn.addEventListener('click', fetchVideo); abortBtn.addEventListener('click', function
() { controller.abort
(); console.log('Download aborted'); }); function fetchVideo
() { ... fetch(url, {signal}).then(function(response) { ... }).catch(...
...rtBtn = document.querySelector('.abort'); downloadBtn.addEventListener('click', fetchVideo); abortBtn.addEventListener('click', function
() { controller.abort
(); console.log('Download aborted'); }); function fetchVideo
() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textContent = 'Download error: ' + e.message; }) } Note: When abort
() is called, the fetch
() promise rejects with an AbortError. You can find a full working example on GitHub -- see abort-api (see it running live also). Specifications Specification Status Comment DOMThe definition of 'AbortController
()' in that specification. Living Standard Initial definition ...
Animation.finish() - Web APIs
The finish
() method of the Web Animations API's Animation Interface sets the current playback time to the end of the animation corresponding to the current playback direction. That is, if the animation is playing forward, it sets the playback time to the length of the animation sequence, and if the animation is playing in reverse (having had its reverse
() method called), it sets the playback time to 0. Syntax Animation.finish
(); Parameters None. Return value None. Exceptions InvalidState The player's playback rate is 0 or the animation's playback rate is greater than 0 and the end time of the animation is infinity. Examples The following example shows how to use the finish
() method and catch an InvalidState error. interfaceElement.addEventListener("mousedown", functio...
... to 0. Syntax Animation.finish
(); Parameters None. Return value None. Exceptions InvalidState The player's playback rate is 0 or the animation's playback rate is greater than 0 and the end time of the animation is infinity. Examples The following example shows how to use the finish
() method and catch an InvalidState error. interfaceElement.addEventListener("mousedown", function
() { try { player.finish
(); } catch(e if e instanceof InvalidState) { console.log("finish
() called on paused or finished animation."); } catch(e); logMyErrors(e); //pass exception object to error handler } }); The following example finishes all the animations on a single element, regardless of their direction of playback. ...
...EventListener("mousedown", function
() { try { player.finish
(); } catch(e if e instanceof InvalidState) { console.log("finish
() called on paused or finished animation."); } catch(e); logMyErrors(e); //pass exception object to error handler } }); The following example finishes all the animations on a single element, regardless of their direction of playback. elem.getAnimations
().forEach( function(animation){ return animation.finish
(); } ); Specifications Specification Status Comment Web AnimationsThe definition of 'finish
()' in that specification. Working Draft ...
Animation.persist() - Web APIs
The persist
() method of the Web Animations API's Animation interface explicitly persists an animation, when it would otherwise be removed due to the browser's Automatically removing filling animations behavior. Syntax animation.persist
(); Parameters None. Return value None. ...
...arameters None. Return value None. Examples In our simple replace indefinite animations demo, you can see the following code: const divElem = document.querySelector('div'); document.body.addEventListener('mousemove', evt => { let anim = divElem.animate( { transform: `translate(${ evt.clientX}px, ${evt.clientY}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitStyles
(); //anim.persist
() anim.onremove = function
() { console.log('Animation removed'); } console.log(anim.replaceState); }); Here we have a <div> element, and an event listener that fires the event handler code whenever the mouse moves. The event handler sets up an animation that animates the <div> element to the position of the mouse pointer. This could result in a huge animations list...
...imates the <div> element to the position of the mouse pointer. This could result in a huge animations list, which could create a memory leak. For this reason, modern browsers automatically remove overriding forward filling animations. You can see the replaceState of the animation being logged at the end of the handler. This will be active for each animation by default, or persisted if the persist
() call is uncommented. Specifications Specification Status Comment Web AnimationsThe definition of 'persist
()' in that specification. Working Draft ...
Animation.updatePlaybackRate() - Web APIs
The updatePlaybackRate
() method of the Web Animations API's Animation Interface sets the speed of an animation after first synchronizing its playback position. In some cases, an animation may run on a separate thread or process and will continue updating even while long-running JavaScript delays the main thread. In such a case, setting the playbackRate on the animation directly may cause the animation's playback position to jump since its playback position on the main thread may have drifted from the playback position where it is currently running. updatePlaybackRate
() is an asynchronous method that sets the speed of an animation after synchronizing with its current playback position, ensuring that the resulting change in speed does not produce a sharp jump. After calling updatePlaybac...
...It will be updated once the animation's ready promise is resolved. Syntax Animation.updatePlaybackRate(2); Parameters playbackRate The new speed to set. ...
...promise is resolved. Syntax Animation.updatePlaybackRate(2); Parameters playbackRate The new speed to set. This may be a positive number (to speed up or slow down the animation), a negative number (to make it play backwards), or zero (to effectively pause the animation). Return value None. Examples A speed selector component would benefit from smooth updating of updatePlaybackRate
(), as demonstrated below: speedSelector.addEventListener('input', evt => { cartoon.updatePlaybackRate(parseFloat(evt.target.value)); cartoon.ready.then(
() => { console.log(`Playback rate set to ${cartoon.playbackRate}`); }); }); Specifications Specification Status Comment Web AnimationsThe definition of 'updatePlaybackRate
()' in that specification. Working D...
AudioBufferSourceNode.AudioBufferSourceNode() - Web APIs
Syntax var audioBufferSourceNode = new AudioBufferSourceNode(context, options) Parameters Inherits parameters from the AudioNodeOptions dictionary. context A reference to an AudioContext. options Optional Options are as follows: buffer: An instance of AudioBuffer to be played. detune: A value in cents to modulate the speed of audio stream rendering. Its nominal range is (-? to +?). The default is 0. loop: A boolean indicating whether the audio should play in a loop. The default is false. If the loop is dynamically modified during playback, the new value will take effect on the next processing block of audio. ...
...playbackRate parameter. playbackRate: The speed at which to render the audio stream. Its default value is 1. This parameter is k-rate. This is a compound parameter with detune. Its nominal range is (-? to +?). Return value A new AudioBufferSourceNode object instance. Specifications Specification Status Comment Web Audio APIThe definition of 'AudioBufferSourceNode
()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for...
...wser 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. ...
AudioContext.createJavaScriptNode() - Web APIs
See also ScriptProcessorNode. Syntax var jsNode = audioCtx.createJavaScriptNode(bufferSize, numInputChannels, numOutputChannels); Parameters bufferSize The buffer size must be in units of sample frames, i.e., one of: 256, 512, 1024, 2048, 4096, 8192, or 16384. It controls the frequency of callbacks asking for a buffer refill. Smaller sizes allow for lower latency and higher for better overall quality. numInputChannels The number of input channels in the audio stream. ...
..., 512, 1024, 2048, 4096, 8192, or 16384. It controls the frequency of callbacks asking for a buffer refill. Smaller sizes allow for lower latency and higher for better overall quality. numInputChannels The number of input channels in the audio stream. numOutputChannels The number of output channels in the audio stream. ...
... this; this.x = 0; // Initial sample number this.context = context; this.node = context.createJavaScriptNode(1024, 1, 1); this.node.onaudioprocess = function(e) { that.process(e) }; } SineWave.prototype.process = function(e) { var data = e.outputBuffer.getChannelData(0); for (var i = 0; i < data.length; ++i) { data[i] = Math.sin(this.x++); } } SineWave.prototype.play = function
() { this.node.connect(this.context.destination); } SineWave.prototype.pause = function
() { this.node.disconnect
(); } See also Generating Tones with the Web Audio API Exploring the HTML5 Web Audio: visualizing sound ...
AudioContext.resume() - Web APIs
The resume
() method of the AudioContext interface resumes the progression of time in an audio context that has previously been suspended. This method will cause an INVALID_STATE_ERR exception to be thrown if called on an OfflineAudioContext. Syntax completePromise = audioContext.resume
(); Parameters None. Return value A Promise that resolves when the context has resumed. The promise is rejected if the context has already been closed. Example The following snippet is taken from our AudioContext states demo (see it running live.) When the suspend/resume button is clicked, the AudioContext.state is queried -- if it is running, suspend
() is called; if it is suspended, resume
() is called. In each case, the text label of the button is updated as appropriate once the promise resolves. s...
...eady been closed. Example The following snippet is taken from our AudioContext states demo (see it running live.) When the suspend/resume button is clicked, the AudioContext.state is queried -- if it is running, suspend
() is called; if it is suspended, resume
() is called. In each case, the text label of the button is updated as appropriate once the promise resolves. ...
...m our AudioContext states demo (see it running live.) When the suspend/resume button is clicked, the AudioContext.state is queried -- if it is running, suspend
() is called; if it is suspended, resume
() is called. In each case, the text label of the button is updated as appropriate once the promise resolves. susresBtn.onclick = function
() { if(audioCtx.state === 'running') { audioCtx.suspend
().then(function
() { susresBtn.textContent = 'Resume context'; }); } else if(audioCtx.state === 'suspended') { audioCtx.resume
().then(function
() { susresBtn.textContent = 'Suspend context'; }); } } Specifications Specification Status Comment Web Audio APIThe definition of 'resume
()' in that specification. Working Draft ...
AudioScheduledSourceNode.start() - Web APIs
If no time is specified, then the sound begins playing immediately. Syntax AudioScheduledSourceNode.start([when [, offset [, duration]]]); Parameters when Optional The time, in seconds, at which the sound should begin to play. This value is specified in the same time coordinate system as the AudioContext is using for its currentTime attribute. A value of 0 (or omitting the when parameter entirely) causes the sound to start playback immediately. offset Optional A floating-point number indicating the offset, in seconds, into the audio buffer where playback should begin. If 0 is passed then the playback will start from the beginning. ...
...e beginning. duration Optional A floating-point number indicating the duration, in seconds, to be played. If no value is passed then the duration will be equal to the length of the audio buffer minus the offset value Return value undefined Exceptions InvalidStateNode The node has already been started. This error occurs even if the node is no longer running because of a prior call to stop
(). ...
... prior call to stop
(). RangeError The value specified for when is negative. Example This example demonstrates how to create an OscillatorNode which is scheduled to start playing in 2 seconds and stop playing 1 second after that. The times are calculated by adding the desired number of seconds to the context's current time stamp returned by AudioContext.currentTime. context = new AudioContext
(); osc = context.createOscillator
(); osc.connect(context.destination); /* Schedule the start and stop times for the oscillator */ osc.start(context.currentTime + 2); osc.stop(context.currentTime + 3); Specifications Specification Status Comment Web Audio APIThe definition of 'start
()' in that specification. Working Draft ...
AudioScheduledSourceNode.stop() - Web APIs
If the node has already stopped, this method has no effect. Note: If a scheduled stop time occurs before the node's scheduled start time, the node never starts to play. Syntax AudioScheduledSourceNode.stop([when]); Parameters when Optional The time, in seconds, at which the sound should stop playing. This value is specified in the same time coordinate system as the AudioContext is using for its currentTime attribute. ...
...n seconds, at which the sound should stop playing. This value is specified in the same time coordinate system as the AudioContext is using for its currentTime attribute. Omitting this parameter, specifying a value of 0, or passing a negative value causes the sound to stop playback immediately. Return value undefined Exceptions InvalidStateNode The node has not been started by calling start
(). ...
...tateNode The node has not been started by calling start
(). RangeError The value specified for when is negative. Example This example demonstrates starting an oscillator node, scheduled to begin playing at once and to stop playing in one second. The stop time is determined by taking the audio context's current time from AudioContext.currentTime and adding 1 second. context = new AudioContext
(); osc = context.createOscillator
(); osc.connect(context.destination); /* Let's play a sine wave for one second. */ osc.start
(); osc.stop(context.currentTime + 1); Specifications Specification Status Comment Web Audio APIThe definition of 'stop
()' in that specification. Working Draft ...
AudioTrackList.getTrackById() - Web APIs
This lets you find a specified track if you know its ID string. Syntax var theTrack = AudioTrackList.getTrackById(id); Paramters id A DOMString indicating the ID of the track to locate within the track list. Return value An AudioTrack object indicating the first track found within the AudioTrackList whose id matches the specified string. If no match is found, this method returns null. The tracks are searched in their natural order; that is, in the order defined by the media resource itself, or, if the resource doesn't define an order, the relative order in which the tracks are declared by the media resource. ...
...t relevant, it gets left out. Obviously that would require some clever graphic design to make work, but... it's a hypothetical game. ...
...short function gets the AudioTrackList containing the video's audio tracks using HTMLMediaElement.audioTracks, then calls getTrackById
() on it, specifying the character's name. The resulting track's audio is then disabled by setting its enabled flag to false. Specifications Specification Status Comment HTML Living StandardThe definition of 'AudioTrackList.getTrackById
()' in that specification. Living Standard HTML5The definition of 'AudioTrackList.getTrackById
()' in that specification. Recommendation ...
AuthenticatorAttestationResponse.getTransports() - Web APIs
getTransports
() is a method of the AuthenticatorAttestationResponse interface that returns an Array containing strings describing the different transports which may be used by the authenticator. Such transports may be USB, NFC, BLE or internal (applicable when the authenticator is not removable from the device). Note: An AuthenticatorAttestationResponse instance is available on PublicKeyCredential.response after calling navigator.credentials.create
(). Note: This method may only be used in top-level contexts and will not be available in an <iframe> for example. Syntaxe arrTransports = authenticatorAttestationResponse.getTransports
() Parameters None. Return value An Array containing the different transports supported by the authenticator or nothing if this information is not av...
... Recommendation Initial definition. ...
... Recommendation Initial definition. ...
BaseAudioContext.createConstantSource() - Web APIs
Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
... Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
... Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
BaseAudioContext.createWaveShaper() - Web APIs
The createWaveShaper
() method of the BaseAudioContext interface creates a WaveShaperNode, which represents a non-linear distortion. It is used to apply distortion effects to your audio. Syntax baseAudioCtx.createWaveShaper
(); Returns A WaveShaperNode. Example The following example shows basic usage of an AudioContext to create a wave shaper node. For applied examples/information, check out our Voice-change-O-matic demo (see app.js for relevant code). Note: Sigmoid functions are commonly used for distortion curves because of their natural properties. Their S-shape, for instance, helps create a smoother sounding result. We found the below distortion curve code on Stack Overflow. ...
...d examples/information, check out our Voice-change-O-matic demo (see app.js for relevant code). Note: Sigmoid functions are commonly used for distortion curves because of their natural properties. Their S-shape, for instance, helps create a smoother sounding result. We found the below distortion curve code on Stack Overflow. var audioCtx = new (window.AudioContext || window.webkitAudioContext)
(); var distortion = audioCtx.createWaveShaper
(); ... function makeDistortionCurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve = new Float32Array(n_samples), deg = Math.PI / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( Math.PI + k * Math.abs(x) ); } ret...
... Working Draft ...
BiquadFilterNode() - Web APIs
Syntax var biquadFilterNode = new BiquadFilterNode(context, options) Parameters Inherits parameters from the AudioNodeOptions dictionary. context A reference to an AudioContext. options Optional Options are as follows: type: One of "lowpass", "highpass", "bandpass", "lowshelf", "highshelf", "peaking", "notch", "allpass". The meaning of the other options depends on the value of this one. ...
...alue implies a sharper transition and a larger group delay. frequency: The frequency where the center of the phase transition occurs. Viewed another way, this is the frequency with maximal group delay. gain: Not used. Return value A new BiquadFilterNode object instance. Specifications Specification Status Comment Web Audio APIThe definition of 'BiquadFilterNode
()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for ...
... 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. ...
Body.blob() - Web APIs
The blob
() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob. Syntax response.blob
().then(function(myBlob) { // do something with myBlob }); Parameters None. Note: If the Response has a Response.type of "opaque", the resulting Blob will have a Blob.size of 0 and a Blob.type of empty string "", which renders it useless for methods like URL.createObjectURL. Return value A promise that resolves with a Blob. Example In our fetch request example (run fetch request live), we create a new request using the Request
() constructor, then use it to fetch a JPG. ...
...l have a Blob.size of 0 and a Blob.type of empty string "", which renders it useless for methods like URL.createObjectURL. Return value A promise that resolves with a Blob. Example In our fetch request example (run fetch request live), we create a new request using the Request
() constructor, then use it to fetch a JPG. ...
...equest
() constructor, then use it to fetch a JPG. When the fetch is successful, we read a Blob out of the response using blob
(), put it into an object URL using URL.createObjectURL, and then set that URL as the source of an <img> element to display the image. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest) .then(response => response.blob
()) .then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); Specifications Specification Status Comment FetchThe definition of 'blob
()' in that specification. Living Standard ...
Body.json() - Web APIs
The json
() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON. Syntax response.json
().then(data => { // do something with your data }); Parameters None. Return value A Promise that resolves to a JavaScript object. This object could be anything that can be represented by JSON -- an object, an array, a string, a number... Example In our fetch json example (run fetch json live), we create a new request using the Request
() constructor, then use it to fetch a .json file. When the fetch is successful, we read and parse the data using json
(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data. const myList = ...
...he Request
() constructor, then use it to fetch a .json file. When the fetch is successful, we read and parse the data using json
(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data. const myList = document.querySelector('ul'); const myRequest = new Request('products.json'); fetch(myRequest) .then(response => response.json
()) .then(data => { for (const product of data.products) { let listItem = document.createElement('li'); listItem.appendChild( document.createElement('strong') ).textContent = product.Name; listItem.append( ` can be found in ${ product.Location }. Cost: ` ); listItem.appendChild( document.createElement('strong') ...
... Living Standard Initial definition ...
CSS.registerProperty() - Web APIs
Registering a custom property allows you to tell the browser how the custom property should behave; what are allowed types, whether the custom property inherits its value, and what the default value of the custom property is. Syntax CSS.registerProperty(PropertyDefinition); Parameters A PropertyDefinition dictionary object, which can contain the following members: name A DOMString indicating the name of the property being defined. syntax Optional A DOMString representing the expected syntax of the defined property. Defaults to "*". ...
...erty. Return value undefined. Exceptions InvalidModificationError The given name has already been registered. SyntaxError The given name isn't a valid custom property name (starts with two dashes, e.g. --foo). TypeError The required name and/or inherits dictionary members were not provided. Examples The following will register a custom property, --my-color, using registerProperty
(), as a color, give it a default value, and have it not inherit its value: window.CSS.registerProperty({ name: '--my-color', syntax: '<color>', inherits: false, initialValue: '#c0ffee', }); In this example, the custom property --my-color has been registered using the syntax <color> . We can now use that property to transition a gradient on hover or focus. Notice that with the registered ...
... Working Draft Initial definition. ...
CSSStyleSheet.addRule() - Web APIs
Syntax var result = cssStyleSheet.addRule(selector, styleBlock, index); Parameters selector A DOMString specifying the selector portion of the CSS rule. The default is the string undefined. styleBlock A DOMString indicating the style block to apply to elements matching the selector. The default is the string undefined. index Optional An optional index into the stylesheet's CSSRuleList at which to insert the new rule. ...
...ndex into the stylesheet's CSSRuleList at which to insert the new rule. If index is not specified, the next index after the last item currently in the list is used (that is, the value of cssStyleSheet.cssRules.length). Return value Always returns -1. Note that due to somewhat estoteric rules about where you can legally insert rules, it's possible that an exception may be thrown. ...
...Rules.length). Return value Always returns -1. Note that due to somewhat estoteric rules about where you can legally insert rules, it's possible that an exception may be thrown. See insertRule
() for more information. Usage notes This method is implemented by browsers by constructing a string using the template literal `${selector}{${styleBlock}}`, then passing it into the standard insertRule
() method. Therefore, given existing code such as the following: cssStyleSheet.addRule(selector, styles, 0); You can rewrite this to use the more standard insertRule
() like this: cssStyleSheet.insertRule(`${selector} {${styles}}`, 0); Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleSheet.addRule
()' in that specification. ...
CSSStyleSheet.insertRule() - Web APIs
Syntax stylesheet.insertRule(rule [, index]) Parameters rule A DOMString containing the rule to be inserted. What the inserted rule must contain depends on its type: For rule-sets, both a selector and a style declaration. For at-rules, both an at-identifier and the rule content. index Optional A positive integer less than or equal to stylesheet.cssRules.length, representing the newly inserted rule's position in CSSStyleSheet.cssRules. The default is 0. ...
... (function(Sheet_proto){ var originalInsertRule = Sheet_proto.insertRule; if (originalInsertRule.length === 2){ // 2 mandatory arguments: (selector, rules) Sheet_proto.insertRule = function(se...
...l; j++) { var prop = rule[j]; propStr += prop[0] + ': ' + prop[1] + (prop[2] ? ' !important' : '') + ';\n'; } // Insert CSS Rule styleSheet.insertRule(selector + '{' + propStr + '}', styleSheet.cssRules.length); } } Polyfill The below polyfill will correct the input of the arguments of insertRule
() to standardize them in Internet Explorer 5-8. It supplements insertRule
() with a function that separates the selector from the rules before sending the arguments to the default native insertRule
(). (function(Sheet_proto){ var originalInsertRule = Sheet_proto.insertRule; if (originalInsertRule.length === 2){ // 2 mandatory arguments: (selector, rules) Sheet_proto.insertRule = function(selectorAndRule){ // First, separate the selector from the rule ...
CacheStorage.delete() - Web APIs
The delete
() method of the CacheStorage interface finds the Cache object matching the cacheName, and if found, deletes the Cache object and returns a Promise that resolves to true. If no Cache object is found, it resolves to false. You can access CacheStorage through the global caches property. Syntax caches.delete(cacheName).then(function(boolean) { // your cache is now deleted }); Parameters cacheName The name of the cache you want to delete. Return value a Promise that resolves to true if the Cache object is found and deleted, and false otherwise. Examples In this code snippet we wait for an activate event, and then run a waitUntil
() block that clears up any old, unused caches before a new service worker is activated. Here we have an array of cache names we want to keep (...
... this code snippet we wait for an activate event, and then run a waitUntil
() block that clears up any old, unused caches before a new service worker is activated. Here we have an array of cache names we want to keep (cachesToKeep). We return the keys of the caches in the CacheStorage object using CacheStorage.keys, then check each key to see if it is in the array. If not, we delete it using delete
(). ...
...before a new service worker is activated. Here we have an array of cache names we want to keep (cachesToKeep). We return the keys of the caches in the CacheStorage object using CacheStorage.keys, then check each key to see if it is in the array. If not, we delete it using delete
(). this.addEventListener('activate', function(event) { var cachesToKeep = ['v2']; event.waitUntil( caches.keys
().then(function(keyList) { return Promise.all(keyList.map(function(key) { if (cachesToKeep.indexOf(key) === -1) { return caches.delete(key); } })); }) ); }); Specifications Specification Status Comment Service WorkersThe definition of 'CacheStorage: delete' in that specification. Working Draft Initial definition. ...
CacheStorage.keys() - Web APIs
The keys
() method of the CacheStorage interface returns a Promise that will resolve with an array containing strings corresponding to all of the named Cache objects tracked by the CacheStorage object in the order they were created. Use this method to iterate over a list of all Cache objects. You can access CacheStorage through the global caches property. Syntax caches.keys
().then(function(keyList) { //do something with your keyList }); Parameters None. Return value a Promise that resolves with an array of the Cache names inside the CacheStorage object. Examples In this code snippet we wait for an activate event, and then run a waitUntil
() block that clears up any old, unused caches before a new service worker is activated. Here we have a whitelist containing the names of the cac...
...an array of the Cache names inside the CacheStorage object. Examples In this code snippet we wait for an activate event, and then run a waitUntil
() block that clears up any old, unused caches before a new service worker is activated. Here we have a whitelist containing the names of the caches we want to keep (cacheWhitelist). We return the keys of the caches in the CacheStorage object using keys
(), then check each key to see if it is in the whitelist. If not, we delete it using CacheStorage.delete
(). ...
...tivated. Here we have a whitelist containing the names of the caches we want to keep (cacheWhitelist). We return the keys of the caches in the CacheStorage object using keys
(), then check each key to see if it is in the whitelist. If not, we delete it using CacheStorage.delete
(). then.addEventListener('activate', function(event) { var cacheWhitelist = ['v2']; event.waitUntil( caches.keys
().then(function(keyList) { return Promise.all(keyList.map(function(key) { if (cacheWhitelist.indexOf(key) === -1) { return caches.delete(key); } }); }) ); }); Specifications Specification Status Comment Service WorkersThe definition of 'CacheStorage: keys' in that specification. Working Draft Initial definition. ...
CanvasRenderingContext2D.createImageData() - Web APIs
All of the pixels in the new object are transparent black. Syntax ImageData ctx.createImageData(width, height); ImageData ctx.createImageData(imagedata); Parameters width The width to give the new ImageData object. A negative value flips the rectangle around the vertical axis. height The height to give the new ImageData object. A negative value flips the rectangle around the horizontal axis. imagedata An existing ImageData object from which to copy the width and height. The image itself is not copied. Return value A new ImageData object with the specified width and height. ...
...py the width and height. The image itself is not copied. Return value A new ImageData object with the specified width and height. The new object is filled with transparent black pixels. Errors thrown IndexSizeError Thrown if either of the width or height arguments is zero. Examples Creating a blank ImageData object This snippet creates a blank ImageData object using the createImageData
() method. HTML <canvas id="canvas"></canvas> JavaScript The generated object is 100 pixels wide and 50 pixels tall, making 5,000 pixels in all. Each pixel within an ImageData object consists of four array values, so the object's data property has a length of 4 x 5,000, or 20,000. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const imageData = ctx.cre...
... Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.createImageData' in that specification. Living Standard ...
CanvasRenderingContext2D.createLinearGradient() - Web APIs
Parameters x0 The x-axis coordinate of the start point. ...
... a linear CanvasGradient. To be applied to a shape, the gradient must first be assigned to the fillStyle or strokeStyle properties. Note: Gradient coordinates are global, i.e., relative to the current coordinate space. When applied to a shape, the coordinates are NOT relative to the shape's coordinates. Syntax CanvasGradient ctx.createLinearGradient(x0, y0, x1, y1); The createLinearGradient
() method is specified by four parameters defining the start and end points of the gradient line. Parameters x0 The x-axis coordinate of the start point. y0 The y-axis coordinate of the start point. x1 The x-axis coordinate of the end point. y1 The y-axis coordinate of the end point. Return value CanvasGradient A linear CanvasGradient initialized with the specified line. Examples ...
... x-axis coordinate of the start point. y0 The y-axis coordinate of the start point. x1 The x-axis coordinate of the end point. y1 The y-axis coordinate of the end point. Return value CanvasGradient A linear CanvasGradient initialized with the specified line. Examples Filling a rectangle with a linear gradient This example initializes a linear gradient using the createLinearGradient
() method. Three color stops between the gradient's start and end points are then created. Finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangle. HTML <canvas id="canvas"></canvas> JavaScript var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); // Create a linear gradient // The start gradient point is at x=20, y=0 // The e...
CanvasRenderingContext2D.fillRect() - Web APIs
The fill style is determined by the current fillStyle attribute. Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. ...
...The fill style is determined by the current fillStyle attribute. Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. ...
...ers x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. height The rectangle's height. Positive values are down, and negative are up. Examples A simple filled rectangle This example draws a filled green rectangle using the fillRect
() method. HTML <canvas id="canvas"></canvas> JavaScript The rectangle's top-left corner is at (20, 10). It has a width of 150 and a height of 100. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'green'; ctx.fillRect(20, 10, 150, 100); Result Filling the whole canvas This code snippet fills the entire canvas with a rectangle. This i...
CanvasRenderingContext2D.fillText() - Web APIs
The CanvasRenderingContext2D method fillText
(), part of the Canvas 2D API, draws a text string at the specified coordinates, filling the string's characters with the current fillStyle. An optional parameter allows specifying a maximum width for the rendered text, which the user agent will achieve by condensing the text or by using a lower font size. This method draws directly to the canvas without modifying the current path, so any subsequent fill
() or stroke
() calls will have no effect on it. The text is rendered using the font and text layout configuration as defined by the font, textAlign, textBaseline, and direction properties. To draw the outlines of the characters in a string, call the context's strokeText
() method. Syntax CanvasRenderingContext2D.fillText(text, x, y [, maxWidt...
...e text. However, if this value is provided, the user agent will adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. Return value undefined. Examples Drawing filled text This example writes the words "Hello world" using the fillText
() method. HTML First, we need a canvas to draw into. This code creates a context 400 pixels wide and 150 pixels across. <canvas id="canvas" width="400" height="150"></canvas> JavaScript The JavaScript code for this example follows. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.fillText('Hello world', 50, 90); This code ...
...Script code for this example follows. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.fillText('Hello world', 50, 90); This code obtains a reference to the <canvas>, then gets a reference to its 2D graphics context. With that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then call fillText
() to draw the text "Hello world," starting at the coordinates (50, 90). Result Restricting the text size This example writes the words "Hello world," restricting its width to 140 pixels. HTML <canvas id="canvas" width="400" height="150"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.fillText('Hello ...
CanvasRenderingContext2D.getImageData() - Web APIs
The CanvasRenderingContext2D method getImageData
() of the Canvas 2D API returns an ImageData object representing the underlying pixel data for a specified portion of the canvas. This method is not affected by the canvas's transformation matrix. If the specified rectangle extends outside the bounds of the canvas, the pixels outside the canvas are transparent black in the returned ImageData object. Note: Image data can be painted onto a canvas using the putImageData
() method. You can find more information about getImageData
() and general manipulation of canvas contents in Pixel manipulation with canvas. Syntax ctx.getImageData(sx, sy, sw, sh); Parameters sx The x-axis coordinate of the top-left corner of the rectangle from which the ImageData will be extracted. sy The y-axis co...
...ontains or may contain pixels which were loaded from an origin other than the one from which the document itself was loaded. To avoid SecurityError being thrown in this situation, configure CORS to allow the source image to be used in this way. See Allowing cross-origin use of images and canvas. Example Getting image data from a canvas This example draws a rectangle, and then uses getImageData
() to grab a portion of the canvas. HTML <canvas id="canvas"></canvas> JavaScript The object retrieved by getImageData
() has a width of 200 and a height of 100, for a total of 20,000 pixels. Of those pixels, most are either transparent or taken from off the canvas; only 5,000 of them are opaque black (the color of the drawn rectangle). const canvas = document.getElementById('canvas'); const ct...
...nvas> JavaScript The object retrieved by getImageData
() has a width of 200 and a height of 100, for a total of 20,000 pixels. Of those pixels, most are either transparent or taken from off the canvas; only 5,000 of them are opaque black (the color of the drawn rectangle). const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 10, 100, 100); ctx.fill
(); let imageData = ctx.getImageData(60, 60, 200, 100); ctx.putImageData(imageData, 150, 10); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.getImageData' in that specification. Living Standard ...
CanvasRenderingContext2D.getTransform() - Web APIs
The CanvasRenderingContext2D.getTransform
() method of the Canvas 2D API retrieves the current transformation matrix being applied to the context. Syntax let storedTransform = ctx.getTransform
(); Parameters None. Return value A DOMMatrix object. The transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] Note: The returned object is not live, so updating it will not affect the current transformation matrix, and updating the current transformation matrix will not affect an already returned DOMMatrix. Examples In the following example, we have two <canvas> elements. ...
...d & f \\ 0 & 0 & 1 \end{array} \right] Note: The returned object is not live, so updating it will not affect the current transformation matrix, and updating the current transformation matrix will not affect an already returned DOMMatrix. Examples In the following example, we have two <canvas> elements. We apply a transform to the first one's context using CanvasRenderingContext2D.setTransform
() and draw a square on it, then retrieve the matrix from it using getTransform
(). We then apply the retrieved matrix directly to the second canvas context by passing the DOMMatrix object directly to setTransform
(), and draw a circle on it. HTML <canvas width="240"></canvas> <canvas width="240"></canvas> CSS canvas { border: 1px solid black; } JavaScript const canvases = document.querySele...
...nd draw a circle on it. HTML <canvas width="240"></canvas> <canvas width="240"></canvas> CSS canvas { border: 1px solid black; } JavaScript const canvases = document.querySelectorAll('canvas'); const ctx1 = canvases[0].getContext('2d'); const ctx2 = canvases[1].getContext('2d'); ctx1.setTransform(1, .2, .8, 1, 0, 0); ctx1.fillRect(25, 25, 50, 50); let storedTransform = ctx1.getTransform
(); console.log(storedTransform); ctx2.setTransform(storedTransform); ctx2.beginPath
(); ctx2.arc(50, 50, 50, 0, 2 * Math.PI); ctx2.fill
(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.getTransform' in that specification. Living Standard ...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
The CanvasRenderingContext2D.isPointInStroke
() method of the Canvas 2D API reports whether or not the specified point is inside the area contained by the stroking of a path. Syntax ctx.isPointInStroke(x, y); ctx.isPointInStroke(path, x, y); Parameters x The x-axis coordinate of the point to check. y The y-axis coordinate of the point to check. path A Path2D path to check against. If unspecified, the current path is used. Return value Boolean A Boolean, which is true if the point is inside the area contained by the stroking of a path, otherwise false. Examples Checking a point in the current path This example uses the isPointInStroke
() method to check if a point is within the area of the current path's stroke. HTML <canvas id="canvas"></canvas> <p>In stroke: <code id=...
...If yes, the ellipse's stroke becomes green, otherwise it is red. ...
...cking a point in the specified path Whenever you move the mouse, this example checks whether the cursor is in the stroke of an elliptical Path2D path. If yes, the ellipse's stroke becomes green, otherwise it is red. ...
CanvasRenderingContext2D.setTransform() - Web APIs
The CanvasRenderingContext2D.setTransform
() method of the Canvas 2D API resets (overrides) the current transformation to the identity matrix, and then invokes a transformation described by the arguments of this method. This lets you scale, rotate, translate (move), and skew the context. Note: See also the transform
() method; instead of overriding the current transform matrix, it multiplies it with a given one. Syntax ctx.setTransform(a, b, c, d, e, f); ctx.setTransform(matrix); The transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] Parameters setTransform
() has two types of parameter that it can accept. The older type consists of several parameters representing the individual components of the transfor...
...ML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.setTransform(1, .2, .8, 1, 0, 0); ctx.fillRect(0, 0, 100, 100); Result Retrieving and passing a DOMMatrix object In the following example, we have two <canvas> elements. We apply a transform to the first one's context using the first type of setTransform
() and draw a square on it, then retrieve the matrix from it using CanvasRenderingContext2D.getTransform
(). We then apply the retrieved matrix directly to the second canvas context by passing the DOMMatrix object directly to setTransform
() (i.e. the second type), and draw a circle on it. HTML <canvas width="240"></canvas> <canvas width="240"></canvas> CSS canvas { border: 1px solid black; } ...
...nd draw a circle on it. HTML <canvas width="240"></canvas> <canvas width="240"></canvas> CSS canvas { border: 1px solid black; } JavaScript const canvases = document.querySelectorAll('canvas'); const ctx1 = canvases[0].getContext('2d'); const ctx2 = canvases[1].getContext('2d'); ctx1.setTransform(1, .2, .8, 1, 0, 0); ctx1.fillRect(25, 25, 50, 50); let storedTransform = ctx1.getTransform
(); console.log(storedTransform); ctx2.setTransform(storedTransform); ctx2.beginPath
(); ctx2.arc(50, 50, 50, 0, 2 * Math.PI); ctx2.fill
(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.setTransform' in that specification. Living Standard ...
CanvasRenderingContext2D.strokeText() - Web APIs
The CanvasRenderingContext2D method strokeText
(), part of the Canvas 2D API, strokes -- that is, draws the outlines of -- the characters of a text string at the specified coordinates. An optional parameter allows specifying a maximum width for the rendered text, which the user agent will achieve by condensing the text or by using a lower font size. This method draws directly to the canvas without modifying the current path, so any subsequent fill
() or stroke
() calls will have no effect on it. Use the fillText
() method to fill the text characters rather than having just their outlines drawn. Syntax CanvasRenderingContext2D.strokeText(text, x, y [, maxWidth]); Parameters text A DOMString specifying the text string to render into the context. The text is rendered using the settings...
.... However, if this value is provided, the user agent will adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. Return value undefined. Examples Drawing text outlines This example writes the words "Hello world" using the strokeText
() method. HTML First, we need a canvas to draw into. This code creates a context 400 pixels wide and 150 pixels high. <canvas id="canvas" width="400" height="150"></canvas> JavaScript The JavaScript code for this example follows. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.strokeText('Hello world', 50, 90); This code ...
...pt code for this example follows. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.strokeText('Hello world', 50, 90); This code obtains a reference to the <canvas>, then gets a reference to its 2D graphics context. With that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then call strokeText
() to draw the text "Hello world," starting at the coordinates (50, 90). Result Restricting the text size This example writes the words "Hello world," restricting its width to 140 pixels. HTML <canvas id="canvas" width="400" height="150"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.strokeText('Hell...
CanvasRenderingContext2D.translate() - Web APIs
An unmoved square of the same size is then drawn for comparison. ...
...An unmoved square of the same size is then drawn for comparison. ...
...ts origin x units horizontally and y units vertically on the grid. Parameters x Distance to move in the horizontal direction. Positive values are to the right, and negative to the left. y Distance to move in the vertical direction. Positive values are down, and negative are up. Examples Moving a shape This example draws a square that is moved from its default position by the translate
() method. An unmoved square of the same size is then drawn for comparison. HTML <canvas id="canvas"></canvas> JavaScript The translate
() method translates the context by 110 horizontally and 30 vertically. The first square is shifted by those amounts from its default position. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Moved square ctx.translate...
Client.postMessage() - Web APIs
The postMessage
() method of the Client interface allows a service worker to send a message to a client (a Window, Worker, or SharedWorker). The message is received in the "message" event on navigator.serviceWorker. Syntax client.postMessage(message[, transfer]); client.postMessage(message[, { transfer }]); Parameters message The message to send to the client. This can be any structured-clonable type. transfer Optional A sequence of objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side. Return value undefined. ...
... This can be any structured-clonable type. transfer Optional A sequence of objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side. Return value undefined. Examples Sending a message from a service worker to a client: addEventListener('fetch', event => { event.waitUntil(async function
() { // Exit early if we don't have access to the client. // Eg, if it's cross-origin. if (!event.clientId) return; // Get the client. const client = await clients.get(event.clientId); // Exit early if we don't get the client. // Eg, if it closed. if (!client) return; // Send a message to the client. client.postMessage({ msg: "Hey I just got a fetch fr...
...ient. // Eg, if it's cross-origin. if (!event.clientId) return; // Get the client. const client = await clients.get(event.clientId); // Exit early if we don't get the client. // Eg, if it closed. if (!client) return; // Send a message to the client. client.postMessage({ msg: "Hey I just got a fetch from you!", url: event.request.url }); }
()); }); Receiving that message: navigator.serviceWorker.addEventListener('message', event => { console.log(event.data.msg, event.data.url); }); Specifications Specification Status Comment Service WorkersThe definition of 'postMessage
()' in that specification. Working Draft Initial definition. ...
Clients.openWindow() - Web APIs
In Firefox, the method is allowed to show popups only when called as the result of a notification click event. In Chrome for Android, the method may instead open the URL in an existing browsing context provided by a standalone web app previously added to the user's home screen. As of recently, this also works on Chrome for Windows. Syntax self.clients.openWindow(url).then(function(windowClient) { // Do something with your WindowClient }); Parameters url A USVString representing the URL of the client you want to open in the window. ...
... ...
...er('notificationclick', e => { // Close the notification popout e.notification.close
(); // Get all the Window clients e.waitUntil(clients.matchAll({ type: 'window' }).then(clientsArr => { // If a Window tab matching the targeted URL already exists, focus that; const hadWindowToFocus = clientsArr.some(windowClient => windowClient.url === e.notification.data.url ? (windowClient.focus
(), true) : false); // Otherwise, open a new tab to the applicable URL and focus it. if (!hadWindowToFocus) clients.openWindow(e.notification.data.url).then(windowClient => windowClient ? windowClient.focus
() : null); })); }); Specifications Specification Status Comment Service WorkersThe definition of 'Clients: openWindow' in that specification. Working Draft...
ClipboardItem.getType() - Web APIs
The getType
() method of the ClipboardItem interface returns a Promise that resolves with a Blob of the requested MIME type or an error if the MIME type is not found. Syntax var blob = clipboardItem.getType(type); Parameters type A valid MIME type. Return value A Promise that resolves with a Blob object. Exceptions DOMException The type does not match a known MIME type. TypeError No parameter is specified or the type is not that of the ClipboardItem. Examples In the following example, we're returning all items on the clipboard via the clipboard.read
() method. Then utilizing the ClipboardItem.types property to set the getType
() argument and return the corresponding blob object. ...
...n The type does not match a known MIME type. TypeError No parameter is specified or the type is not that of the ClipboardItem. Examples In the following example, we're returning all items on the clipboard via the clipboard.read
() method. Then utilizing the ClipboardItem.types property to set the getType
() argument and return the corresponding blob object. ...
... is specified or the type is not that of the ClipboardItem. Examples In the following example, we're returning all items on the clipboard via the clipboard.read
() method. Then utilizing the ClipboardItem.types property to set the getType
() argument and return the corresponding blob object. ...
CloseEvent.initCloseEvent() - Web APIs
The page on Creating and triggering events gives more information about the way to use these. Syntax event.initMouseEvent(type, canBubble, cancelable, wasClean, reasonCode, reason); Parameters type the string to set the event's type to. ...
...The page on Creating and triggering events gives more information about the way to use these. Syntax event.initMouseEvent(type, canBubble, cancelable, wasClean, reasonCode, reason); Parameters type the string to set the event's type to. ...
...The page on Creating and triggering events gives more information about the way to use these. Syntax event.initMouseEvent(type, canBubble, cancelable, wasClean, reasonCode, reason); Parameters type the string to set the event's type to. Possible types for mouse events include: click, mousedown, mouseup, mouseover, mousemove, mouseout. ...
console.count() - Web APIs
The console.count
() method logs the number of times that this particular call to count
() has been called. Note: This feature is available in Web Workers. Syntax console.count([label]); Parameters label Optional A String. If supplied, count
() outputs the number of times it has been called with that label. If omitted, count
() behaves as though it was called with the "default" label. Examples For example, given code like this: let user = ""; function greet
() { console.count
(); return "hi " + user; } user = "bob"; greet
(); user = "alice"; greet
(); greet
(); console.count
(); Console output will look something like this: "default: 1" "default: 2" "default: 3" "default: 4" The label is displayed as default because no explicit label was supplied. If we pass the user variable as...
...; function greet
() { console.count
(); return "hi " + user; } user = "bob"; greet
(); user = "alice"; greet
(); greet
(); console.count
(); Console output will look something like this: "default: 1" "default: 2" "default: 3" "default: 4" The label is displayed as default because no explicit label was supplied. If we pass the user variable as the label argument to the first invocation of count
(), and the string "alice" to the second: let user = ""; function greet
() { console.count(user); return "hi " + user; } user = "bob"; greet
(); user = "alice"; greet
(); greet
(); console.count("alice"); We will see output like this: "bob: 1" "alice: 1" "alice: 2" "alice: 3" We're now maintaining separate counts based only on the value of label. Specifications Specification S...
... { console.count(user); return "hi " + user; } user = "bob"; greet
(); user = "alice"; greet
(); greet
(); console.count("alice"); We will see output like this: "bob: 1" "alice: 1" "alice: 2" "alice: 3" We're now maintaining separate counts based only on the value of label. Specifications Specification Status Comment Console APIThe definition of 'console.count
()' in that specification. Living Standard Initial definition ...
Console.countReset() - Web APIs
The console.countReset
() method resets counter used with console.count
(). Note: This feature is available in Web Workers. Syntax console.countReset([label]); Parameters label Optional A String. If supplied, countReset
() resets the count for that label to 0. If omitted, countReset
() resets the default counter to 0. Examples For example, given code like this: let user = ""; function greet
() { console.count
(); return "hi " + user; } user = "bob"; greet
(); user = "alice"; greet
(); greet
(); console.count
(); console.countReset
(); Console output will look something like this: "default: 1" "default: 2" "default: 3" "default: 4" "default: 0" Note that the call to console.counterReset
() resets the value of the default counter to zero. If we pass the user variable as the label ...
..."; greet
(); user = "alice"; greet
(); greet
(); console.count
(); console.countReset
(); Console output will look something like this: "default: 1" "default: 2" "default: 3" "default: 4" "default: 0" Note that the call to console.counterReset
() resets the value of the default counter to zero. If we pass the user variable as the label argument with the string "bob" to the first invocation of count
(), and the string "alice" to the second: let user = ""; function greet
() { console.count(user); return "hi " + user; } user = "bob"; greet
(); user = "alice"; greet
(); greet
(); console.countReset("bob"); console.count("alice"); We will see output like this: "bob: 1" "alice: 1" "alice: 2" "bob: 0" "alice: 3" Resetting the value of the counter "bob" only changes the value of that counter. Th...
..."alice"; greet
(); greet
(); console.countReset("bob"); console.count("alice"); We will see output like this: "bob: 1" "alice: 1" "alice: 2" "bob: 0" "alice: 3" Resetting the value of the counter "bob" only changes the value of that counter. The value of "alice" is unchanged. Specifications Specification Status Comment Console APIThe definition of 'console.countReset
()' in that specification. Living Standard Initial definition ...
Console.error() - Web APIs
Parameters obj1 ... objN A list of JavaScript objects to output. ...
... Parameters obj1 ... objN A list of JavaScript objects to output. ...
...aining zero or more substitution strings. subst1 ... substN JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. See Outputting text to the console in the documentation of console for details. Specifications Specification Status Comment Console APIThe definition of 'console.error
()' in that specification. Living Standard Initial definition ...
Console.timeEnd() - Web APIs
See Timers in the documentation for details and examples. Note: This feature is available in Web Workers. Syntax console.timeEnd(label); Parameters label The name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the Web Console along with an indicator that the time has ended. ...
... Living Standard Initial definition ...
...; alert("Do a bunch of other stuff..."); console.timeEnd("answer time"); The output from the example above shows the time taken by the user to dismiss the first alert box, followed by the time it took for the user to dismiss the second alert: Notice that the timer's name is displayed when the timer value is logged using timeLog
() and again when it's stopped. In addition, the call to timeEnd
() has the additional information, "timer ended" to make it obvious that the timer is no longer tracking time. Specifications Specification Status Comment Console APIThe definition of 'console.timeEnd
()' in that specification. Living Standard Initial definition ...
ContentIndex.getAll() - Web APIs
Return value Returns a Promise that resolves with an Array of ContentDescription items. ContentDescription Each item returned is an Object containing 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. ...
...tation of the image size. type: Optional The MIME type of the image. Exceptions No exceptions are thrown. If there are no items in the Content Index, an empty Array is returned. Examples The below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface. ...
...returned. Examples The below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface. ...
ConvolverNode() - Web APIs
Syntax var convolverNode = new ConvolverNode(context, options) Parameters Inherits parameters from the AudioNodeOptions dictionary. context A reference to an AudioContext. options Optional Options are as follows: audioBuffer: A mono, stereo, or 4-channel AudioBuffer containing the (possibly multichannel) impulse response used by the ConvolverNode to create the reverb effect. disableNormalization: A Boolean controlling whether the impulse response from the buffer will be scaled by an equal-power normalization, or not. The default is 'false'. Return value A new ConvolverNode object instance. ...
.... Return value A new ConvolverNode object instance. Exceptions Exception Explanation NotSupportedError The referenced AudioBuffer does not have the correct number of channels, or it has a different sample rate to the associated AudioContext. Specifications Specification Status Comment Web Audio APIThe definition of 'ConvolverNode
()' in that specification. Working Draft Initial definition. 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...
... 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. ...
CredentialsContainer.get() - Web APIs
If no match is found the Promise will resolve to null. This method first collects all credentials in the CredentialsContainer that meet the necessary criteria (defined in the options argument). From the resulting set of credentials, it then selects the best one. Depending on the options, it may display a dialog to the user and ask the user to make the selection. This method collects credentials by calling the "CollectFromCredentialStore" method for each credential type allowed by the options argument. For example: if options.password exists, then the PasswordCredential.[[CollectFromCredentialStore]] is called. ...
...ntaining requirements for returned WebAuthn credentials. mediation: A String indicating whether the user will be required to log on for every visit to the website. Valid values are "silent", "optional", or "required". unmediated: A Boolean indicating the returned Credential instance should not require user mediation. signal: An instance of AbortSignal that can indicate that an ongoing get
() operation should be halted. An aborted operation may complete normally (generally if the abort was received after the operation finished) or reject with an "AbortError" DOMException. Returns A Promise that resolves with a Credential instance that matches the provided parameters. If a single Credential cannot be unambigiously obtained, the Promise will resolve to null. Specifications ...
...received after the operation finished) or reject with an "AbortError" DOMException. Returns A Promise that resolves with a Credential instance that matches the provided parameters. If a single Credential cannot be unambigiously obtained, the Promise will resolve to null. Specifications Specification Status Comment Credential Management Level 1The definition of 'get
()' in that specification. Working Draft Initial definition. Web Authentication: An API for accessing Public Key Credentials Level 1 Recommendation Initial definition. ...
CustomElementRegistry.whenDefined() - Web APIs
The menu displays placeholder content until the actual menu content is ready to display. ...
...ment name. Return value A Promise that resolves to undefined when the custom element is defined. If the custom element is already defined, the promise is resolved immediately. Exceptions Exception Description SyntaxError If the provided name is not a valid custom element name, the promise rejects with a SyntaxError. Examples This example uses whenDefined
() to detect when the custom elements that make up a menu are defined. The menu displays placeholder content until the actual menu content is ready to display. <nav id="menu-container"> <div class="menu-placeholder">Loading...</div> <nav-menu> <menu-item>Item 1</menu-item> <menu-item>Item 2</menu-item> ... <menu-item>Item N</menu-item> </nav-menu> </nav> const container = d...
... Living Standard Initial definition. ...
DOMMatrixReadOnly.flipX() - Web APIs
The original matrix is not modified. Examples This SVG contains two paths in the shape of a triangle, both drawn to the same position. Note that the x co-ordinate of the viewBox attribute is negative, showing us content from both sides of the x-axis. ...
...both drawn to the same position. Note that the x co-ordinate of the viewBox attribute is negative, showing us content from both sides of the x-axis. ...
... 50 0 L 50 100 Z" /> <path id="flipped" fill="blue" d="M 0 50 L 50 0 L 50 100 Z" /> </svg> This JavaScript first creates an identity matrix, then uses the `flipX
()` method to create a new matrix, which is then applied to the blue triangle, inverting it across the x-axis. The red triangle is left in place. const flipped = document.getElementById('flipped'); const matrix = new DOMMatrixReadOnly
(); const flippedMatrix = matrix.flipX
(); flipped.setAttribute('transform', flippedMatrix.toString
()); ScreenshotLive sample Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'DOMMatrixReadOnly.flipX
()' in that specification. Candidate Recommendation Initial definition ...
DOMMatrixReadOnly.translate() - Web APIs
DOMMatrix.translate(translateX, translateY[, translateZ]) Parameters translateX A number representing the abscissa (x-coordinate) of the translating vector. translateY A number representing the ordinate (y-coordinate) of the translating vector. translateZ Optional A number representing the z component of the translating vector. If not supplied, this defaults to 0. If this is anything other than 0, the resulting matrix will be 3D. Return value Returns a DOMMatrix containing a new matrix being the result of the matrix being translated by the given vector. ...
...the resulting matrix will be a 4x4 3D matrix. ...
..."250" viewBox="0 0 50 50"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> </svg> The following JavaScript first creates an identity matrix, then uses the translate
() method to create a new, translated matrix -- which is then applied to the blue square as a transform. The red square is left in place. const matrix = new DOMMatrixReadOnly
().translate(25, 25); document.querySelector('#transformed').setAttribute('transform', matrix.toString
()); ScreenshotLive sample Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'DOMMatrixReadOnly.translate
()' in that specification. Candidate Recommendation Initial definition ...
DOMRectReadOnly.fromRect() - Web APIs
Candidate Recommendation Initial definition. ...
...s default to 0. The properties are: x: The coordinate of the left side of the rectangle. y: The coordinate of the top side of the rectangle. width: The width of the rectangle. height: The height of the rectangle. Return value An instance of DOMRect. Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'fromRect
()' in that specification. Candidate Recommendation Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for Android...
...n. 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. ...
DataTransferItem.getAsFile() - Web APIs
If the item is a file, the DataTransferItem.getAsFile
() method returns the drag data item's File object. If the item is not a file, this method returns null. Syntax File = DataTransferItem.getAsFile
(); Parameters None. Return value File If the drag data item is a file, a File object is returned; otherwise null is returned. Example This example shows the use of the getAsFile
() method in a drop event handler. ...
...ile object. If the item is not a file, this method returns null. Syntax File = DataTransferItem.getAsFile
(); Parameters None. Return value File If the drag data item is a file, a File object is returned; otherwise null is returned. Example This example shows the use of the getAsFile
() method in a drop event handler. ...
...'))) { // Drag data item is HTML console.log("... Drop: HTML"); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI console.log("... Drop: URI"); } else if ((data[i].kind == 'file') && (data[i].type.match('^image/'))) { // Drag data item is an image file var f = data[i].getAsFile
(); console.log("... Drop: File "); } } } Specifications Specification Status Comment HTML Living StandardThe definition of 'getAsFile
()' in that specification. Living Standard Initial value HTML 5.1The definition of 'getAsFile
()' in that specification. Recommendation Snapshot of the HTML WHATWG document ...
DataTransferItem.getAsString() - Web APIs
The DataTransferItem.getAsString
() method invokes the given callback with the drag data item's string data as the argument if the item's kind is a Plain unicode string (i.e. kind is string). Syntax dataTransferItem.getAsString(callback); Parameters callback A callback function that has access to the data transfer item's string data. See Callback below for details. Return value undefined Callback The callback parameter is a callback function which accepts one parameter: DOMString The drag data item's string data. The callback return value is undefined. Example This example shows the use of the getAsString
() method as an inline function in a drop event handler. ...
...low for details. Return value undefined Callback The callback parameter is a callback function which accepts one parameter: DOMString The drag data item's string data. The callback return value is undefined. Example This example shows the use of the getAsString
() method as an inline function in a drop event handler. ...
...'))) { // Drag data item is HTML console.log("... Drop: HTML"); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI console.log("... Drop: URI"); } else if ((data[i].kind == 'file') && (data[i].type.match('^image/'))) { // Drag data item is an image file var f = data[i].getAsFile
(); console.log("... Drop: File "); } } } Specifications Specification Status Comment HTML Living StandardThe definition of 'getAsString
()' in that specification. Living Standard Initial definition. HTML 5.1The definition of 'getAsString
()' in that specification. Recommendation Snapshot fo HTML WHATWG document ...
DelayNode() - Web APIs
Syntax var delayNode = new DelayNode(context); var delayNode = new DelayNode(context, options); Parameters Inherits parameters from the AudioNodeOptions dictionary. context A reference to an AudioContext or OfflineAudioContext. options Optional An object specifying the delay node options. Can contain the following members: delayTime: The initial delay time for the node, in seconds. The default is 0. maxDelayTime: The maximum delay time for the node, in seconds. Defaults to 1. Return value A new DelayNode object instance. ...
...to an AudioContext or OfflineAudioContext. options Optional An object specifying the delay node options. Can contain the following members: delayTime: The initial delay time for the node, in seconds. The default is 0. maxDelayTime: The maximum delay time for the node, in seconds. Defaults to 1. Return value A new DelayNode object instance. Example const audioCtx = new AudioContext
(); const delayNode = new DelayNode(audioCtx, { delayTime: 0.5, maxDelayTime: 2, }); Specifications Specification Status Comment Web Audio APIThe definition of 'DelayNode
()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to t...
.... 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. ...
Document.adoptNode() - Web APIs
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. ...
... Best Practice: Although Firefox doesn't currently enforce this rule, we encourage you to follow this rule for improved future compatibility. For more on the Node.ownerDocument issues, see the W3C DOM FAQ. Specifications Specification Status Comment DOMThe definition of 'document.adoptNode' in that specification. Living...
... iframeImages = iframe.contentDocument.querySelectorAll('img'); const newParent = document.getElementById('images'); iframeImages.forEach(function(imgEl) { newParent.appendChild(document.adoptNode(imgEl)); }); Notes Before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importNode
(); or adopted using document.adoptNode
(). Best Practice: Although Firefox doesn't currently enforce this rule, we encourage you to follow this rule for improved future compatibility. For more on the Node.ownerDocument issues, see the W3C DOM FAQ. Specifications Specification Status Comment DOMThe definition of 'document.adoptNode' in that specification. Living Standard ...
Document.createAttribute() - Web APIs
The object created a node implementing the Attr interface. The DOM does not enforce what sort of attributes can be added to a particular element in this manner. The string given in parameter is converted to lowercase. Syntax attribute = document.createAttribute(name) Parameters name is a string containing the name of the attribute. Return value A Attr node. Exceptions INVALID_CHARACTER_ERR if the parameter contains invalid characters for XML attribute. ...
...CHARACTER_ERR if the parameter contains invalid characters for XML attribute. Example var node = document.getElementById("div1"); var a = document.createAttribute("my_attrib"); a.value = "newVal"; node.setAttributeNode(a); console.log(node.getAttribute("my_attrib")); // "newVal" Specifications Specification Status Comment DOMThe definition of 'Document.createAttribute
()' in that specification. Living Standard Precised behavior with uppercase characters Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Document.createAttribute
()' in that specification. Obsolete No change. Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Document.createAttribute
()' in that specification. Obsolete No...
...bject Model (DOM) Level 3 Core SpecificationThe definition of 'Document.createAttribute
()' in that specification. Obsolete No change. Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Document.createAttribute
()' in that specification. Obsolete No change. Document Object Model (DOM) Level 1 SpecificationThe definition of 'Document.createAttribute
()' in that specification. Obsolete Initial definition. ...
Document.createTouch() - Web APIs
Syntax var touch = DocumentTouch.createTouch(view, target, identifier, pageX, pageY, screenX, screenY); Parameters Note: All parameters are optional. view The window in which the touch occurred. target The EventTarget for the touch. identifier The value for Touch.identifier. pageX The value for Touch.pageX. pageY The value for Touch.pageY. screenX The value for Touch.screenX. screenY The value for Touch.screenY. ...
... clientX The value for Touch.clientX. clientY The value for Touch.clientY. radiusX The value for Touch.radiusX. radiusY The value for Touch.radiusY. rotationAngle The value for Touch.rotationAngle. force The value for Touch.force. Return value touch A Touch object configured as described by the input parameters. Example This example illustrates using the Document.createTouch
() method to create Touch objects. In following code snippet, two Touch objects are created for the target element. var target = document.getElementById("target"); var touch1 = Document.createTouch(window, target, 1, 15, 20, 35, 40); var touch2 = Document.createTouch(window, target, 2, 25, 30, 45, 50); Specifications Specification Status Comment Touch EventsThe defi...
.... In following code snippet, two Touch objects are created for the target element. var target = document.getElementById("target"); var touch1 = Document.createTouch(window, target, 1, 15, 20, 35, 40); var touch2 = Document.createTouch(window, target, 2, 25, 30, 45, 50); Specifications Specification Status Comment Touch EventsThe definition of 'Document.createTouch
()' in that specification. Recommendation Initial definition. ...
Document.createTreeWalker() - Web APIs
Syntax document.createTreeWalker(root, whatToShow[, filter[, entityReferenceExpansion]]); Parameters root A root Node of this TreeWalker traversal. Typically this will be an element owned by the document. whatToShow Optional A unsigned long representing a bitmask created by combining the constant properties of NodeFilter. It is a convenient way of filtering for certain types of node. It defaults to 0xFFFFFFFF representing the SHOW_ALL constant. Constant Numerical value Description NodeFilter.SHOW_ALL -1 (that is the max value of unsigned long) Shows all nodes. ...
... check. entityReferenceExpansion Optional A Boolean flag indicating if when discarding an EntityReference its whole sub-tree must be discarded at the same time. Return value A new TreeWalker object. Example The following example goes through all nodes in the body, reduces the set of nodes to elements, simply passes through as acceptable each node (it could reduce the set in the acceptNode
() method instead), and then makes use of tree walker iterator that is created to advance through the nodes (now all elements) and push them into an array. var treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); var nodeList = []; var currentNode = treeWalker.currentNode; while(curren...
...ed to advance through the nodes (now all elements) and push them into an array. var treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); var nodeList = []; var currentNode = treeWalker.currentNode; while(currentNode) { nodeList.push(currentNode); currentNode = treeWalker.nextNode
(); } Specifications Specification Status Comment DOMThe definition of 'Document.createTreeWalker' in that specification. Living Standard Removed the expandEntityReferences parameter. Made the whatToShow and filter parameters optionals. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Document.createTreeWalker' in that ...
Document.getElementsByName() - Web APIs
Syntax var elements = document.getElementsByName(name); elements is a live NodeList Collection, meaning it automatically updates as new elements with the same name are added to/removed from the document. name is the value of the name attribute of the element(s). Example <!DOCTYPE html> <html lang="en"> <title>Example: using document.getElementsByName</title> <input type="hidden" name="up"> <input type="hidden" name="down"> <script> var up_names = document.getElementsByName("up"); console.log(up_names[0].tagName); // displays "INPUT" </script> </html> Notes The name attribute can only be applied in (X)HTML documents. ...
...sole.log(up_names[0].tagName); // displays "INPUT" </script> </html> Notes The name attribute can only be applied in (X)HTML documents. The returned NodeList Collection contains all elements with the given name, such as <meta>, <object>, and even elements which do not support the name attribute at all. The getElementsByName method works differently in IE10 and below. There, getElementsByName
() also returns elements that have an id attribute with the specified value. Be careful not to use the same string as both a name and an id. The getElementsByName method works differently in IE. There, getElementsByName
() does not return all elements which may not have a name attribute (such as <span>). Both IE and Edge return an HTMLCollection, not a NodeList Specifications Specif...
...tring as both a name and an id. The getElementsByName method works differently in IE. There, getElementsByName
() does not return all elements which may not have a name attribute (such as <span>). Both IE and Edge return an HTMLCollection, not a NodeList Specifications Specification Status Comment HTML Living StandardThe definition of 'Document.getElementsByName
()' in that specification. Living Standard Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'Document.getElementsByName
()' in that specification. Obsolete Initial definition ...
Document.mozSetImageElement() - Web APIs
Syntax document.mozSetImageElement(imageElementId, imageElement); Parameters imageElementId is a string indicating the name of an element that has been specified as a background image using the -moz-element CSS function. imageElement is the new element to use as the background corresponding to that image element string. Specify null to remove the background element. Example This example changes the background of a <div> block each time the block is clicked by the user. View this example live. ...
... time the block is clicked by the user. View this example live. <style type="text/css"> #mybox { background-image: -moz-element(#canvasbg); text-align: center; width: 400px; height: 400px; cursor: pointer; } </style> The CSS defined by the <style> block above is used by our <div> to use an element with the id "canvasbg" as its background. ...
...t. It creates a new <canvas> with the width and height set to 100 pixels, then draws into it a 50 by 50 pixel square. Each time the function is called, the square is a different color (its red component is increased each time), so each time the user clicks the element, the background is filled with a brighter and brighter pattern of red tiles. Once the canvas is drawn, document.mozSetImageElement
() is called to set the background for any CSS using the ID "canvasbg" as its background element ID to be our new canvas. Specifications Not part of any specification. ...
Document.queryCommandState() - Web APIs
The queryCommandState
() method will tell you if the current selection has a certain Document.execCommand
() command applied. Syntax queryCommandState(String command) Parameters command is a command from Document.execCommand
() Return value queryCommandState
() can return a Boolean value or null if the state is unknown. ...
...od will tell you if the current selection has a certain Document.execCommand
() command applied. Syntax queryCommandState(String command) Parameters command is a command from Document.execCommand
() Return value queryCommandState
() can return a Boolean value or null if the state is unknown. ...
...mand applied. Syntax queryCommandState(String command) Parameters command is a command from Document.execCommand
() Return value queryCommandState
() can return a Boolean value or null if the state is unknown. ...
DocumentOrShadowRoot.caretPositionFromPoint() - Web APIs
Syntax var caretPosition = document.caretPositionFromPoint(float x, float y); Parameters x The horizontal coordinate of a point. y The vertical coordinate of a point. Returns A CaretPosition object. Example This example inserts line breaks wherever you click. The code for it is below the demo. Demo HTML Content <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. ...
... Working Draft Initial definition. ...
... Working Draft Initial definition. ...
DocumentTimeline.DocumentTimeline() - Web APIs
Syntax var sharedTimeline = new DocumentTimeline(options); Parameters options An object specifying options for the new timeline. Currently the only supported option is the originTime member which specifies the zero time for the documentTimeline as a real number of milliseconds relative to the navigationStart moment of the active document for the current browsing context. Examples We could share a single documentTimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. ...
... Working Draft Editor's draft. ...
... Working Draft Editor's draft. ...
DynamicsCompressorNode() - Web APIs
That can occur when multiple sounds are played and multiplexed together at once. Syntax var dynamicsCompressorNode = new DynamicsCompressorNode(context, options) Parameters context A reference to an AudioContext. options Optional Options are as follows: attack: The amount of time (in seconds) to reduce the gain by 10dB. Its default value is 0.003. This parameter is k-rate. Its nominal range is [0, 1]. ...
... the gain by 10dB. Its default value is 0.250. This parameter is k-rate. Its nominal range is [0, 1]. threshold: The decibel value above which the compression will start taking effect. Its default value is -24. This parameter is k-rate. Its nominal range is [-100, 0]. Specifications Specification Status Comment Web Audio APIThe definition of 'DynamicsCompressorNode
()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for...
...ser 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. ...
Element.closest() - Web APIs
Will return itself or the matching ancestor. If no such element exists, it returns null. Syntax var closestElement = targetElement.closest(selectors); Parameters selectors is a DOMString containing a selector list. ex: p:hover, .toto + q Return value closestElement is the Element which is the closest ancestor of the selected element. It may be null. Exceptions SyntaxError is thrown if the selectors is not a valid selector list string. ...
...v"); // returns the closest ancestor which is a div in div, here it is the div-03 itself var r3 = el.closest("article > div"); // returns the closest ancestor which is a div and has a parent article, here it is the div-01 var r4 = el.closest(":not(div)"); // returns the closest ancestor which is not a div, here it is the outmost article Polyfill For browsers that do not support Element.closest
(), but carry support for element.matches
() (or a prefixed equivalent, meaning IE9+), a polyfill exists: if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector; } if (!Element.prototype.closest) { Element.prototype.closest = function(s) { var el = this; do { if (Element.prototype.matche...
... Living Standard Initial definition. ...
Element.getAttribute() - Web APIs
The getAttribute
() method of the Element interface returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string); see Non-existing attributes for details. Syntax let attribute = element.getAttribute(attributeName); where attribute is a string containing the value of attributeName. attributeName is the name of the attribute whose value you want to get. Examples const div1 = document.getElementById('div1'); const align = div1.getAttribute('align'); alert(align); // Shows the value of align for the element with id="div1" Description Lower casing When called on an HTML element in a DOM flagged as an HTML document, getAttribute
() lower-cases its argument before proceeding. Non-exis...
...r, and iCab, as a non-exhaustive list) return null when the specified attribute does not exist on the specified element; this is what the current DOM specification draft specifies. The old DOM 3 Core specification, on the other hand, says that the correct return value in this case is actually the empty string, and some DOM implementations implement this behavior. The implementation of getAttribute
() in XUL (Gecko) actually follows the DOM 3 Core specification and returns an empty string. Consequently, you should use element.hasAttribute
() to check for an attribute's existence prior to calling getAttribute
() if it is possible that the requested attribute does not exist on the specified element. Retrieving nonce values For security reasons, CSP nonces from non-script sources, such as CSS sel...
... Living Standard ...
Element.getElementsByTagNameNS() - Web APIs
It is similar to Document.getElementsByTagNameNS, except that its search is restricted to descendants of the specified element. Syntax elements = element.getElementsByTagNameNS(namespaceURI, localName) elements is a live HTMLCollection of found elements in the order they appear in the tree. element is the element from where the search should start. Note that only the descendants of this element are included in the search, not the node itself. namespaceURI is the namespace URI of elements to look for (see Element.namespaceURI and Attr.namespaceURI). ...
... Obsolete No change from Document Object Model (DOM) Level 2 Core Specification. Document Object Model (DOM) Level 2 Core SpecificationThe def...
... if (axis == "year") { // grab the data } } Specifications Specification Status Comment DOMThe definition of 'Element.getElementsByTagNameNS
()' in that specification. Living Standard Changed the return value from NodeList to HTMLCollection. Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Element.getElementsByTagNameNS
()' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification. Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Element.getElementsByTagNameNS
()' in that specification. Obsolete Initial definition ...
Element.hasAttribute() - Web APIs
Syntax var result = element.hasAttribute(name); result holds the return value true or false. name is a string representing the name of the attribute. ...
... Obsolete No change from Document Object Model (DOM) Level 2 Core Specification Document Object Model (DOM) Level 2 Core S...
...OM 1) removeAttributeNS removeAttributeNode - Specifications Specification Status Comment DOMThe definition of 'Element.hasAttribute
()' in that specification. Living Standard From Document Object Model (DOM) Level 3 Core Specification, moved from Node to Element Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Element.hasAttribute
()' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Element.hasAttribute
()' in that specification. Obsolete Initial definition. ...
Element.insertAdjacentHTML() - Web APIs
It does not reparse the element it is being used on, and thus it does not corrupt the existing elements inside that element. This avoids the extra step of serialization, making it much faster than direct innerHTML manipulation. Syntax element.insertAdjacentHTML(position, text); Parameters position A DOMString representing the position relative to the element; must be one of the following strings: 'beforebegin': Before the element itself. 'afterbegin': Just inside the element, before its first child. 'beforeend': Just inside the element, after its last child. ...
...positions work only if the node is in the DOM tree and has a parent element. Example // <div id="one">one</div> var d1 = document.getElementById('one'); d1.insertAdjacentHTML('afterend', '<div id="two">two</div>'); // At this point, the new structure is: // <div id="one">one</div><div id="two">two</div> Notes Security considerations When inserting HTML into a page by using insertAdjacentHTML
(), be careful not to use user input that hasn't been escaped. It is not recommended you use insertAdjacentHTML
() when inserting plain text; instead, use the Node.textContent property or the Element.insertAdjacentText
() method. This doesn't interpret the passed content as HTML, but instead inserts it as raw text. Specification Specification Status Comment DOM Parsing a...
... It is not recommended you use insertAdjacentHTML
() when inserting plain text; instead, use the Node.textContent property or the Element.insertAdjacentText
() method. This doesn't interpret the passed content as HTML, but instead inserts it as raw text. Specification Specification Status Comment DOM Parsing and SerializationThe definition of 'Element.insertAdjacentHTML
()' in that specification. Working Draft ...
Element.querySelector() - Web APIs
Syntax element = baseElement.querySelector(selectors); Parameters selectors A group of selectors to match the descendant elements of the Element baseElement against; this must be valid CSS syntax, or a SyntaxError exception will occur. The first element found which matches this group of selectors is returned. Return value The first descendant element of baseElement which matches the specified group of selectors. ...
... matching, including those outside the set of elements including baseElement and its descendants; in other words, selectors is first applied to the whole document, not the baseElement, to generate an initial list of potential elements. The resulting elements are then examined to see if they are descendants of baseElement. The first match of those remaining elements is returned by the querySelector
() method. If no matches are found, the returned value is null. Exceptions SyntaxError The specified selectors are invalid. Examples Let's consider a few examples. Find a specific element with specific values of an attribute In this first example, the first <style> element which either has no type or has type "text/css" in the HTML document body is returned: var el = document.body.queryS...
...erySelector("p"); document.getElementById("output").innerHTML = (baseElement.querySelector("div span").innerHTML); Result The result looks like this: Notice how the "div span" selector still successfully matches the <span> element, even though the baseElement's child nodes do not include the div element (it is still part of the specified selector). More examples See Document.querySelector
() for additional examples of the proper format for the selectors. Specifications Specification Status Comment DOMThe definition of 'querySelector
()' in that specification. Living Standard Selectors API Level 2The definition of 'querySelectorAll
()' in that specification. Obsolete Selectors API Level 1The definition of 'querySelectorAll(...
Element.scrollIntoView() - Web APIs
Corresponds to scrollIntoViewOptions: {block: "start", inline: "nearest"}. This is the default value. If false, the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor. ...
...behavior Optional Defines the transition animation. One of auto or smooth. Defaults to auto. block Optional Defines vertical alignment. One of start, center, end, or nearest. Defaults to start. inline Optional Defines horizontal alignment. One of start, center, end, or nearest. Defaults to nearest. Example var element = document.getElementById("box"); element.scrollIntoView
(); element.scrollIntoView(false); element.scrollIntoView({block: "end"}); element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"}); Notes The element may not be scrolled completely to the top or bottom depending on the layout of other elements. Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'Ele...
... Working Draft Initial definition ...
Element.scrollIntoViewIfNeeded() - Web APIs
Syntax TODO Parameters opt_center Is an optional Boolean value with a default value of true: If true, the element will be aligned so it is centered within the visible area of the scrollable ancestor. If false, the element will be aligned to the nearest edge of the visible area of the scrollable ancestor. ...
... Syntax TODO Parameters opt_center Is an optional Boolean value with a default value of true: If true, the element will be aligned so it is centered within the visible area of the scrollable ancestor. If false, the element will be aligned to the nearest edge of the visible area of the scrollable ancestor. ...
... nearest edge of the visible area of the scrollable ancestor. Depending on which edge of the visible area is closest to the element, either the top of the element will be aligned to the top edge of the visible area, or the bottom edge of the element will be aligned to the bottom edge of the visible area. Example var element = document.getElementById("my-el"); element.scrollIntoViewIfNeeded
(); element.scrollIntoViewIfNeeded(true); // Centers the element in the visible area Specifications Not part of any specification. This is a proprietary, WebKit-specific method. ...
Element.setAttributeNode() - Web APIs
Syntax var replacedAttr = element.setAttributeNode(attribute); attribute is the Attr node to set on the element. replacedAttr is the replaced attribute node, if any, returned by this function. Example This example copies the align attribute from one element to another. ...
...= document.getElementById('one'); let d2 = document.getElementById('two'); let a = d1.getAttributeNode('align'); d2.setAttributeNode(a.cloneNode(true)); // Returns: 'left' alert(d2.attributes[1].value); Notes If the attribute named already exists on the element, that attribute is replaced with the new one and the replaced one is returned. This method is seldom used, with Element.setAttribute
() usually being used to change element's attributes. DOM methods dealing with element's attributes: Not namespace-aware, most commonly used methods Namespace-aware variants (DOM Level 2) DOM Level 1 methods for dealing with Attr nodes directly (seldom used) DOM Level 2 namespace-aware methods for dealing with Attr nodes directly (seldom used) setAttribute (DOM 1) setAttributeNS setAttribute...
... Living Standard ...
Element.setCapture() - Web APIs
Warning: This interface never had much cross-browser support and you probably looking for element.setPointerCapture instead, from the Pointer Events API. Syntax element.setCapture(retargetToElement); retargetToElement If true, all events are targeted directly to this element; if false, events can also fire at descendants of this element. ...
...le In this example, the current mouse coordinates are drawn while you mouse around after clicking and holding down on an element. ...
...= document.getElementById("myButton"); if (btn.setCapture) { btn.addEventListener("mousedown", mouseDown, false); btn.addEventListener("mouseup", mouseUp, false); } else { document.getElementById("output").innerHTML = "Sorry, there appears to be no setCapture support on this browser"; } } function mouseDown(e) { e.target.setCapture
(); e.target.addEventListener("mousemove", mouseMoved, false); } function mouseUp(e) { e.target.removeEventListener("mousemove", mouseMoved, false); } function mouseMoved(e) { var output = document.getElementById("output"); output.innerHTML = "Position: " + e.clientX + ", " + e.clientY; } </script> </head> <body onload="init
()"> <p>This is an example...
File.getAsBinary() - Web APIs
lete since Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Summary The getAsBinary method allows to access the file's data in raw binary format. Note: This method is obsolete; you should use the FileReader method readAsBinaryString
() or readAsArrayBuffer
() instead. Syntax var binary = instanceOfFile.getAsBinary
(); Returns A string. Example // fileInput is an HTMLInputElement: <input type="file" id="myfileinput" multiple> var fileInput = document.getElementById("myfileinput"); // files is a FileList object (similar to NodeList) var files = fileInput.files; // object for allowed media types var accept = { binary : ["...
... ...
... ...
File.getAsDataURL() - Web APIs
Summary The getAsDataURL provides a data: URL that encodes the entire contents of the referenced file. Note: This method is obsolete; you should use the FileReader method readAsDataURL
() instead. ...
... Summary The getAsDataURL provides a data: URL that encodes the entire contents of the referenced file. Note: This method is obsolete; you should use the FileReader method readAsDataURL
() instead. ...
... ...
FileReader() - Web APIs
The FileReader
() constructor creates a new FileReader. For details about how to use FileReader, see Using files from web applications. Syntax var reader = new FileReader
(); Parameters None. ...
... The FileReader
() constructor creates a new FileReader. For details about how to use FileReader, see Using files from web applications. Syntax var reader = new FileReader
(); Parameters None. ...
... The FileReader
() constructor creates a new FileReader. For details about how to use FileReader, see Using files from web applications. Syntax var reader = new FileReader
(); Parameters None. ...
FileSystemEntry.getParent() - Web APIs
Syntax FileSystemEntry.getParent(successCallback[, errorCallback]); Parameters successCallback A function which is called when the parent directory entry has been retrieved. The callback receives a single input parameter: a FileSystemDirectoryEntry object representing the parent directory. The parent of the root directory is considered to be the root directory, itself, so be sure to watch for that. errorCallback Optional An optional callback which is executed if an error occurs. There's a single parameter: a FileError describing what went wrong. Return value undefined. ...
...nt, "newname.html", function(updatedEntry) { console.log("File " + fileEntry.name + " renamed to newname.html."); }); }, function(error) { console.error("An error occurred: Unable to rename " + fileEntry.name + " to newname.html."); }); This is accomplished by first obtaining a FileSystemDirectoryEntry object representing the directory the file is currently located in. Then moveTo
() is used to rename the file within that directory. Using promises Currently, there isn't a Promise-based version of this method. You can, however, create a simple helper function to adapt it, like this: function getParentPromise(entry) { return new Promise((resolve, reject) => { entry.getParent(resolve, reject); }); } A similar approach can be taken elsewhere in the File and Directory ...
...er, create a simple helper function to adapt it, like this: function getParentPromise(entry) { return new Promise((resolve, reject) => { entry.getParent(resolve, reject); }); } A similar approach can be taken elsewhere in the File and Directory Entries API. Specifications Specification Status Comment File and Directory Entries APIThe definition of 'getParent
()' in that specification. Draft Initial specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for Andro...
FontFace.FontFace() - Web APIs
The FontFace
() constructor creates a new FontFace object. Syntax var fontFace = new FontFace(family, source, descriptors); Parameters family Specifies a name that will be used as the font face value for font properties. Takes the same type of values as the font-family descriptor of @font-face . source The font source. This can be either: A URL Binary font data descriptors Optional A set of optional descriptors passed as an object. ...
...ptor of @font-face . source The font source. This can be either: A URL Binary font data descriptors Optional A set of optional descriptors passed as an object. ...
...al A set of optional descriptors passed as an object. It can have the following keys: family: Family style: Style weight: Weight stretch: Stretch unicodeRange: Unicode range variant: variant featureSettings: Feature settings Example async function loadFonts
() { const font = new FontFace('myfont', 'url(myfont.woff)'); // wait for font to be loaded await font.load
(); // add font to document document.fonts.add(font); // enable font with CSS class document.body.classList.add('fonts-loaded'); } Specifications Specification Status Comment CSS Font Loading Module Level 3The definition of 'FontFace Constructor' in that specification. Working Draft Initial definition ...
FormData() - Web APIs
The FormData
() constructor creates a new FormData object. Note: This feature is available in Web Workers. Syntax var formData = new FormData(form) Parameters form Optional An HTML <form> element -- when specified, the FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content. ...
...mData = new FormData(form) Parameters form Optional An HTML <form> element -- when specified, the FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content. ...
...Note: Only successful form controls are included in a FormData object, i.e. those with a name, not disabled and checked (radio buttons and checkboxes) or selected (one or more options within a select). let myForm = document.getElementById('myForm'); let formData = new FormData(myForm); Specifications Specification Status Comment XMLHttpRequestThe definition of 'FormData
()' in that specification. Living Standard Initial definition ...
FormData.append() - Web APIs
Note: This method is available in Web Workers. Syntax There are two versions of this method: a two and a three parameter version: formData.append(name, value); formData.append(name, value, filename); Parameters name The name of the field whose data is contained in value. value The field's value. This can be a USVString or Blob (including subclasses such as File). ...
...e for Blob objects is "blob". The default filename for File objects is the file's filename. Note: If you specify a Blob as the data to append to the FormData object, the filename that will be reported to the server in the "Content-Disposition" header used to vary from browser to browser. Returns Void. Example The following line creates an empty FormData object: var formData = new FormData
(); // Currently empty You can add key/value pairs to this using FormData.append: formData.append('username', 'Chris'); formData.append('userpic', myFileInput.files[0], 'chris.jpg'); As with regular form data, you can append multiple values with the same name. For example (and being compatible with PHP's naming conventions by adding [] to the name): formData.append('userpic[]', myFileInput.files...
... data structure is more conducive to looping. If the sent value is different than String or Blob it will be automatically converted to String: formData.append('name', true); formData.append('name', 74); formData.append('name', 'John'); formData.getAll('name'); // ["true", "74", "John"] Specifications Specification Status Comment XMLHttpRequestThe definition of 'append
()' in that specification. Living Standard Initial definition ...
FormData.getAll() - Web APIs
The getAll
() method of the FormData interface returns all the values associated with a given key from within a FormData object. Note: This method is available in Web Workers. Syntax formData.getAll(name); Parameters name A USVString representing the name of the key you want to retrieve. Returns An array of FormDataEntryValues whose key matches the value passed in the name parameter. If the key doesn't exist, the method returns an empty list. ...
... available in Web Workers. Syntax formData.getAll(name); Parameters name A USVString representing the name of the key you want to retrieve. Returns An array of FormDataEntryValues whose key matches the value passed in the name parameter. If the key doesn't exist, the method returns an empty list. ...
...rns An array of FormDataEntryValues whose key matches the value passed in the name parameter. If the key doesn't exist, the method returns an empty list. Example The following line creates an empty FormData object: var formData = new FormData
(); If we add two username values using FormData.append: formData.append('username', 'Chris'); formData.append('username', 'Bob'); The following getAll
() function will return both username values in an array: formData.getAll('username'); // Returns ["Chris", "Bob"] Specifications Specification Status Comment XMLHttpRequestThe definition of 'getAll
()' in that specification. Living Standard ...
FormData.has() - Web APIs
The has
() method of the FormData interface returns a boolean stating whether a FormData object contains a certain key. Note: This method is available in Web Workers. Syntax formData.has(name); Parameters name A USVString representing the name of the key you want to test for. Returns A Boolean. ...
... The has
() method of the FormData interface returns a boolean stating whether a FormData object contains a certain key. Note: This method is available in Web Workers. Syntax formData.has(name); Parameters name A USVString representing the name of the key you want to test for. Returns A Boolean. ...
... Living Standard ...
FormData.set() - Web APIs
Note: This method is available in Web Workers. Syntax There are two versions of this method: a two and a three parameter version: formData.set(name, value); formData.set(name, value, filename); Parameters name The name of the field whose data is contained in value. value The field's value. This can be a USVString or Blob (including subclasses such as File). ...
... default filename for Blob objects is "blob". The default filename for File objects is the file's filename. Note: If you specify a Blob as the data to append to the FormData object, the filename that will be reported to the server in the "Content-Disposition" header used to vary from browser to browser. ...
... Living Standard ...
HTMLCanvasElement.captureStream() - Web APIs
Return value A reference to a MediaStream object, which has a single CanvasCaptureMediaStreamTrack in it. Exceptions NotSupportedError The value of frameRate is negative. ...
...nvas's contents. Syntax MediaStream = canvas.captureStream(frameRate); Parameters frameRate Optional A double-precision floating-point value that indicates the rate of capture of each frame. If not set, a new frame will be captured each time the canvas changes; if set to 0, frames will not be captured automatically; instead, they will only be captured when the returned track's requestFrame
() method is called. Return value A reference to a MediaStream object, which has a single CanvasCaptureMediaStreamTrack in it. Exceptions NotSupportedError The value of frameRate is negative. Example // Find the canvas element to capture var canvasElt = document.querySelector('canvas'); // Get the stream var stream = canvasElt.captureStream(25); // 25 FPS // Do things to the stream // E...
... Working Draft Initial definition ...
HTMLElement.click() - Web APIs
The HTMLElement.click
() method simulates a mouse click on an element. When click
() is used with supported elements (such as an <input>), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events. ...
... The HTMLElement.click
() method simulates a mouse click on an element. When click
() is used with supported elements (such as an <input>), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events. ...
.... When click
() is used with supported elements (such as an <input>), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events. Syntax element.click
() Example Simulate a mouse-click when moving the mouse pointer over a checkbox: HTML <form> <input type="checkbox" id="myCheck" onmouseover="myFunction
()" onclick="alert('click event occured')"> </form> JavaScript // On mouse-over, execute myFunction function myFunction
() { document.getElementById("myCheck").click
(); } Specification Specification Status Comment HTML Living Standard Living Standard Document Object Model (DOM) Level 2 HTML Specification Obsolete Initial definition. ...
HTMLHyperlinkElementUtils.toString() - Web APIs
The HTMLHyperlinkElementUtils.toString
() stringifier method returns a USVString containing the whole URL. It is a read-only version of HTMLHyperlinkElementUtils.href. ...
... The HTMLHyperlinkElementUtils.toString
() stringifier method returns a USVString containing the whole URL. It is a read-only version of HTMLHyperlinkElementUtils.href. ...
...ing
() stringifier method returns a USVString containing the whole URL. It is a read-only version of HTMLHyperlinkElementUtils.href. ...
HTMLInputElement.setRangeText() - Web APIs
Syntax element.setRangeText(replacement); element.setRangeText(replacement, start, end [, selectMode]); Parameters replacement The string to insert. start Optional The 0-based index of the first character to replace. Defaults to the current selectionStart value (the start of the user's current selection). end Optional The 0-based index of the character after the last character to replace. Defaults to the current selectionEnd value (the end of the user's current selection). selectMode Optional A string defining how the selection should be set after the text has been replaced. ...
...oves the selection to just after the inserted text. "preserve" attempts to preserve the selection. This is the default. Example Click the button in this example to replace part of the text in the text box. The newly inserted text will be highlighted (selected) afterwards. HTML <input type="text" id="text-box" size="30" value="This text has NOT been updated."> <button onclick="selectText
()">Update text</button> JavaScript function selectText
() { const input = document.getElementById('text-box'); input.focus
(); input.setRangeText('ALREADY', 14, 17, 'select'); } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLInputElement.setSelectionRange
()' in that specification. Living Standard No change ...
...t input = document.getElementById('text-box'); input.focus
(); input.setRangeText('ALREADY', 14, 17, 'select'); } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLInputElement.setSelectionRange
()' in that specification. Living Standard No change HTML5The definition of 'HTMLInputElement.setSelectionRange
()' in that specification. Recommendation Initial definition ...
HTMLSelectElement.item() - Web APIs
In JavaScript, using the array bracket syntax with an unsigned long, like selectElt[index] is equivalent to selectElt.namedItem(index). Syntax var item = collection.item(index); var item = collection[index]; Parameters index is an unsigned long. Return value item is a HTMLOptionElement. ...
... Recommendation Initial definition, snapshot of HTML Living Standard ...
... Recommendation Initial definition, snapshot of HTML Living Standard ...
HTMLSelectElement.remove() - Web APIs
Syntax collection.remove(index); Parameters index is a long for the index of the HTMLOptionElement to remove from the collection. If the index is not found the method has no effect. ...
... Obsolete Document Object Model (DOM) Level 1 Specificatio...
... <select id="existingList" name="existingList"> <option value="1">Option: Value 1</option> <option value="3">Option: Value 3</option> </select> */ Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLSelectElement.remove
()' in that specification. Living Standard HTML5The definition of 'HTMLSelectElement.remove
()' in that specification. Recommendation Is a snapshot of HTML Living Standard. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLSelectElement.remove
()' in that specification. Obsolete Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLSelectElement.remove
()' in that specification. Obsolete Initial definition. ...
HTMLVideoElement.getVideoPlaybackQuality() - Web APIs
Example This example updates an element to indicate the total number of video frames that have elapsed so far in the playback process. ...
... Example This example updates an element to indicate the total number of video frames that have elapsed so far in the playback process. ...
... Example This example updates an element to indicate the total number of video frames that have elapsed so far in the playback process. This value includes any dropped or corrupted frames, so it's not the same as "total number of frames played." var videoElem = document.getElementById("my_vid"); var counterElem = document.getElementById("counter"); var quality = videoElem.getVideoPlaybackQuality
(); counterElem.innerText = quality.totalVideoFrames; Specifications Specification Status Comment Media Playback QualityThe definition of 'HTMLVideoElement.getVideoPlaybackQuality
()' in that specification. Editor's Draft Initial definition. ...
Headers.delete() - Web APIs
The delete
() method of the Headers interface deletes a header from the current Headers object. This method throws a TypeError for the following reasons: The value of the name parameter is not the name of an HTTP header. The value of Guard is immutable. For security reasons, some headers can only be controller by the user agent. These headers include the forbidden header names and forbidden response header names. Syntax myHeaders.delete(name); Parameters name The name of the HTTP header you want to delete from the Headers object. Returns Void. ...
...mmutable. For security reasons, some headers can only be controller by the user agent. These headers include the forbidden header names and forbidden response header names. Syntax myHeaders.delete(name); Parameters name The name of the HTTP header you want to delete from the Headers object. Returns Void. ...
... Living Standard ...
Headers.entries() - Web APIs
The Headers.entries
() method returns an iterator allowing to go through all key/value pairs contained in this object. The both the key and value of each pairs are ByteString objects. Note: This method is available in Web Workers. Syntax headers.entries
(); Return value Returns an iterator. ...
... The Headers.entries
() method returns an iterator allowing to go through all key/value pairs contained in this object. The both the key and value of each pairs are ByteString objects. Note: This method is available in Web Workers. Syntax headers.entries
(); Return value Returns an iterator. ...
...the key and value of each pairs are ByteString objects. Note: This method is available in Web Workers. Syntax headers.entries
(); Return value Returns an iterator. ...
Headers.getAll() - Web APIs
Obsolete since Gecko 52 (Firefox 52 / Thunderbird 52 / SeaMonkey 2.49)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. The getAll
() method of the Headers interface used to return an array of all the values of a header within a Headers object with a given name; in newer versions of the Fetch spec, it has been deleted, and Headers.get
() has been updated to fetch all header values instead of only the first one. If the requested header doesn't exist in the Headers object, it returns an empty array. For security reasons, some headers can only be controller by the user agent. These headers include the forbidden header names and forbidden response header names. Syntax myHeaders.
...yHeaders.getAll(name); Parameters name The name of the HTTP header whose values you want to retrieve from the Headers object. If the given name is not the name of an HTTP header, this method throws a TypeError. Returns An Array containing a ByteString sequence representing the values of the retrieved header. ...
...from the Headers object. If the given name is not the name of an HTTP header, this method throws a TypeError. Returns An Array containing a ByteString sequence representing the values of the retrieved header. ...
Headers.keys() - Web APIs
The Headers.keys
() method returns an iterator allowing to go through all keys contained in this object. The keys are ByteString objects. Note: This method is available in Web Workers. Syntax headers.keys
(); Return value Returns an iterator. ...
... The Headers.keys
() method returns an iterator allowing to go through all keys contained in this object. The keys are ByteString objects. Note: This method is available in Web Workers. Syntax headers.keys
(); Return value Returns an iterator. ...
...hrough all keys contained in this object. The keys are ByteString objects. Note: This method is available in Web Workers. Syntax headers.keys
(); Return value Returns an iterator. ...
Headers.values() - Web APIs
The Headers.values
() method returns an iterator allowing to go through all values contained in this object. The values are ByteString objects. Note: This method is available in Web Workers. Syntax headers.values
(); Return value Returns an iterator. ...
... The Headers.values
() method returns an iterator allowing to go through all values contained in this object. The values are ByteString objects. Note: This method is available in Web Workers. Syntax headers.values
(); Return value Returns an iterator. ...
...lues contained in this object. The values are ByteString objects. Note: This method is available in Web Workers. Syntax headers.values
(); Return value Returns an iterator. ...
History.forward() - Web APIs
Living Standard No change from HTML5. ...
... Living Standard No change from HTML5. ...
... Living Standard No change from HTML5. HTML5The definition of 'History' in that specification. ...
History.replaceState() - Web APIs
This method is particularly useful when you want to update the state object or URL of the current history entry in response to some user action. Syntax history.replaceState(stateObj, title, [url]) Parameters stateObj The state object is a JavaScript object which is associated with the history entry passed to the replaceState method. The state object can be null. title Most browsers currently ignore this parameter, although they may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state. ...
...e. url Optional The URL of the history entry. The new URL must be of the same origin as the current URL; otherwise replaceState throws an exception. Examples Suppose https://www.mozilla.org/foo.html executes the following JavaScript: const stateObj = { foo: 'bar' }; history.pushState(stateObj, '', 'bar.html'); The explanation of these two lines above can be found in the Example of pushState
() method section of the Working with the History API article. Then suppose https://www.mozilla.org/bar.html executes the following JavaScript: history.replaceState(stateObj, '', 'bar2.html'); This will cause the URL bar to display https://www.mozilla.org/bar2.html, but won't cause the browser to load bar2.html or even check that bar2.html exists. Suppose now that the user navigates to https://ww...
...ser navigates to https://www.microsoft.com, then clicks the Back button. At this point, the URL bar will display https://www.mozilla.org/bar2.html. If the user now clicks Back again, the URL bar will display https://www.mozilla.org/foo.html, and totally bypass bar.html. Specifications Specification Status Comment HTML Living StandardThe definition of 'History.replaceState
()' in that specification. Living Standard No change from HTML5. HTML5The definition of 'History.replaceState
()' in that specification. Recommendation Initial definition. ...
IDBFactory.open() - Web APIs
The method returns an IDBOpenDBRequest object immediately, and performs the open operation asynchronously. If the operation is successful, a success event is fired on the request object that is returned from this method, with its result attribute set to the new IDBDatabase object for the connection. If an error occurs while the database connection is being opened, then an error event is fired on the request object returned from this method. May trigger upgradeneeded, blocked or versionchange events. Note: This feature is available in Web Workers. ...
...ion and storage) Optional In Gecko, since version 26, you can include a non-standard options object as a parameter of IDBFactory.open that contains the version number of the database, plus a storage value that specifies whether you want to use persistent or temporary storage. Warning: The storage attribute is deprecated and will soon be removed from Gecko. You should use StorageManager.persist
() to get persistent storage instead. Note: You can find out more information on the different available storage types, and how Firefox handles client-side data storage, at Browser storage limits and eviction criteria. Return value A IDBOpenDBRequest object on which subsequent events related to this request are fired. Exceptions This method may raise a DOMException of the following types: ...
... DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db // variable. This is used a lot later on, for opening // transactions and suchlike. db = DBOpenRequest.result; }; Specifications Specification Status Comment Indexed Database API 2.0The definition of 'open
()' in that specification. Recommendation Indexed Database API DraftThe definition of 'open
()' in that specification. Recommendation Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobi...
IDBKeyRange.only() - Web APIs
Note: This feature is available in Web Workers. Syntax var myIDBKeyRange = IDBKeyRange.only(value); Parameters value is the value for the new key range. Return value IDBKeyRange: The newly created key range. Exceptions This method may raise a DOMException of the following types: Exception Description DataError The value parameter passed was not a valid key. Example The following example illustrates how you'd use an only key range. Here we declare a keyRangeValue = IDBKeyRange.only("A"); -- a range that only includes the value "A". ...
...n (using IDBTransaction) and an object store, and open a Cursor with IDBObjectStore.openCursor, declaring keyRangeValue as its optional key range value. This means that the cursor will only retrieve the record with the key value "A". ...
... Recommendation Indexed Database API DraftThe definition of 'only' in that specification. Recommendation Browser compatibility The compatibili...
IDBObjectStore.getAll() - Web APIs
The getAll
() method of the IDBObjectStore interface returns an IDBRequest object containing all objects in the object store matching the specified parameter or all objects in the store if no parameters are given. If a value is successfully found, then a structured clone of it is created and set as the result of the request object. This method produces the same result for: a record that doesn't exist in the database a record that has an undefined value To tell these situations apart, you either call the openCursor
() method with the same key. That method provides a cursor if the record exists, and no cursor if it does not. the count
() method with the same key, which will return 1 if the row exists and 0 if it doesn't. ...
...a record that doesn't exist in the database a record that has an undefined value To tell these situations apart, you either call the openCursor
() method with the same key. That method provides a cursor if the record exists, and no cursor if it does not. the count
() method with the same key, which will return 1 if the row exists and 0 if it doesn't. Syntax var request = objectStore.getAll
(); var request = objectStore.getAll(query); var request = objectStore.getAll(query, count); Parameters query Optional A key or IDBKeyRange to be queried. If nothing is passed, this will default to a key range that selects all the records in this object store. count Optional Specifies the number of values to return if more than one is found. If it is lower than 0 or greater than 232-1 a TypeE...
... Recommendation Initial definition ...
IDBObjectStore.getAllKeys() - Web APIs
The getAllKeys
() method of the IDBObjectStore interface returns an IDBRequest object retrieves record keys for all objects in the object store matching the specified parameter or all objects in the store if no parameters are given. If a value is successfully found, then a structured clone of it is created and set as the result of the request object. This method produces the same result for: a record that doesn't exist in the database a record that has an undefined value To tell these situations apart, you need to call the openCursor
() method with the same key. That method provides a cursor if the record exists, and no cursor if it does not. ...
...eated and set as the result of the request object. This method produces the same result for: a record that doesn't exist in the database a record that has an undefined value To tell these situations apart, you need to call the openCursor
() method with the same key. That method provides a cursor if the record exists, and no cursor if it does not. Syntax var request = objectStore.getAllKeys
(); var request = objectStore.getAllKeys(query); var request = objectStore.getAllKeys(query, count); Parameters query Optional A value that is or resolves to an IDBKeyRange. count Optional Specifies the number of values to return if more than one is found. If it is lower than 0 or greater than 232-1 a TypeError exception will be thrown. Return value An IDBRequest object on which subsequent...
... Recommendation Initial definition ...
IDBObjectStore.getKey() - Web APIs
This is for retrieving specific records from an object store. If a key is successfully found, then a structured clone of it is created and set as the result of the request object. Note: This feature is available in Web Workers. Syntax var request = objectStore.getKey(key); Parameters key The key or key range that identifies the record to be retrieved. Return Value An IDBRequest object on which subsequent events related to this operation are fired. ...
... inactive. DataError The key or key range provided contains an invalid key. InvalidStateError The IDBObjectStore has been deleted or removed. ...
...ains an invalid key. InvalidStateError The IDBObjectStore has been deleted or removed. Example let openRequest = indexedDB.open("telemetry"); openRequest.onsuccess = (event) => { let db = event.target.result; let store = db.transaction("netlogs").objectStore("netlogs"); let today = new Date
(); let yesterday = new Date(today); yesterday.setDate(today.getDate
() - 1); let request = store.getKey(IDBKeyRange(yesterday, today)); request.onsuccess = (event) => { let when = event.target.result; alert("The 1st activity in last 24 hours was occurred at " + when); }; }; Specifications Specification Status Comment Indexed Database API DraftThe definition of 'getKey
()' in that specification. Recommendation Initial defi...
IIRFilterNode() - Web APIs
Syntax var iIRFilterNode = new IIRFilterNode(context, options) Parameters Inherits parameters from the AudioNodeOptions dictionary. context A reference to an AudioContext. options Options are as follows: feedforward: A sequence of feedforward coefficients. feedback: A sequence of feedback coefficients. Unlike other nodes in the Web Audio API, the options passed into the IIR filter upon creation are not optional. The filter needs these values to work and with the vast range of filters available, there is no default. Return value A new IIRFilterNode object instance. ...
...nal. The filter needs these values to work and with the vast range of filters available, there is no default. Return value A new IIRFilterNode object instance. Examples let feedForward = [0.00020298, 0.0004059599, 0.00020298]; let feedBackward = [1.0126964558, -1.9991880801, 0.9873035442]; const AudioContext = window.AudioContext || window.webkitAudioContext; const audioCtx = new AudioContext
(); const iirFilter = new IIRFilterNode(audioCtx, { feedforward: feedForward, feedback: feedBackward }); Specifications Specification Status Comment Web Audio APIThe definition of 'IIRFilterNode
()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd li...
... 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. ...
IntersectionObserver.observe() - Web APIs
When the visibility of the specified element crosses over one of the observer's visibility thresholds (as listed in IntersectionObserver.thresholds), the observer's callback is executed with an array of IntersectionObserverEntry objects representing the intersection changes which occurred. ...
... When the visibility of the specified element crosses over one of the observer's visibility thresholds (as listed in IntersectionObserver.thresholds), the observer's callback is executed with an array of IntersectionObserverEntry objects representing the intersection changes which occurred. ...
...Element An element whose visibility within the root is to be monitored. This element must be a descendant of the root element (or contained wtihin the current document, if the root is the document's viewport). Return value undefined. Examples <<<...>>> Specifications Specification Status Comment Intersection ObserverThe definition of 'IntersectionObserver.observe
()' in that specification. Working Draft Initial definition. ...
KeyboardEvent.initKeyEvent() - Web APIs
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The KeyboardEvent.initKeyEvent
() method is used to initialize the value of an event created using document.createEvent("KeyboardEvent"). Events initialized in this way must have been created with the document.createEvent("KeyboardEvent") method. initKeyEvent
() must be called to set the event before it is dispatched. Do not use this method anymore, use the KeyboardEvent
() constructor instead. This method is based on early drafts of Document Object Model (DOM) Level 2 Events Specification and is...
... 0); // charCodeArg); document.getElementById('blah').dispatchEvent(event); Specification This implementation of keyboard events is based on the key events spec in the early versions of DOM 2 Events, later removed from that spec. ...
... // charCodeArg); document.getElementById('blah').dispatchEvent(event); Specification This implementation of keyboard events is based on the key events spec in the early versions of DOM 2 Events, later removed from that spec. ...
KeyframeEffect.setKeyframes() - Web APIs
element.animate([ { // from opacity: 0, color: "#fff" }, { // to opacity: 1, color: "#000" } ], 2000); Offsets for each keyframe can be specified by providing an offset value. ...
...rames. Syntax existingKeyframeEffect.setKeyframes(keyframes); Parameters keyframes A keyframe object or null. If set to null, the keyframes are replaced with a sequence of empty keyframes. There are two different ways to format keyframes: An array of objects (keyframes) consisting of properties and values to iterate over. This is the canonical format returned by the getKeyframes
() method. element.animate([ { // from opacity: 0, color: "#fff" }, { // to opacity: 1, color: "#000" } ], 2000); Offsets for each keyframe can be specified by providing an offset value. element.animate([ { opacity: 1 }, { opacity: 0.1, offset: 0.7 }, { opacity: 0 } ], 2000); Note: offset values, if provided,...
... Working Draft Editor's draft. ...
Location: toString() - Web APIs
The toString
() stringifier method of the Location interface returns a USVString containing the whole URL. It is a read-only version of Location.href. ...
... The toString
() stringifier method of the Location interface returns a USVString containing the whole URL. It is a read-only version of Location.href. ...
...he toString
() stringifier method of the Location interface returns a USVString containing the whole URL. It is a read-only version of Location.href. ...
MediaCapabilities.decodingInfo() - Web APIs
Syntax mediaCapabilities.decodingInfo(MediaDecodingConfiguration) Parameters MediaDecodingConfiguration A valid MediaDecodingConfiguration dictionary containing a valid media decoding type of file or media-source and a valid media configuration: either an AudioConfiguration or a VideoConfiguration. ...
... dictionary containing a valid media decoding type of file or media-source and a valid media configuration: either an AudioConfiguration or a VideoConfiguration. Return value A Promise fulfilling with a MediaCapabilitiesInfo interface containing three Boolean attributes: supported smooth powerEfficient Exceptions A TypeError is raised if the MediaConfiguration passed to the decodingInfo
() method is invalid, either because the type is not video or audio, the contentType is not a valid codec MIME type, the media decoding configuration is not a valid value for the media decoding type, or any other error in the media configuration passed to the method, including omitting values required in the media decoding configuration. Example //Create media configuration to be tested...
... Draft Initial definition ...
MediaCapabilities.encodingInfo() - Web APIs
Syntax mediaCapabilities.encodingInfo(mediaEncodingConfiguration) Parameters mediaEncodingConfiguration A valid MediaEncodingConfiguration dictionary containing a valid media encoding type of record or transmission and a valid media configuration: either an AudioConfiguration or VideoConfiguration dictionary. ...
... containing a valid media encoding type of record or transmission and a valid media configuration: either an AudioConfiguration or VideoConfiguration dictionary. Return value A Promise fulfilling with a MediaCapabilitiesInfo interface containing three Boolean attributes: supported smooth powerEfficient Exceptions A TypeError is raised if the MediaConfiguration passed to the encodingInfo
() method is invalid, either because the type is not video or audio, the contentType is not a valid codec MIME type, or any other error in the media configuration passed to the method, including omitting any of the media encoding configuration elements. Example //Create media configuration to be tested const mediaConfig = { type : 'record', // or 'transmission' video : { ...
... Draft Initial definition ...
MediaDevices.getSupportedConstraints() - Web APIs
Return value A new object based on the MediaTrackSupportedConstraints dictionary listing the constraints supported by the user agent. Because only constraints supported by the user agent are included in the list, each of these Boolean properties has the value true. Example This example outputs a list of the constraints supported by your browser. ...
...e true. Example This example outputs a list of the constraints supported by your browser. ...
... Candidate Recommendation Initial definition. ...
MediaRecorder.resume() - Web APIs
The MediaRecorder.resume
() method (part of the MediaRecorder API) is used to resume media recording when it has been previously paused. When the resume
() method is invoked, the browser queues a task that runs the following steps: If MediaRecorder.state is "inactive", raise a DOM InvalidState error and terminate these steps. If MediaRecorder.state is not "inactive", continue to the next step. Set MediaRecorder.state to "recording". Continue gathering data into the current Blob. Raise a resume event. ...
... the resume
() method is invoked, the browser queues a task that runs the following steps: If MediaRecorder.state is "inactive", raise a DOM InvalidState error and terminate these steps. If MediaRecorder.state is not "inactive", continue to the next step. Set MediaRecorder.state to "recording". Continue gathering data into the current Blob. Raise a resume event. Syntax MediaRecorder.resume
() Errors An InvalidState error is raised if the resume
() method is called while the MediaRecorder object's MediaRecorder.state is "inactive" -- the recording cannot be resumed if it is not already paused; if MediaRecorder.state is already "recording", resume
() has no effect. Example ... ...
...ata into the current Blob. Raise a resume event. Syntax MediaRecorder.resume
() Errors An InvalidState error is raised if the resume
() method is called while the MediaRecorder object's MediaRecorder.state is "inactive" -- the recording cannot be resumed if it is not already paused; if MediaRecorder.state is already "recording", resume
() has no effect. Example ... pause.onclick = function
() { if(MediaRecorder.state === "recording") { mediaRecorder.pause
(); // recording paused } else if(MediaRecorder.state === "paused") { mediaRecorder.resume
(); // resume recording } } ... Specifications Specification Status Comment MediaStream RecordingThe definition of 'MediaRecorder.resume
()' in that specification. Working Draft ...
MediaSession.setActionHandler() - Web APIs
These actions let a web app receive notifications when the user engages a device's built-in physical or onscreen media controls, such as play, stop, or seek buttons. Syntax navigator.mediaSession.setActionHandler(type, callback) Parameters type A DOMString representing an action type to listen for. It will be one of play, pause, seekbackward, seekforward, seekto, skipad,previoustrack, or nexttrack. Further details on the action types can be found below under Media session actions. callback A function to call when the specified action type is invoked. The callback receives no input parameters, and should not return a value. Return value undefined. ...
...eekforward, seekto, skipad,previoustrack, or nexttrack. Further details on the action types can be found below under Media session actions. callback A function to call when the specified action type is invoked. The callback receives no input parameters, and should not return a value. Return value undefined. Description To remove a previously-established action handler, call setActionHandler
() again, specifying null as the callback. The action handler receives as input a single parameter: an object conforming to the MediaSessionActionDetails dictionary, which provides both the action type (so the same function can handle multiple action types), as well as data needed in order to perform the action. Media session actions A media session action's type is specified using a string from ...
... Specifications Specification Status Comment Media Session StandardThe definition of 'Media Session action types' in that specification. Draft Initial definition. ...
MediaStream.getAudioTracks() - Web APIs
The getAudioTracks
() method of the MediaStream interface returns a sequence that represents all the MediaStreamTrack objects in this stream's track set where MediaStreamTrack.kind is audio. Syntax var mediaStreamTracks = mediaStream.getAudioTracks
() Parameters None. Return value An array of MediaStreamTrack objects, one for each audio track contained in the stream. Audio tracks are those tracks whose kind property is audio. The array is empty if the stream contains no audio tracks. Note: The order of the returned tracks is not defined by the specification and may, in fact, change from one call to getAudioTracks
() to the next. Early versions of this API included a special AudioStreamTrack interface which was used as the type for each entry in the list of audio streams; however, thi...
...the specification and may, in fact, change from one call to getAudioTracks
() to the next. Early versions of this API included a special AudioStreamTrack interface which was used as the type for each entry in the list of audio streams; however, this has since been merged into the main MediaStreamTrack interface. Example This example gets a webcam's audio and video in a stream using getUserMedia
(), attaches the stream to a <video> element, then sets a timer that, upon expiring, will stop the first audio track found on the stream. ...
...s a webcam's audio and video in a stream using getUserMedia
(), attaches the stream to a <video> element, then sets a timer that, upon expiring, will stop the first audio track found on the stream. navigator.mediaDevices.getUserMedia({audio: true, video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream; // Stop the audio stream after 5 seconds setTimeout(
() => { const tracks = mediaStream.getAudioTracks
() tracks[0].stop
() }, 5000) }) Specifications Specification Status Comment Media Capture and StreamsThe definition of 'getAudioTracks
()' in that specification. Candidate Recommendation Initial definition. ...
MediaStream.getVideoTracks() - Web APIs
The getVideoTracks
() method of the MediaStream interface returns a sequence of MediaStreamTrack objects representing the video tracks in this stream. Syntax var mediaStreamTracks[] = mediaStream.getVideoTracks
(); Parameters None. Return value An array of MediaStreamTrack objects, one for each video track contained in the media stream. Video tracks are those tracks whose kind property is video. The array is empty if the stream contains no video tracks. Note: The order of the tracks is not defined by the specification, and may not be the same from one call to getVideoTracks
() to another. Early versions of this API included a special VideoStreamTrack interface which was used as the type for each entry in the list of video streams; however, this has since been merged into the main Med...
...be the same from one call to getVideoTracks
() to another. Early versions of this API included a special VideoStreamTrack interface which was used as the type for each entry in the list of video streams; however, this has since been merged into the main MediaStreamTrack interface. Example The following example, extracted from Chrome's Image Capture / Photo Resolution Sample, uses getVideoTracks
() to retrieve a track for passing to the ImageCapture
() constructor. ...
...rack interface. Example The following example, extracted from Chrome's Image Capture / Photo Resolution Sample, uses getVideoTracks
() to retrieve a track for passing to the ImageCapture
() constructor. var imageCapture; navigator.mediaDevices.getUserMedia({video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream; const track = mediaStream.getVideoTracks
()[0]; imageCapture = new ImageCapture(track); return imageCapture.getPhotoCapabilities
(); }) Specifications Specification Status Comment Media Capture and StreamsThe definition of 'getVideoTracks
()' in that specification. Candidate Recommendation Initial definition. ...
MediaStreamTrack.applyConstraints() - Web APIs
Constraints can be used to ensure that the media meets certain guidelines you prefer. For example, you may prefer high-density video but require that the frame rate be a little low to help keep the data rate low enough not overtax the network. Constraints can also specify ideal and/or acceptable sizes or ranges of sizes. See Applying constraints in Capabilities, constraints, and settings for more information on how to apply your preferred constraints. ...
...t is not available. Note that these constraints also illustrate what the spec refers to as a backoff strategy. const constraints = { width: {min: 640, ideal: 1280}, height: {min: 480, ideal: 720}, advanced: [ {width: 1920, height: 1280}, {aspectRatio: 1.333} ] }; navigator.mediaDevices.getUserMedia({ video: true }) .then(mediaStream => { const track = mediaStream.getVideoTracks
()[0]; track.applyConstraints(constraints) .then(
() => { // Do something with the track such as using the Image Capture API. }) .catch(e => { // The constraints could not be satisfied by the available devices. }); }); Specifications Specification Status Comment Media Capture and StreamsThe definition of 'applyConstraints
()' in that specification. Candi...
...Image Capture API. }) .catch(e => { // The constraints could not be satisfied by the available devices. }); }); Specifications Specification Status Comment Media Capture and StreamsThe definition of 'applyConstraints
()' in that specification. Candidate Recommendation Initial definition. MediaStream Image CaptureThe definition of 'applyConstraints
()' in that specification. Working Draft Adds image constraints. ...
MediaStreamTrackEvent() - Web APIs
type A DOMString representing the name of the type of the MediaStreamTrackEvent. It is case-sensitive and can be "addtrack" or "removetrack". track A MediaStreamTrack object representing the track which was added to or removed from the stream. Return value A new MediaStreamTrackEvent, initialized based on the provided options. ...
... type A DOMString representing the name of the type of the MediaStreamTrackEvent. It is case-sensitive and can be "addtrack" or "removetrack". track A MediaStreamTrack object representing the track which was added to or removed from the stream. Return value A new MediaStreamTrackEvent, initialized based on the provided options. ...
...TrackEvent. It is case-sensitive and can be "addtrack" or "removetrack". track A MediaStreamTrack object representing the track which was added to or removed from the stream. Return value A new MediaStreamTrackEvent, initialized based on the provided options. Specifications Specification Status Comment Media Capture and StreamsThe definition of 'MediaStreamTrackEvent
()' in that specification. Candidate Recommendation ...
MerchantValidationEvent() - Web APIs
You should not have to create these events yourself; instead, just handle the merchantvalidation event. Syntax merchantValidationEvent = new MerchantValidationEvent(type, options); Parameters type A DOMString which must be merchantvalidation, the only type of event which uses the MerchantValidationEvent interface. options Optional An optional dictionary which may contain zero or more of the following properties: methodName Optional A DOMString containing the payment method identifier for the payment handler being used. This is an empty string by default. ...
...ed. This is an empty string by default. validationURL Optional The URL from which to retrieve payment handler specific verification information used to validate the merchant. This is an empty string by default. Return value A newly-created MerchantValidationEvent providing the information that needs to be delivered to the client-side code to present to the user agent by calling complete
(). ...
...y calling complete
(). Exceptions TypeError The string specified as validationURL could not be parsed as a URL. RangeError The specified methodName does not correspond to a known and supported merchant or is not a well-formed standard payment method identifier. Specifications Specification Status Comment Payment Request APIThe definition of 'MerchantValidationEvent
()' in that specification. Candidate Recommendation Initial definition. ...
NDEFReader.scan() - Web APIs
Return value A Promise that resolves with undefined immediatelly after scheduling read operations for the NFC adapter. ...
...e NFC devices, e.g., NDEF NFC tags. Syntax var readerPromise = NDEFReader.scan(options); Parameters options Optional id -- the match pattern for matching each NDEFRecord.id. recordType -- the match pattern for matching each NDEFRecord.recordType. mediaType -- the match pattern for matching each NDEFRecord.mediaType. signal -- optional AbortSignal that allows to cancell this scan
() operation. Return value A Promise that resolves with undefined immediatelly after scheduling read operations for the NFC adapter. Exceptions This method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a DOMException whose name is one of the following: AbortError The scan operation was aborted with AbortSignal passed in options. NotAllowedErro...
... ...
Navigator.getGamepads() - Web APIs
%d buttons, %d axes.", gp.index, gp.id, gp.buttons.length, gp.axes.length ); }); Specifications Specification Status Comment GamepadThe definition of 'The Gamepad API specification' in that specification. ...
...%d buttons, %d axes.", gp.index, gp.id, gp.buttons.length, gp.axes.length ); }); Specifications Specification Status Comment GamepadThe definition of 'The Gamepad API specification' in that specification. ...
...%d buttons, %d axes.", gp.index, gp.id, gp.buttons.length, gp.axes.length ); }); Specifications Specification Status Comment GamepadThe definition of 'The Gamepad API specification' in that specification. ...
Navigator.registerProtocolHandler() - Web APIs
For example, this API lets webmail sites open mailto: URLs, or VoIP sites open tel: URLs. Syntax navigator.registerProtocolHandler(scheme, url, title); Note: Recently updated to navigator.registerProtocolHandler(scheme, url), but no browsers currently support this version. Parameters scheme A string containing the protocol the site wishes to handle. For example, you can register to handle SMS text message links by passing the "sms" scheme. url A string containing the URL of the handler. ...
...he browser handles itself (https:, about:, etc.) The handler URL's origin does not match the origin of the page calling this API. The browser requires that this function is called from a secure context. The browser requires that the handler's URL be over HTTPS. SyntaxError The %s placeholder is missing from the handler URL. Permitted schemes For security reasons, registerProtocolHandler
() restricts which schemes can be registered. A custom scheme may be registered as long as: The custom scheme's name begins with web+ The custom scheme's name includes at least 1 letter after the web+ prefix The custom scheme has only lowercase ASCII letters in its name. For example, web+burger, as shown in the Example below. Otherwise, the scheme must be one of the following: bitcoin ...
...tps://burgers.example.com), and the handler URL must be http or https. The user will be notified that your code asked to register the protocol handler, so that they can decide whether or not to allow it. See the screenshot below for an example on google.co.uk: Specifications Specification Status Comment HTML Living StandardThe definition of 'registerProtocolHandler
()' in that specification. Living Standard Living standard ...
Navigator.requestMediaKeySystemAccess() - Web APIs
The Navigator.requestMediaKeySystemAccess
() method returns a Promise which delivers a MediaKeySystemAccess object that can be used to access a particular media key system, which can in turn be used to create keys for decrypting a media stream. This method is part of the Encrypted Media Extensions API, which brings support for encrypted media and DRM-protected video to the web. This method may have user-visible effects such as asking for permission to access one or more system resources. Consider that when deciding when to call requestMediaKeySystemAccess
(); you don't want those requests to happen at inconvenient times. As a general rule, this function should be called only when it's about time to create and use a MediaKeys object by calling the returned MediaKeySystemAccess object's create...
... Syntax Promise = Navigator.requestMediaKeySystemAccess(keySystem, supportedConfigurations); Parameters keySystem A DOMString identifying the key system. For example com.example.somesystem or org.w3.clearkey. ...
... Recommendation Initial definition ...
Node.compareDocumentPosition() - Web APIs
The return value is a bitmask of the following values: Name Value DOCUMENT_POSITION_DISCONNECTED 1 DOCUMENT_POSITION_PRECEDING 2 DOCUMENT_POSITION_FOLLOWING 4 DOCUMENT_POSITION_CONTAINS 8 DOCUMENT_POSITION_CONTAINED_BY 16 DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC 32 Syntax compareMask = node.compareDocumentPosition(otherNode) Parameters otherNode The other Node with which to compare the first node's document position. ...
...cumentPosition(otherNode) Parameters otherNode The other Node with which to compare the first node's document position. Return value An integer value whose bits represent the otherNode's relationship to the calling node. More than one bit is set if multiple scenarios apply. For example, if otherNode is located earlier in the document and contains the node on which compareDocumentPosition
() was called, then both the DOCUMENT_POSITION_CONTAINS and DOCUMENT_POSITION_PRECEDING bits would be set, producing a value of 10 (0x0A). Example const head = document.head; const body = document.body; if (head.compareDocumentPosition(body) & Node.DOCUMENT_POSITION_FOLLOWING) { console.log('Well-formed document'); } else { console.error('<head> is not before <body>'); } Note: Because the ...
...ON_CONTAINS and DOCUMENT_POSITION_PRECEDING bits would be set, producing a value of 10 (0x0A). Example const head = document.head; const body = document.body; if (head.compareDocumentPosition(body) & Node.DOCUMENT_POSITION_FOLLOWING) { console.log('Well-formed document'); } else { console.error('<head> is not before <body>'); } Note: Because the result returned by compareDocumentPosition
() is a bitmask, the bitwise AND operator must be used for meaningful results. Specifications Specification Status Comment DOMThe definition of 'Node.compareDocumentPosition
()' in that specification. Living Standard Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.compareDocumentPosition
()' in that specification. Obsolete ...
Node.normalize() - Web APIs
The Node.normalize
() method puts the specified node and all of its sub-tree into a "normalized" form. In a normalized sub-tree, no text nodes in the sub-tree are empty and there are no adjacent text nodes. ...
... The Node.normalize
() method puts the specified node and all of its sub-tree into a "normalized" form. In a normalized sub-tree, no text nodes in the sub-tree are empty and there are no adjacent text nodes. ...
...no adjacent text nodes. Syntax element.normalize
(); Example let wrapper = document.createElement("div"); wrapper.appendChild( document.createTextNode("Part 1 ") ); wrapper.appendChild( document.createTextNode("Part 2 ") ); // At this point, wrapper.childNodes.length === 2 // wrapper.childNodes[0].textContent === "Part 1 " // wrapper.childNodes[1].textContent === "Part 2 " wrapper.normalize
(); // Now, wrapper.childNodes.length === 1 // wrapper.childNodes[0].textContent === "Part 1 Part 2 " Specifications Specification Status Comment DOMThe definition of 'Node: normalize' in that specification. Living Standard ...
Node.setUserData() - Web APIs
This method offers the convenience of associating data with specific nodes without needing to alter the structure of a document and in a standard fashion, but it also means that extra steps may need to be taken if one wishes to serialize the information or include the information upon clone, import, or rename operations. ...
... This method offers the convenience of associating data with specific nodes without needing to alter the structure of a document and in a standard fashion, but it also means that extra steps may need to be taken if one wishes to serialize the information or include the information upon clone, import, or rename operations. ...
... Obsolete Initial definition ...
NodeIterator.detach() - Web APIs
The NodeIterator.detach
() method is a no-op, kept for backward compatibility only. Originally, it detached the NodeIterator from the set over which it iterates, releasing any resources used by the set and setting the iterator's state to INVALID. Once this method had been called, calls to other methods on NodeIterator would raise the INVALID_STATE_ERR exception. ...
... The NodeIterator.detach
() method is a no-op, kept for backward compatibility only. Originally, it detached the NodeIterator from the set over which it iterates, releasing any resources used by the set and setting the iterator's state to INVALID. Once this method had been called, calls to other methods on NodeIterator would raise the INVALID_STATE_ERR exception. ...
...ing the iterator's state to INVALID. Once this method had been called, calls to other methods on NodeIterator would raise the INVALID_STATE_ERR exception. Syntax nodeIterator.detach
(); Example var nodeIterator = document.createNodeIterator( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); nodeIterator.detach
(); // detaches the iterator nodeIterator.nextNode
(); // throws an INVALID_STATE_ERR exception Specifications Specification Status Comment DOMThe definition of 'NodeIterator.detach' in that specification. Living Standard Transformed in a no-op Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'NodeIterator.detach' in tha...
NodeIterator.nextNode() - Web APIs
The NodeIterator.nextNode
() method returns the next node in the set represented by the NodeIterator and advances the position of the iterator within the set. The first call to nextNode
() returns the first node in the set. This method returns null when there are no nodes left in the set. In old browsers, as specified in old versions of the specifications, the method may throws the INVALID_STATE_ERR DOMException if this method is called after the NodeIterator.detach
()method. Recent browsers never throw. ...
...n the set. The first call to nextNode
() returns the first node in the set. This method returns null when there are no nodes left in the set. In old browsers, as specified in old versions of the specifications, the method may throws the INVALID_STATE_ERR DOMException if this method is called after the NodeIterator.detach
()method. Recent browsers never throw. ...
...ethod is called after the NodeIterator.detach
()method. Recent browsers never throw. Syntax node = nodeIterator.nextNode
(); Example var nodeIterator = document.createNodeIterator( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false // this optional argument is not used any more ); currentNode = nodeIterator.nextNode
(); // returns the next node Specifications Specification Status Comment DOMThe definition of 'NodeIterator.nextNode' in that specification. Living Standard As detach
() is now a no-op method, this method cannot throw anymore. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'NodeIterator.nextNode' in that specification. ...
NodeIterator.previousNode() - Web APIs
The NodeIterator.previousNode
() method returns the previous node in the set represented by the NodeIterator and moves the position of the iterator backwards within the set. This method returns null when the current node is the first node in the set. In old browsers, as specified in old versions of the specifications, the method may throws the INVALID_STATE_ERR DOMException if this method is called after the NodeIterator.detach
()method. Recent browsers never throw. ...
...moves the position of the iterator backwards within the set. This method returns null when the current node is the first node in the set. In old browsers, as specified in old versions of the specifications, the method may throws the INVALID_STATE_ERR DOMException if this method is called after the NodeIterator.detach
()method. Recent browsers never throw. ...
...d is called after the NodeIterator.detach
()method. Recent browsers never throw. Syntax node = nodeIterator.previousNode
(); Example var nodeIterator = document.createNodeIterator( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false // this optional argument is not used any more ); currentNode = nodeIterator.nextNode
(); // returns the next node previousNode = nodeIterator.previousNode
(); // same result, since we backtracked to the previous node Specifications Specification Status Comment DOMThe definition of 'NodeIterator.previousNode' in that specification. Living Standard As detach
() is now a no-op method, this method cannot throw anymore. Document Object Model (DOM) ...
NodeList.prototype.forEach() - Web APIs
thisArg Optional Value to use as this when executing callback. Return value undefined. ...
...e list, in insertion order. Syntax someNodeList.forEach(callback[, thisArg]); Parameters callback A function to execute on each element of someNodeList. It accepts 3 parameters: currentValue The current element being processed in someNodeList. currentIndex Optional The index of the currentValue being processed in someNodeList. listObj Optional The someNodeList that forEach
() is being applied to. thisArg Optional Value to use as this when executing callback. Return value undefined. Example let node = document.createElement("div"); let kid1 = document.createElement("p"); let kid2 = document.createTextNode("hey"); let kid3 = document.createElement("span"); node.appendChild(kid1); node.appendChild(kid2); node.appendChild(kid3); let list = node.childNodes; l...
... Specifications Specification Status Comment Web IDLThe definition of 'forEach' in that specification. Candidate Recommendation Defines forEach on iterable declarations Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://gith...
Notification.Notification() - Web APIs
Syntax var myNotification = new Notification(title, options); Parameters title Defines a title for the notification, which is shown at the top of the notification window. options Optional An options object containing any custom settings that you want to apply to the notification. The possible options are: dir: The direction in which to display the notification. ...
...itself. The action's name is sent to the service worker notification handler to let it know the action was selected by the user. silent: A Boolean specifying whether the notification is silent (no sounds or vibrations issued), regardless of the device settings. The default is false, which means it won't be silent. Example In our Emogotchi demo (see source code), we run a spawnNotification
() function when we want to trigger a notification. The function is passed parameters to specify the body, icon, and title we want, and then it creates the necessary options object and triggers the notification by using the Notification
() constructor. function spawnNotification(theBody,theIcon,theTitle) { var options = { body: theBody, icon: theIcon } var n = new Notification(theT...
...it creates the necessary options object and triggers the notification by using the Notification
() constructor. function spawnNotification(theBody,theIcon,theTitle) { var options = { body: theBody, icon: theIcon } var n = new Notification(theTitle,options); } Specifications Specification Status Comment Notifications APIThe definition of 'Notification
() constructor' in that specification. Living Standard Initial definition. ...
OES_vertex_array_object.createVertexArrayOES() - Web APIs
// calls to bindBuffer or vertexAttribPointer // which will be "recorded" in the VAO // ... ...
...// calls to bindBuffer or vertexAttribPointer // which will be "recorded" in the VAO // ... ...
...// calls to bindBuffer or vertexAttribPointer // which will be "recorded" in the VAO // ... ...
OffscreenCanvas.getContext() - Web APIs
Note: This API is currently implemented for WebGL1 and WebGL2 contexts only. See bug 801176 for Canvas 2D API support from workers. Syntax offscreen.getContext(contextType, contextAttributes); Parameters contextType Is a DOMString containing the context identifier defining the drawing context associated to the canvas. Possible values are: "2d" creates a CanvasRenderingContext2D object representing a two-dimensional rendering context. "webgl" creates a WebGLRenderingContext object representing a three-dimensional rendering context. ...
...pha channel. If set to false, the browser now knows that the backdrop is always opaque, which can speed up drawing of transparent content and images then. (Gecko only) willReadFrequently: Boolean that indicates whether or not a lot of read-back operations are planned. This will force the use of a software (instead of hardware accelerated) 2D canvas and can save memory when calling getImageData
() frequently. This option is only available, if the flag gfx.canvas.willReadFrequently.enable is set to true (which, by default, is only the case for B2G/Firefox OS). (Blink only) storage: String that indicates which storage is used ("persistent" by default). WebGL context attributes: alpha: Boolean that indicates if the canvas contains an alpha buffer. depth: Boolean that indicates t...
...ext for "bitmaprenderer". If the contextType doesn't match a possible drawing context, null is returned. Examples var offscreen = new OffscreenCanvas(256, 256); var gl = offscreen.getContext("webgl"); gl; // WebGLRenderingContext gl.canvas; // OffscreenCanvas Specifications Specification Status Comment HTML Living StandardThe definition of 'OffscreenCanvas.getContext
()' in that specification. Living Standard ...
OscillatorNode.setPeriodicWave() - Web APIs
The setPeriodicWave
() method of the OscillatorNode interface is used to point to a PeriodicWave defining a periodic waveform that can be used to shape the oscillator's output, when type is custom. This replaces the now-obsolete OscillatorNode.setWaveTable
(). Syntax OscillatorNode.setPeriodicWave(wave); Parameters wave A PeriodicWave object representing the waveform to use as the shape of the oscillator's output. Returns undefined Example The following example illustrates simple usage of createPeriodicWave
(), recreating a sine wave from a periodic wave. ...
...yntax OscillatorNode.setPeriodicWave(wave); Parameters wave A PeriodicWave object representing the waveform to use as the shape of the oscillator's output. Returns undefined Example The following example illustrates simple usage of createPeriodicWave
(), recreating a sine wave from a periodic wave. var real = new Float32Array(2); var imag = new Float32Array(2); var ac = new AudioContext
(); var osc = ac.createOscillator
(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createPeriodicWave(real, imag); osc.setPeriodicWave(wave); osc.connect(ac.destination); osc.start
(); osc.stop(2); This works because a sound that contains only a fundamental tone is by definition a sine wave. Here, we create a PeriodicWave with two values. The first value is the DC offset,...
... values. The first value is the DC offset, which is the value at which the oscillator starts. 0 is good here, because we want to start the curve at the middle of the [-1.0; 1.0] range. The second and subsequent values are sine and cosine components. You can think of it as the result of a Fourier transform, where you get frequency domain values from time domain value. Here, with createPeriodicWave
(), you specify the frequencies, and the browser performs a an inverse Fourier transform to get a time domain buffer for the frequency of the oscillator. Here, we only set one component at full volume (1.0) on the fundamental tone, so we get a sine wave. Specifications Specification Status Comment Web Audio APIThe definition of 'setPeriodicWave' in that specification. Wo...
Path2D() - Web APIs
The Path2D
() constructor returns a newly instantiated Path2D object, optionally with another path as an argument (creates a copy), or optionally with a string consisting of SVG path data. Syntax new Path2D
(); new Path2D(path); new Path2D(d); Parameters path Optional When invoked with another Path2D object, a copy of the path argument is created. d Optional When invoked with a string consisting of SVG path data, a new path is created from that description. Examples Creating and copying paths This example creates and copies a Path2D path. ...
...h2D object, a copy of the path argument is created. d Optional When invoked with a string consisting of SVG path data, a new path is created from that description. Examples Creating and copying paths This example creates and copies a Path2D path. <canvas id="canvas"></canvas> const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let path1 = new Path2D
(); path1.rect(10, 10, 100,100); let path2 = new Path2D(path1); path2.moveTo(220, 60); path2.arc(170, 60, 50, 0, 2 * Math.PI); ctx.stroke(path2); Using SVG paths This example creates a Path2D path using SVG path data. The path will move to point (M10 10) and then move horizontally 80 points to the right (h 80), then 80 points down (v 80), then 80 points to the left (h -80), and then back to t...
... Living Standard Initial definition. ...
PaymentAddress.toJSON() - Web APIs
Candidate Recommendation Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... Candidate Recommendation Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
...ion. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternettoJSON
()Chrome Full support 61Disabled Full support 61Disabled Disabled From version 61: this feature is behind the #web-payments preference (needs to be set to Enabled). To change preferences in Chrome, visit chrome://flags.Edge Full support 15Firefox Ful...
PaymentRequest.PaymentRequest() - Web APIs
Syntax var paymentRequest = new PaymentRequest(methodData, details, [options]); Parameters methodData Contains an array of identifiers for the payment methods the merchant web site accepts and any associated payment method specific data. Each item in the array contains the following fields: supportedMethods For early implementations of the spec, this was a sequence of identifiers for payment methods that the merchant website accepts. ...
...mount', amount: {currency: 'USD', value: '65.00'} } ], shippingOptions: [ { id: 'standard', label: 'Standard shipping', amount: {currency: 'USD', value: '0.00'}, selected: true } ] }; var options = {requestShipping: true}; try { var request = new PaymentRequest(supportedInstruments, details, options); // Add event listeners here. // Call show
() to trigger the browser's payment flow. request.show
().then(function(instrumentResponse) { // Do something with the response from the UI. }) .catch(function(err) { // Do something with the error from request.show
(). }); } catch (e) { // Catch any other errors. } Specifications Specification Status Comment Payment Request APIThe definition of 'PaymentRequ...
... trigger the browser's payment flow. request.show
().then(function(instrumentResponse) { // Do something with the response from the UI. }) .catch(function(err) { // Do something with the error from request.show
(). }); } catch (e) { // Catch any other errors. } Specifications Specification Status Comment Payment Request APIThe definition of 'PaymentRequest
() constructor' in that specification. Candidate Recommendation Initial definition. ...
PaymentRequestUpdateEvent.updateWith() - Web APIs
For address field specific errors, use shippingAddressErrors. ...
...eWith(details); Parameters details A PaymentDetailsUpdate object specifying the changes applied to the payment request: displayItems Optional An array of PaymentItem objects, each describing one line item for the payment request. These represent the line items on a receipt or invoice. error Optional A DOMString specifying an error message to present to the user. When calling updateWith
(), including error in the updated data causes the user agent to display the text as a general error message. For address field specific errors, use shippingAddressErrors. modifiers Optional An array of PaymentDetailsModifier objects, each describing a modifier for particular payment method identifiers. For example, you can use one to adjust the total payment amount based on the selected payment m...
...alculated automatically. You must update this value yourself anytime the total amount due changes. This lets you have flexibility for how to handle things like tax, discounts, and other adjustments to the total price charged. Return value undefined. Specifications Specification Status Comment Payment Request APIThe definition of 'PaymentRequestUpdateEvent.updateWith
()' in that specification. Candidate Recommendation Initial definition. ...
PerformanceObserver.takeRecords() - Web APIs
The takeRecords
() method of the PerformanceObserver interface returns the current list of performance entries stored in the performance observer, emptying it out. Syntax var PerformanceEntry[] = performanceObserver.takeRecords
(); Parameters None. Return value A list of PerformanceEntry objects. ...
...akeRecords
() method of the PerformanceObserver interface returns the current list of performance entries stored in the performance observer, emptying it out. Syntax var PerformanceEntry[] = performanceObserver.takeRecords
(); Parameters None. Return value A list of PerformanceEntry objects. ...
...eEntry[] = performanceObserver.takeRecords
(); Parameters None. Return value A list of PerformanceEntry objects. Example var observer = new PerformanceObserver(function(list, obj) { var entries = list.getEntries
(); for (var i=0; i < entries.length; i++) { // Process "mark" and "frame" events } }); observer.observe({entryTypes: ["mark", "frame"]}); var records = observer.takeRecords
(); console.log(records[0].name); console.log(records[0].startTime); console.log(records[0].duration); Specifications Specification Status Comment Performance Timeline Level 2The definition of 'takeRecords
()' in that specification. Candidate Recommendation Initial definition of takeRecords
() method. ...
Permissions.query() - Web APIs
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. ...
...n for every message or be able to send silent push notifications. The default is false. sysex: (Midi only) Indicates whether you need and/or receive system exclusive messages. The default is false. Note: As of Firefox 44, the permissions for Notifications and Push have been merged. If permission is granted (e.g. by the user, in the relevant permissions dialog), navigator.permissions.query
() will return true for both notifications and push. Note: The persistent-storage permission allows an origin to use a persistent box (i.e persistent storage) for its storage, as per the Storage API. Returns A Promise that resolves to a PermissionStatus object. Exceptions Exception Explanation TypeError Retrieving the PermissionDescriptor information failed in som...
... Exceptions Exception Explanation TypeError Retrieving the PermissionDescriptor information failed in some way, or the permission doesn't exist or is currently unsupported (e.g. midi, or push with userVisibleOnly). Example navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state == 'granted') { showLocalNewsWithGeolocation
(); } else if (result.state == 'prompt') { showButtonToEnableLocalNews
(); } // Don't do anything if the permission was denied. }); Specification Specification Status Comment PermissionsThe definition of 'query
()' in that specification. Working Draft Initial definition. ...
Permissions.revoke() - Web APIs
Syntax This method is called on the global Permissions object navigator.permissions. var revokePromise = navigator.permissions.revoke(descriptor); Parameters descriptor An object based on the PermissionDescriptor dictionary that sets options for the 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. Valid values are 'geolocation', 'midi', 'notifications', and 'push'. ...
...n for every message or be able to send silent push notifications. The default is false. sysex: (MIDI only) Indicates whether you need and/or receive system exclusive messages. The default is false. Note: As of Firefox 44, the permissions for Notifications and Push have been merged. If permission is granted (e.g. by the user, in the relevant permissions dialog), navigator.permissions.query
() will return true for both notifications and push. Note: The persistent-storage permission allows an origin to use a persistent box (i.e persistent storage) for its storage, as per the Storage API. Returns A Promise that calls its fulfillment handler with a PermissionStatus object indicating the result of the request. Exceptions TypeError Retrieving the PermissionDescriptor information ...
...th a PermissionStatus object indicating the result of the request. ...
PushEvent.PushEvent() - Web APIs
Note that the this constructor is exposed only to a service worker context. Syntax var myPushEvent = new PushEvent(type, eventInitDict); Parameters type A DOMString defining the type of PushEvent. This can be push or pushsubscriptionchange. eventInitDict Optional An options object containing any initialization data you want to populate the PushEvent object with. The options are: data: The data you want the PushEvent to contain, if any. When the constructor is invoked, the PushEvent.data property of the resulting object will be set to a new PushMessageData object containing bytes extracted from the eventInitDict data member. ...
...ions are: data: The data you want the PushEvent to contain, if any. When the constructor is invoked, the PushEvent.data property of the resulting object will be set to a new PushMessageData object containing bytes extracted from the eventInitDict data member. Example var dataInit = { data : 'Some sample text' } var myPushEvent = new PushEvent('push', dataInit); myPushEvent.data.text
(); // should return 'Some sample text' Browser Compatibility The compatibility table on this page is generated from structured data. 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 o...
...e text' 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 InternetPushEvent
() constructor ExperimentalChrome Full support 42Edge Full support 16Disabled Full support 16Disabled Disabled From version 16: this feature is behind the Enable service workers preference. Full support 17Firefox ...
PushManager.registrations() - Web APIs
The registrations method is used to ask the system about existing push endpoint registrations. Syntax var request = navigator.push.registrations
(); Return A DOMRequest object to handle the success or failure of the method call. If the method call is successful, the request's result will be an array of PushRegistration objects. PushRegistration Those objects are anonymous JavaScript objects with the following properties: pushEndpoint A string representing the URL of the endpoint. version The current version that the push endpoint is at. ...
...failure of the method call. If the method call is successful, the request's result will be an array of PushRegistration objects. PushRegistration Those objects are anonymous JavaScript objects with the following properties: pushEndpoint A string representing the URL of the endpoint. version The current version that the push endpoint is at. ...
... at. Example var req = navigator.push.registrations
(); req.onsuccess = function(e) { if (req.result.length > 0) { for (var i = 0, l = req.result.length; i < l; i++) { console.log("Existing registration", req.result[i].pushEndpoint, req.result[i].version); } // Reuse existing endpoints. } else { // Register for a new endpoint. var register = navigator.push.register
(); register.onsuccess = function(e) { console.log("Registered new endpoint", register.result); } } } Specification Specification Status Comment Push API Working Draft Defines the PushManager interface. ...
PushMessageData.arrayBuffer() - Web APIs
Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
PushMessageData.text() - Web APIs
Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
RTCDTMFSender.insertDTMF() - Web APIs
Syntax RTCDTMFSender.insertDTMF(tones[, duration[, interToneGap]]); Parameters tones A DOMString containing the DTMF codes to be transmitted to the recipient. Specifying an empty string as the tones parameter clears the tone buffer, aborting any currently queued tones. ...
... Syntax RTCDTMFSender.insertDTMF(tones[, duration[, interToneGap]]); Parameters tones A DOMString containing the DTMF codes to be transmitted to the recipient. Specifying an empty string as the tones parameter clears the tone buffer, aborting any currently queued tones. ...
... Candidate Recommendation ...
RTCIceTransport.getLocalCandidates() - Web APIs
Return value A JavaScript Array containing one RTCIceCandidate object for each candidate that has been identified so far during the ICE candidate gathering session. You can't correlate these local candidates with matching remote candidates. ...
...eCandidate objects, one for each of the candidates that have been gathered by the local device during the current ICE agent session. The local candidates are placed in this list by the ICE agent prior to being delivered to the local client's code in an icecandidate event so that the client can forward the candidates to the remote peer. Syntax localCandidates = RTCIceTransport.getLocalCandidates
(); Parameters None. Return value A JavaScript Array containing one RTCIceCandidate object for each candidate that has been identified so far during the ICE candidate gathering session. You can't correlate these local candidates with matching remote candidates. To find the best match found so far, call RTCIceTransport.getSelectedCandidatePair
(). Example This simple example gets the local cand...
... You can't correlate these local candidates with matching remote candidates. To find the best match found so far, call RTCIceTransport.getSelectedCandidatePair
(). Example This simple example gets the local candidate list from the RTCIceTransport for the first RTCRtpSender on the RTCPeerConnection, then outputs to the console all of the candidates in the list. var localCandidates = pc.getSenders
()[0].transport.transport.getLocalCandidates
(); localCandidates.forEach(function(candidate, index)) { console.log("Candidate " + index + ": " + candidate.candidate); }); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCIceCandidate.getLocalCandidates
()' in that specification. Candidate Recommendati...
RTCIceTransport.getLocalParameters() - Web APIs
Return value An RTCIceParameters object indicating the usernameFragment and password which uniquely identify the local peer for the duration of the ICE session. Returns null if the parameters have not yet been received. ...
... Return value An RTCIceParameters object indicating the usernameFragment and password which uniquely identify the local peer for the duration of the ICE session. Returns null if the parameters have not yet been received. ...
... Return value An RTCIceParameters object indicating the usernameFragment and password which uniquely identify the local peer for the duration of the ICE session. Returns null if the parameters have not yet been received. ...
RTCIceTransport.getRemoteParameters() - Web APIs
Return value An RTCIceParameters object indicating the usernameFragment and password which uniquely identify the remote peer for the duration of the ICE session. Returns null if the parameters haven't been received yet. ...
... Return value An RTCIceParameters object indicating the usernameFragment and password which uniquely identify the remote peer for the duration of the ICE session. Returns null if the parameters haven't been received yet. ...
... Return value An RTCIceParameters object indicating the usernameFragment and password which uniquely identify the remote peer for the duration of the ICE session. Returns null if the parameters haven't been received yet. ...
RTCPeerConnection.close() - Web APIs
Calling this method terminates the RTCPeerConnection's ICE agent, ending any ongoing ICE processing and any active streams. This also releases any resources in use by the ICE agent, including TURN permissions. All RTCRtpSender objects are considered to be stopped once this returns (they may still be in the process of stopping, but for all intents and purposes, they're stopped). Once this method returns, the signaling state as returned by RTCPeerConnection.signalingState is closed. ...
...nd purposes, they're stopped). Once this method returns, the signaling state as returned by RTCPeerConnection.signalingState is closed. Make sure that you delete all references to the previous RTCPeerConnection before attempting to create a new one that connects to the same remote peer, as not doing so might result in some errors depending on the browser. ...
... Make sure that you delete all references to the previous RTCPeerConnection before attempting to create a new one that connects to the same remote peer, as not doing so might result in some errors depending on the browser. Example var pc = new RTCPeerConnection
(); var dc = pc.createDataChannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); pc.close
(); // We decided to close after the first received message }; dc.onopen = function
() { console.log("datachannel open"); }; dc.onclose = function
() { console.log("datachannel close"); }; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.close
()' in that specification. Candidate...
RTCPeerConnection.getDefaultIceServers() - Web APIs
The getDefaultIceServers
() method of the RTCPeerConnection interface returns an array of objects based on the RTCIceServer dictionary, which indicates what, if any, ICE servers the browser will use by default if none are provided to the RTCPeerConnection in its RTCConfiguration. However, browsers are not required to provide any default ICE servers at all. Syntax var defaultIceServers = RTCPeerConnection.getDefaultIceServers
(); Return value An array of ICE servers, specified as objects based on RTCIceServer, which the browser will use if none are specified in the configuration of the RTCPeerConnection. If there are no defaults provided by the browser, the returned array is empty; this property's value is never null. ...
...r defaultIceServers = RTCPeerConnection.getDefaultIceServers
(); Return value An array of ICE servers, specified as objects based on RTCIceServer, which the browser will use if none are specified in the configuration of the RTCPeerConnection. If there are no defaults provided by the browser, the returned array is empty; this property's value is never null. ...
...efaultIceServers
(); Return value An array of ICE servers, specified as objects based on RTCIceServer, which the browser will use if none are specified in the configuration of the RTCPeerConnection. If there are no defaults provided by the browser, the returned array is empty; this property's value is never null. ...
RTCPeerConnection.getSenders() - Web APIs
The RTCPeerConnection method getSenders
() returns an array of RTCRtpSender objects, each of which represents the RTP sender responsible for transmitting one track's data. A sender object provides methods and properties for examining and controlling the encoding and transmission of the track's data. Syntax var senders = rtcPeerConnection.getSenders
(); Return value An array of RTCRtpSender objects, one for each track on the connection. The array is empty if there are no RTP senders on the connection. The order of the returned RTCRtpSenders is not defined by the specification, and may change from one call to getSenders
() to the next. Example In this example, a setMuting
() function is shown. This function takes as input an RTCPeerConnection, pc, and a Boolean, muting. The function gets ...
... Candidate Recommendation Initial specification. ...
...g the corresponding media track's enabled to the inverse of the specified muting. function setMuting(pc, muting) { let senderList = pc.getSenders
(); senderList.forEach(sender) { sender.track.enabled = !muting; } } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.getSenders
()' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection.removeStream() - Web APIs
If the signalingState is set to "closed", an InvalidStateError is raised. If the signalingState is set to "stable", the event negotiationneeded is sent on the RTCPeerConnection. Syntax RTCPeerConnection.removeStream(mediaStream); Parameters mediaStream A MediaStream specifying the stream to remove from the connection. Return value undefined. ...
...d. If the signalingState is set to "stable", the event negotiationneeded is sent on the RTCPeerConnection. ...
...diaStream A MediaStream specifying the stream to remove from the connection. Return value undefined. ...
RTCPeerConnection.removeTrack() - Web APIs
If the track is already stopped, or is not in the connection's senders list, this method has no effect. If the connection has already been negotiated (signalingState is set to "stable"), it is marked as needing to be negotiated again; the remote peer won't experience the change until this negotiation occurs. A negotiationneeded event is sent to the RTCPeerConnection to let the local end know this negotiation must occur. ...
...pecifying the sender to remove from the connection. Return value undefined. Exceptions InvalidStateError The connection is not open. Example This example adds a video track to a connection and sets up a listener on a close button which removes the track when the user clicks the button. ...
... connection. Return value undefined. Exceptions InvalidStateError The connection is not open. Example This example adds a video track to a connection and sets up a listener on a close button which removes the track when the user clicks the button. var pc, sender; navigator.getUserMedia({video: true}, function(stream) { pc = new RTCPeerConnection
(); var track = stream.getVideoTracks
()[0]; sender = pc.addTrack(track, stream); }); document.getElementById("closeButton").addEventListener("click", function(event) { pc.removeTrack(sender); pc.close
(); }, false); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.removeTrack
()' in that specification. Candidate Rec...
RTCPeerConnectionIceEvent() - Web APIs
Syntax var event = new RTCPeerConnectionIceEvent(type, options); Parameters type Is a DOMString containing the name of the event, like "icecandidate". options A dictionary of type RTCPeerConnectionInit, which may contain one or more of the following fields: "candidate" (optional, default is null): A RTCIceCandidate representing the ICE candidate being concerned by the event. If null, the event indicates the end of candidate gathering. "url" (optional, default is null): The URL of the STUN or TURN server which was used to gather the candidate. If the candidate was not gathered by a STUN or TURN server, this value must be null. ...
...CIceCandidate representing the ICE candidate being concerned by the event. If null, the event indicates the end of candidate gathering. "url" (optional, default is null): The URL of the STUN or TURN server which was used to gather the candidate. If the candidate was not gathered by a STUN or TURN server, this value must be null. "bubbles" (optional, default is false): Inherited from EventInit
(), this Boolean option indicates whether or not the event must bubble. "cancelable" (optional, default is false, inherited from EventInit
(), this Boolean indicates whether or not the event can be canceled. Return value A newly-created RTCPeerConnectionIceEvent, configured as specified in the provided options. Specifications Specification Status Comment WebRTC 1.0:...
...(optional, default is false, inherited from EventInit
(), this Boolean indicates whether or not the event can be canceled. Return value A newly-created RTCPeerConnectionIceEvent, configured as specified in the provided options. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnectionIceEvent
()' in that specification. Candidate Recommendation Initial definition. ...
RTCRtpReceiver.getStats() - Web APIs
The promise's fulfillment handler receives as a parameter a RTCStatsReport object containing the collected statistics. The returned statistics include those from all streams which are coming in through the RTCRtpReceiver, as well as any of their dependencies. ...
...The promise's fulfillment handler receives as a parameter a RTCStatsReport object containing the collected statistics. The returned statistics include those from all streams which are coming in through the RTCRtpReceiver, as well as any of their dependencies. ...
...ndler receives as a parameter a RTCStatsReport object containing the collected statistics. The returned statistics include those from all streams which are coming in through the RTCRtpReceiver, as well as any of their dependencies. Example This simple example obtains the statistics for an RTCRtpReceiver and updates an element's innerText to display the number of packets lost. receiver.getStats
().then(function(stats) { document.getElementById("lostpackets").innerText = stats.packetsLost; }); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpReceiver.getStats
()' in that specification. Candidate Recommendation Initial specification. ...
RTCRtpSender.setParameters() - Web APIs
Syntax var promise = rtcRtpSender.setParameters(parameters) Parameters parameters An object conforming with the RTCRtpSendParameters dictionary, specifying options for the RTCRtpSender; these include potential codecs that could be use for encoding the sender's track. ...
...y of RTCRtpEncodingParameters objects, each specifying the parameters for a single codec that could be used to encode the track's media. priority A string from the RTCPriorityType enumerated type which indicates the encoding's priority. The default value is low. transactionId A string containing a unique ID for the last set of parameters applied; this value is used to ensure that setParameters
() can only be called to alter changes made by a specific previous call to getParameters
(). Return value A Promise that resolves when the RTCRtpSender.track property is updated with the given parameters. Exceptions If an error occurs, the returned promise is rejected with the appropriate exception from the list below. InvalidModificationError One of the following problems was detected: ...
...ne or more of the specified encodings' maxFramerate values is less than 0.0. In addition, if a WebRTC error occurs while configuring or accessing the media, an RTCError is thrown with its errorDetail set to hardware-encoder-error. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpSender.setParameters
()' in that specification. Candidate Recommendation Initial definition. ...
RTCRtpTransceiver.stop() - Web APIs
The stop
() method in the RTCRtpTransceiver interface permanently stops the transceiver by stopping both the associated RTCRtpSender and RTCRtpReceiver. Note: Until recently, the stopped property was provided to return true if the connection is stopped. That property has been deprecated and will be removed at some point. Instead, check the value of currentDirection. If it's stopped, the transceiver has been stopped. This method does nothing if the transceiver is already stopped. Syntax RTCRtpTransceiver.stop
() Paramters None. Return value undefined Exceptions InvalidStateError The RTCPeerConnection of which the transceiver is a member is closed. ...
...removed at some point. Instead, check the value of currentDirection. If it's stopped, the transceiver has been stopped. This method does nothing if the transceiver is already stopped. Syntax RTCRtpTransceiver.stop
() Paramters None. Return value undefined Exceptions InvalidStateError The RTCPeerConnection of which the transceiver is a member is closed. Usage notes When you call stop
() on a transceiver, the sender immediately stops sending media and each of its RTP streams are closed using the RTCP "BYE" message. The receiver then stops receiving media; the receiver's track is stopped, and the transceiver's direction is changed to stopped, and renegotiation is triggered by sending a negotiationneeded event to the RTCPeerConnection. The negotiation process causes currentNegotia...
... Candidate Recommendation ...
RTCSessionDescription() - Web APIs
Syntax sessionDescription = new RTCSessionDescription(rtcSessionDescriptionInit); Values rtcSessionDescriptionInit Optional An object providing the default values for the session description; the object conforms to the RTCSessionDescriptionInit dictionary. That dictionary has the following properties: type Required. ...
...ession description is used to roll back to the previous stable state. sdp A string containing a SDP message describing the session. This value is an empty string ("") by default and may not be null. Example This example uses the constructor to convert an SDP offer into an RTCSessionDescription object. This is no longer necessary, however; RTCPeerConnection.setLocalDescription
() and other methods which take SDP as input now directly accept an object conforming to the RTCSessionDescriptionInit dictionary, so you don't have to instantiate an RTCSessionDescription yourself. navigator.getUserMedia({video: true}, function(stream) { pc.onaddstream({stream: stream}); // Adding a local stream won't trigger the onaddstream callback pc.addStream(stream); pc.createOffer(...
...the RTCSessionDescriptionInit dictionary, so you don't have to instantiate an RTCSessionDescription yourself. navigator.getUserMedia({video: true}, function(stream) { pc.onaddstream({stream: stream}); // Adding a local stream won't trigger the onaddstream callback pc.addStream(stream); pc.createOffer(function(offer) { pc.setLocalDescription(new RTCSessionDescription(offer), function
() { // send the offer to a server to be forwarded to the friend you're calling. }, error); }, error); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCSessionDescription
()' in that specification. Candidate Recommendation Initial specification. ...
Range.cloneContents() - Web APIs
The Range.cloneContents
() returns a DocumentFragment copying the objects of type Node included in the Range. Event Listeners added using DOM Events are not copied during cloning. HTML attribute events are duplicated as they are for the DOM Core cloneNode method. HTML id attributes are also cloned, which can lead to an invalid document through cloning. Partially selected nodes include the parent tags necessary to make the document fragment valid. ...
...he Range. Event Listeners added using DOM Events are not copied during cloning. HTML attribute events are duplicated as they are for the DOM Core cloneNode method. HTML id attributes are also cloned, which can lead to an invalid document through cloning. Partially selected nodes include the parent tags necessary to make the document fragment valid. Syntax documentFragment = range.cloneContents
(); Example range = document.createRange
(); range.selectNode(document.getElementsByTagName("div").item(0)); documentFragment = range.cloneContents
(); document.body.appendChild(documentFragment); Specifications Specification Status Comment DOMThe definition of 'Range.cloneContents
()' in that specification. Living Standard No change. Document Object Model (...
...TagName("div").item(0)); documentFragment = range.cloneContents
(); document.body.appendChild(documentFragment); Specifications Specification Status Comment DOMThe definition of 'Range.cloneContents
()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.cloneContents
()' in that specification. Obsolete Initial specification. ...
Range.compareBoundaryPoints() - Web APIs
Syntax compare = range.compareBoundaryPoints(how, sourceRange); Return value compare A number, -1, 0, or 1, indicating whether the corresponding boundary-point of the Range is respectively before, equal to, or after the corresponding boundary-point of sourceRange. Parameters how A constant describing the comparison method: Range.END_TO_END compares the end boundary-point of sourceRange to the end boundary-point of Range. Range.END_TO_START compares the end boundary-point of sourceRange to the start boundary-point of Range. Range.START_TO_END compares the start boundary-point of sourceRange to the end boundary-point of Range. ...
...sourceRange to the end boundary-point of Range. Range.START_TO_START compares the start boundary-point of sourceRange to the start boundary-point of Range. If the value of the parameter is invalid, a DOMException with a NotSupportedError code is thrown. sourceRange A Range to compare boundary points with the range. Example var range, sourceRange, compare; range = document.createRange
(); range.selectNode(document.getElementsByTagName("div")[0]); sourceRange = document.createRange
(); sourceRange.selectNode(document.getElementsByTagName("div")[1]); compare = range.compareBoundaryPoints(Range.START_TO_END, sourceRange); Specifications Specification Status Comment DOMThe definition of 'Range.compareBoundaryPoints
()' in that specification. Living Standar...
...tsByTagName("div")[1]); compare = range.compareBoundaryPoints(Range.START_TO_END, sourceRange); Specifications Specification Status Comment DOMThe definition of 'Range.compareBoundaryPoints
()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.compareBoundaryPoints
()' in that specification. Obsolete Initial specification. ...
Range.createContextualFragment() - Web APIs
The Range.createContextualFragment
() method returns a DocumentFragment by invoking the HTML fragment parsing algorithm or the XML fragment parsing algorithm with the start of the range (the parent of the selected node) as the context node. The HTML fragment parsing algorithm is used if the range belongs to a Document whose HTMLness bit is set. In the HTML case, if the context node would be html, for historical reasons the fragment parsing algorithm is invoked with body as the context instead. Syntax documentFragment = range.createContextualFragment(tagString) Parameters tagString Text that contains text and tags to be converted to a document fragment. ...
... case, if the context node would be html, for historical reasons the fragment parsing algorithm is invoked with body as the context instead. Syntax documentFragment = range.createContextualFragment(tagString) Parameters tagString Text that contains text and tags to be converted to a document fragment. ...
... Working Draft Initial specification. ...
Range.insertNode() - Web APIs
The Range.insertNode
() method inserts a node at the start of the Range. The new node is inserted at the start boundary point of the Range. If the new node is to be added to a text Node, that Node is split at the insertion point, and the insertion occurs between the two text nodes. If the new node is a document fragment, the children of the document fragment are inserted instead. Syntax range.insertNode(newNode); Parameters newNode The Node to insert at the start of the range. ...
...he Range. If the new node is to be added to a text Node, that Node is split at the insertion point, and the insertion occurs between the two text nodes. If the new node is a document fragment, the children of the document fragment are inserted instead. Syntax range.insertNode(newNode); Parameters newNode The Node to insert at the start of the range. Example range = document.createRange
(); newNode = document.createElement("p"); newNode.appendChild(document.createTextNode("New Node Inserted Here")); range.selectNode(document.getElementsByTagName("div").item(0)); range.insertNode(newNode); Specifications Specification Status Comment DOMThe definition of 'Range.insertNode
()' in that specification. Living Standard No change Document Object Mod...
... Obsolete Initial definition ...
Range.setEnd() - Web APIs
Syntax range.setEnd(endNode, endOffset); Parameters endNode The Node inside which the Range should end. endOffset An integer greater than or equal to zero representing the offset for the end of the Range from the start of endNode. Return value undefined. Exceptions Exceptions are thrown as DOMException objects of the following types: InvalidNodeTypeError The node specified by endNode is a doctype node; range endpoints cannot be located inside a doctype node. ...
...e value specified by endOffset is either greater than or equal to the length of the node or is less than zero. Usage notes If the endNode is a Node of type Text, Comment, or CDataSection, then endOffset is the number of characters from the start of endNode. For other Node types, endOffset is the number of child nodes between the start of the endNode. Example const range = document.createRange
(); const endNode = document.getElementsByTagName('p').item(3); const endOffset = endNode.childNodes.length; range.setEnd(endNode, endOffset); setEnd
() is commonly used in conjunction with setStart
() to fully configure a range. Specifications Specification Status Comment DOMThe definition of 'Range.setEnd
()' in that specification. Living Standard No change. ...
...th; range.setEnd(endNode, endOffset); setEnd
() is commonly used in conjunction with setStart
() to fully configure a range. Specifications Specification Status Comment DOMThe definition of 'Range.setEnd
()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.setEnd
()' in that specification. Obsolete Initial specification. ...
Range.surroundContents() - Web APIs
After surrounding, the boundary points of the range include newNode. An exception will be thrown, however, if the Range splits a non-Text node with only one of its boundary points. That is, unlike the alternative above, if there are partially selected nodes, they will not be cloned and instead the operation will fail. Syntax range.surroundContents(newParent); Parameters newParent A Node with which to surround the contents. ...
...e of its boundary points. That is, unlike the alternative above, if there are partially selected nodes, they will not be cloned and instead the operation will fail. Syntax range.surroundContents(newParent); Parameters newParent A Node with which to surround the contents. Example HTML <span class="header-text">Put this in a headline</span> JavaScript const range = document.createRange
(); const newParent = document.createElement('h1'); range.selectNode(document.querySelector('.header-text')); range.surroundContents(newParent); Result Specifications Specification Status Comment DOMThe definition of 'Range.surroundContents
()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range Specifi...
...); range.selectNode(document.querySelector('.header-text')); range.surroundContents(newParent); Result Specifications Specification Status Comment DOMThe definition of 'Range.surroundContents
()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.surroundContents
()' in that specification. Obsolete Initial specification. ...
ReadableStream.pipeThrough() - Web APIs
Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. Syntax var transformedStream = readableStream.pipeThrough(transformStream[, options]); Parameters transformStream A TransformStream (or an object with the structure {writable, readable}) consisting of a readable stream and a writable stream working together to transform some data from one form to another. Data writen to the writable stream can be read in some transformed state by the readable stream. ...
...side of the transformStream. Exceptions TypeError The writable and/or readable property of transformStream are undefined. Examples In the following example (see Unpack chunks of a PNG for the full code running live, and png-transform-stream for the source code), an image is fetched and its body retrieved as a ReadableStream. Next, we log the contents of the readable stream, use pipeThrough
() to send it to a new function that creates a gray-scaled version of the stream, then log the new stream's contents too. // Fetch the original image fetch('png-logo.png') // Retrieve its body as ReadableStream .then(response => response.body) .then(rs => logReadableStream('Fetch Response Stream', rs)) // Create a gray-scaled PNG stream out of the original .then(body => body.pipeThrough(new PNGTran...
... to a new function that creates a gray-scaled version of the stream, then log the new stream's contents too. // Fetch the original image fetch('png-logo.png') // Retrieve its body as ReadableStream .then(response => response.body) .then(rs => logReadableStream('Fetch Response Stream', rs)) // Create a gray-scaled PNG stream out of the original .then(body => body.pipeThrough(new PNGTransformStream
())) .then(rs => logReadableStream('PNG Chunk Stream', rs)) Specifications Specification Status Comment StreamsThe definition of 'pipeThrough
()' in that specification. Living Standard Initial definition. ...
ReadableStreamBYOBReader.cancel() - Web APIs
Syntax var promise = readableStreamBYOBReader.cancel(reason); Parameters reason A DOMString providing a human-readable reason for the cancellation. Return value A Promise, which fulfills with the value given in the reason parameter. Exceptions TypeError The source object is not a ReadableStreamBYOBReader, or the stream has no owner. Examples TBD. ...
... Syntax var promise = readableStreamBYOBReader.cancel(reason); Parameters reason A DOMString providing a human-readable reason for the cancellation. Return value A Promise, which fulfills with the value given in the reason parameter. Exceptions TypeError The source object is not a ReadableStreamBYOBReader, or the stream has no owner. Examples TBD. ...
... Living Standard Initial definition. ...
ReportingObserver() - Web APIs
The callback function is given two parameters: reports: A sequence of Report objects representing the reports collected in the observer's report queue. This is probably the most common way to retrieve the reports. observer: A reference to the same ReportingObserver object, allowing for recursive report collection, etc. ...
...The callback function is given two parameters: reports: A sequence of Report objects representing the reports collected in the observer's report queue. This is probably the most common way to retrieve the reports. observer: A reference to the same ReportingObserver object, allowing for recursive report collection, etc. ...
...ugh this last type usually isn't retrievable via a ReportingObserver). buffered: a boolean that defines whether the reports that were generated before the observer was able to be created should be observable (true) or not (false). Examples let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { reportBtn.onclick =
() => displayReports(reports); }, options); Specifications Specification Status Comment Reporting APIThe definition of 'ReportingObserver
()' in that specification. Editor's Draft ...
ResizeObserver.observe() - Web APIs
Syntax resizeObserver.observe(target, options); Parameters target A reference to an Element or SVGElement to be observed. options Optional An options object allowing you to set options for the observation. Currently this only has one possible option that can be set: box Sets which box model the observer will observe changes to. Possible values are content-box (the default), and border-box. Return value Void. Exceptions None. ...
... Editor's Draft Initial definition. ...
... Editor's Draft Initial definition. ...
ResizeObserver.unobserve() - Web APIs
Syntax void unobserve(target); Parameters target A reference to an Element or SVGElement to be unobserved. Return value Void. Exceptions None. ...
... Editor's Draft Initial definition. ...
... Editor's Draft Initial definition. ...
Selection.containsNode() - Web APIs
The Selection.containsNode
() method indicates whether a specfied node is part of the selection. Syntax sel.containsNode(node, partialContainment) Parameters node The node that is being looked for in the selection. partialContainment Optional When true, containsNode
() returns true when a part of the node is part of the selection. When false, containsNode
() only returns true when the entire node is part of the selection. If not specified, the default value false is used. Example Check for selection This snippet checks whether anything inside the body element is selected. console.log(window.getSelection
().containsNode(document.body, true)); Find the hidden word In this example, a message appears when you select the secret word. ...
...urns true when the entire node is part of the selection. If not specified, the default value false is used. Example Check for selection This snippet checks whether anything inside the body element is selected. console.log(window.getSelection
().containsNode(document.body, true)); Find the hidden word In this example, a message appears when you select the secret word. It uses addEventListener
() to check for selectionchange events. ...
...tener
() to check for selectionchange events. HTML <p>Can you find the secret word?</p> <p>Hmm, where <span id="secret" style="color:transparent">SECRET</span> could it be?</p> <p id="win" hidden>You found it!</p> JavaScript const secret = document.getElementById('secret'); const win = document.getElementById('win'); // Listen for selection changes document.addEventListener('selectionchange',
() => { const selection = window.getSelection
(); const found = selection.containsNode(secret); win.toggleAttribute('hidden', !found); }); Result Specifications Specification Status Comment Selection APIThe definition of 'Selection.containsNode
()' in that specification. Working Draft Current ...
Selection.modify() - Web APIs
Syntax sel.modify(alter, direction, granularity) Parameters alter The type of change to apply. Specify "move" to move the current cursor position or "extend" to extend the current selection. direction The direction in which to adjust the current selection. You can specify "forward" or "backward" to adjust in the appropriate direction based on the language at the selection point. If you want to adjust in a specific direction, you can specify "left" or "right". granularity The distance to adjust the current selection or cursor position. ...
... ...
... ...
Selection.removeRange() - Web APIs
Working Draft Current Browser compatibility The compatibility table on this page is generated from structured data. ...
... Working Draft Current Browser compatibility The compatibility table on this page is generated from structured data. ...
... Working Draft Current Browser compatibility The compatibility table on this page is generated from structured data. ...
SourceBuffer.removeAsync() - Web APIs
Syntax removePromise = sourceBuffer.removeAsync(start, end); Parameters start A double representing the start of the time range, in seconds. end A double representing the end of the time range, in seconds. Return value A Promise whose fulfillment handler is executed once the buffers in the specified time range have been removed from the SourceBuffer. ...
... Syntax removePromise = sourceBuffer.removeAsync(start, end); Parameters start A double representing the start of the time range, in seconds. end A double representing the end of the time range, in seconds. Return value A Promise whose fulfillment handler is executed once the buffers in the specified time range have been removed from the SourceBuffer. ...
...eAsync(start, end); Parameters start A double representing the start of the time range, in seconds. end A double representing the end of the time range, in seconds. Return value A Promise whose fulfillment handler is executed once the buffers in the specified time range have been removed from the SourceBuffer. Example This example establishes an asynchronous function, emptySourceBuffer
(), which simply clears the contents of the specified SourceBuffer. async function emptySourceBuffer(msBuffer) { await msBuffer.removeAsync(0, Infinity).catch(function(e) { handleException(e); } } Specifications Not currently part of the MSE specification. Specification Status Comment Media Source Extensions Recommendation Initial definition. ...
SpeechGrammar.SpeechGrammar() - Web APIs
The SpeechGrammar constructor of the SpeechGrammar interface creates a new SpeechGrammar object instance. Syntax var mySpeechGrammar = new SpeechGrammar
(); Parameters None. ...
...e | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new SpeechRecognition
(); var speechRecognitionList = new SpeechGrammarList
(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; var newGrammar = new SpeechGrammar
(); newGrammar.src = '#JSGF V1.0; grammar names; public <name> = chris | kirsty | mike;' speechRecognitionList[1] = newGrammar; // should add the new SpeechGrammar object to the list Specifications Speci...
... Draft ...
SpeechGrammarList.SpeechGrammarList() - Web APIs
The SpeechGrammarList
() constructor creates a new SpeechGrammarList object instance. Syntax var myGrammarList = new SpeechGrammarList
(); Parameters None. Examples In our simple Speech color changer example, we create a new SpeechRecognition object instance using the SpeechRecognition
() constructor, create a new SpeechGrammarList, add our grammar string to it using the SpeechGrammarList.addFromString method, and set it to be the grammar that will be recognised by the SpeechRecognition instance using the SpeechRecognition.grammars property. var grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | li...
... Draft ...
... Draft ...
SpeechGrammarList.item() - Web APIs
...
... Draft ...
...on = new SpeechRecognition
(); var speechRecognitionList = new SpeechGrammarList
(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; var myFirstGrammar = speechRecognitionList[0]; // var should contain the SpeechGrammar object created in line 4. Specifications Specification Status Comment Web Speech APIThe definition of 'item
()' in that specification. Draft ...
SpeechSynthesis.speak() - Web APIs
The speak
() method of the SpeechSynthesis interface adds an utterance to the utterance queue; it will be spoken when any other utterances queued before it have been spoken. Syntax speechSynthesisInstance.speak(utterance); Returns Void. Parameters utterance A SpeechSynthesisUtterance object. Examples This snippet is excerpted from our Speech synthesiser demo. When a form containing the text we want to speak is submitted, we (amongst other things) create a new utterance containing this text, then speak it by passing it into speak
() as a parameter. var synth = window.speechSynthesis; ... ...
...eechSynthesisUtterance object. Examples This snippet is excerpted from our Speech synthesiser demo. When a form containing the text we want to speak is submitted, we (amongst other things) create a new utterance containing this text, then speak it by passing it into speak
() as a parameter. var synth = window.speechSynthesis; ... ...
...Synthesis; ... inputForm.onsubmit = function(event) { event.preventDefault
(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedOption) { utterThis.voice = voices[i]; } } synth.speak(utterThis); inputTxt.blur
(); } Specifications Specification Status Comment Web Speech APIThe definition of 'speak
()' in that specification. Draft ...
SpeechSynthesisUtterance.SpeechSynthesisUtterance() - Web APIs
The SpeechSynthesisUtterance
() constructor of the SpeechSynthesisUtterance interface returns a new SpeechSynthesisUtterance object instance. Syntax var utterThis = new SpeechSynthesisUtterance(text); Parameters text A DOMString containing the text that will be synthesized when the utterance is spoken.. Examples The following snippet is excerpted from our Speech synthesizer demo. var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices
(); ... ...
...when the utterance is spoken.. Examples The following snippet is excerpted from our Speech synthesizer demo. var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices
(); ... ...
...tVoices
(); ... inputForm.onsubmit = function(event) { event.preventDefault
(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedOption) { utterThis.voice = voices[i]; } } synth.speak(utterThis); inputTxt.blur
(); } Specifications Specification Status Comment Web Speech APIThe definition of 'SpeechSynthesisUtterance
()' in that specification. Draft ...
StereoPannerNode.StereoPannerNode() - Web APIs
Syntax var stereoPannerNode = StereoPannerNode(context, options) Parameters Inherits parameters from the AudioNodeOptions dictionary. context A reference to an AudioContext. options Optional Options are as follows: pan: A floating point number in the range [-1,1] indicating the position of an AudioNode in an output image. The value -1 represents full left and 1 represents full right. The default value is 0. Return value A new StereoPannerNode object instance. ...
...tions are as follows: pan: A floating point number in the range [-1,1] indicating the position of an AudioNode in an output image. The value -1 represents full left and 1 represents full right. The default value is 0. Return value A new StereoPannerNode object instance. Specifications Specification Status Comment Web Audio APIThe definition of 'StereoPannerNode
()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for...
... 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. ...
Storage.removeItem() - Web APIs
The removeItem
() method of the Storage interface, when passed a key name, will remove that key from the given Storage object if it exists. The Storage interface of the Web Storage API provides access to a particular domain's session or local storage. If there is no item associated with the given key, this method will do nothing. Syntax storage.removeItem(keyName); Parameters keyName A DOMString containing the name of the key you want to remove. Return value undefined. Example The following function creates three data items inside local storage, then removes the image data item. ...
...s session or local storage. If there is no item associated with the given key, this method will do nothing. Syntax storage.removeItem(keyName); Parameters keyName A DOMString containing the name of the key you want to remove. Return value undefined. Example The following function creates three data items inside local storage, then removes the image data item. ...
...e undefined. Example The following function creates three data items inside local storage, then removes the image data item. function populateStorage
() { localStorage.setItem('bgcolor', 'red'); localStorage.setItem('font', 'Helvetica'); localStorage.setItem('image', 'myCat.png'); localStorage.removeItem('image'); } We can do the same for the session storage. function populateStorage
() { sessionStorage.setItem('bgcolor', 'red'); sessionStorage.setItem('font', 'Helvetica'); sessionStorage.setItem('image', 'myCat.png'); sessionStorage.removeItem('image'); } Note: To see this used within a real world example, see our Web Storage Demo. Specifications Specification Status Comment HTML Living StandardThe definition of 'Storage.removeItem' in ...
Storage.setItem() - Web APIs
Particularly, in Mobile Safari (since iOS 5) it always throws when the user enters private mode. ...
...a key name and value, will add that key to the given Storage object, or update that key's value if it already exists. Syntax storage.setItem(keyName, keyValue); Parameters keyName A DOMString containing the name of the key you want to create/update. keyValue A DOMString containing the value you want to give the key you are creating/updating. Return value undefined. Exceptions setItem
() may throw an exception if the storage is full. Particularly, in Mobile Safari (since iOS 5) it always throws when the user enters private mode. (Safari sets the quota to 0 bytes in private mode, unlike other browsers, which allow storage in private mode using separate data containers.) Hence developers should make sure to always catch possible exceptions from setItem
(). Example The following fu...
...(since iOS 5) it always throws when the user enters private mode. (Safari sets the quota to 0 bytes in private mode, unlike other browsers, which allow storage in private mode using separate data containers.) Hence developers should make sure to always catch possible exceptions from setItem
(). Example The following function creates three data items inside local storage. function populateStorage
() { localStorage.setItem('bgcolor', 'red'); localStorage.setItem('font', 'Helvetica'); localStorage.setItem('image', 'myCat.png'); } Note: To see this used within a real world example, see our Web Storage Demo. Specifications Specification Status Comment HTML Living StandardThe definition of 'Storage.setItem' in that specification. Living Standard ...
StorageManager.estimate() - Web APIs
Return value A Promise that resolves to an object which conforms to the StorageEstimate dictionary. This dictionary contains estimates of how much space is available to the origin in StorageEstimate.quota, as well as how much is currently used in StorageEstimate.usage. ...
...ace asks the Storage Manager for how much storage the current origin takes up (usage), and how much space is available (quota). This method operates asynchronously, so it returns a Promise which resolves once the information is available. The promise's fulfillment handler is called with a StorageEstimate containing the usage and quota data. Syntax const estimatePromise = StorageManager.estimate
(); Parameters None. Return value A Promise that resolves to an object which conforms to the StorageEstimate dictionary. This dictionary contains estimates of how much space is available to the origin in StorageEstimate.quota, as well as how much is currently used in StorageEstimate.usage. The returned values are not exact; between compression, deduplication, and obfuscation for security reaso...
...er engagement signals like bookmarking, adding to homescreen, or accepting push notifications Example In this example, we obtain the usage estimates and present the percentage of storage capacity currently used to the user. HTML content <label> You're currently using about <output id="percent"> </output>% of your available storage. </label> JavaScript content navigator.storage.estimate
().then(function(estimate) { document.getElementById("percent").value = (estimate.usage / estimate.quota * 100).toFixed(2); }); Result Specifications Specification Status Comment StorageThe definition of 'estimate
()' in that specification. Living Standard Initial definition. ...
TextDecoder() - Web APIs
If the value for utfLabel is unknown, or is one of the two values leading to a 'replacement' decoding algorithm ( "iso-2022-cn" or "iso-2022-cn-ext"), a DOMException with the "TypeError" value is thrown. Syntax decoder = new TextDecoder(utfLabel, options); Parameters utfLabelOptional Is a DOMString, defaulting to "utf-8", containing the label of the encoder. ...
...var textDecoder4 = new TextDecoder("iso-2022-cn"); // Throw a Typ...
...iso-2022-cn-ext" 'replacement' optionsOptional Is a TextDecoderOptions dictionary with the property: fatal A Boolean flag indicating if the TextDecoder.decode
() method must throw a DOMException with the "EncodingError" value when an coding error is found. It defaults to false. Example var textDecoder1 = new TextDecoder("iso-8859-2"); var textDecoder2 = new TextDecoder
(); var textDecoder3 = new TextDecoder("csiso2022kr", {fatal: true}); // Allows EncodingError exception to be thrown. var textDecoder4 = new TextDecoder("iso-2022-cn"); // Throw a TypeError exception. Specifications Specification Status Comment EncodingThe definition of 'TextDecoder
()' in that specification. Living Standard Initial definition. ...
URLSearchParams.keys() - Web APIs
Living Standard Initial definition. ...
... Living Standard Initial definition. ...
...allowing iteration through all keys contained in this object. The keys are USVString objects. Note: This method is available in Web Workers. Syntax searchParams.keys
(); Parameters None. Return value Returns an iterator. Examples // Create a test URLSearchParams object var searchParams = new URLSearchParams("key1=value1&key2=value2"); // Display the keys for(var key of searchParams.keys
()) { console.log(key); } The result is: key1 key2 Specifications Specification Status Comment URLThe definition of 'keys
() (see "iterable")' in that specification. Living Standard Initial definition. ...
URLUtilsReadOnly.toString() - Web APIs
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. ...
...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. ...
...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. ...
WEBGL_debug_shaders.getTranslatedShaderSource() - Web APIs
The WEBGL_debug_shaders.getTranslatedShaderSource
() method is part of the WebGL API and allows you to debug a translated shader. Syntax gl.getExtension('WEBGL_debug_shaders').getTranslatedShaderSource(shader); Parameters shader A WebGLShader to get the translated source from. Return value A String containing the translated shader source. An empty string is returned, if: no source has been defined or, WebGLRenderingContext.compileShader
() has not yet been called or, the translation for the shader failed. ...
...ng containing the translated shader source. An empty string is returned, if: no source has been defined or, WebGLRenderingContext.compileShader
() has not yet been called or, the translation for the shader failed. ...
...hader failed. Examples var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var shader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(shader, 'void main
() { gl_FragColor = vec4(gl_FragCoord.x, 0.0, 0.0, 1.0); }'); gl.compileShader(shader); var src = gl.getExtension('WEBGL_debug_shaders').getTranslatedShaderSource(shader); console.log(src); // "void main
(){ // (gl_FragColor = vec4(gl_FragCoord.x, 0.0, 0.0, 1.0)); // }" Specifications Specification Status Comment WEBGL_debug_shadersThe definition of 'WEBGL_debug_shaders.getTranslatedShaderSource' in that specification. Recommendation Initial definition. ...
WakeLock.request() - Web APIs
Syntax var wakeLock = navigator.wakeLock.request(type); Parameters type Options are as follows: 'screen': Requests a screen wake lock. Prevents devices from dimming or locking the screen. Return value A Promise that resolves with a WakeLockSentinel object. Exceptions NotAllowedError Thrown when wake lock is not available, which can happen because: Document is not allowed to use screen wake lock due to screen-wake-lock policy. Document is not fully active. Document is hidden. User Agent could not acquire platform's wake lock. ...
...nel object. Exceptions NotAllowedError Thrown when wake lock is not available, which can happen because: Document is not allowed to use screen wake lock due to screen-wake-lock policy. Document is not fully active. Document is hidden. User Agent could not acquire platform's wake lock. Examples The following asynchronous function requests a WakeLockSentinel object. ...
...screen wake lock due to screen-wake-lock policy. Document is not fully active. Document is hidden. User Agent could not acquire platform's wake lock. Examples The following asynchronous function requests a WakeLockSentinel object. The request
() method is wrapped in a try...catch statement to account for if the browser refuses the request for any reason. const requestWakeLock = async
() => { try { const wakeLock = await navigator.wakeLock.request('screen'); } catch (err) { // the wake lock request fails - usually system related, such low as battery console.log(`${err.name}, ${err.message}`); } } requestWakeLock
(); Specifications Specification Status Comment Screen Wake Lock APIThe definition of 'request
()' in that specification. ...
WaveShaperNode.WaveShaperNode() - Web APIs
Syntax var waveShaperNode = new WaveShaperNode(context, options) Parameters Inherits parameters from the AudioNodeOptions dictionary. context A reference to an AudioContext. options Optional Options are as follows: curve: The shaping curve used for the waveshaping effect. The input signal is nominally within the range [-1;1]. oversample: Specifies what type of oversampling (if any) should be used when applying the shaping curve. Valid values are 'none', '2x', or '4x'. The default is 'none'. Return value A new WaveShaperNode object instance. ...
... The input signal is nominally within the range [-1;1]. oversample: Specifies what type of oversampling (if any) should be used when applying the shaping curve. Valid values are 'none', '2x', or '4x'. The default is 'none'. Return value A new WaveShaperNode object instance. Specifications Specification Status Comment Web Audio APIThe definition of 'WaveShaperNode
()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for...
... 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. ...
WebGL2RenderingContext.copyBufferSubData() - Web APIs
Syntax void gl.copyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size); Parameters readTarget writeTarget A GLenum specifying the binding point (target) from whose data store should be read or written. Possible values: gl.ARRAY_BUFFER: Buffer containing vertex attributes, such as vertex coordinates, texture coordinate data, or vertex color data. gl.ELEMENT_ARRAY_BUFFER: Buffer used for element indices. gl.COPY_READ_BUFFER: Buffer for copying from one buffer object to another (provided specifically for copy operations). ...
... used for pixel transfer operations. gl.PIXEL_UNPACK_BUFFER: Buffer used for pixel transfer operations. readOffset writeOffset A GLintptr specifying the byte offset from which to start reading from or writing to the buffer. size A GLsizei in bytes specifying the size of the data to be copied from readTarget to writeTarget. Return value None. ...
.... gl.PIXEL_UNPACK_BUFFER: Buffer used for pixel transfer operations. readOffset writeOffset A GLintptr specifying the byte offset from which to start reading from or writing to the buffer. size A GLsizei in bytes specifying the size of the data to be copied from readTarget to writeTarget. Return value None. ...
WebGL2RenderingContext.createQuery() - Web APIs
Editor's Draft Initial definition. OpenGL ES 3.0The definition of 'glGenQueries' in that specification. ...
... Editor's Draft Initial definition. OpenGL ES 3.0The definition of 'glGenQueries' in that specification. ...
... Editor's Draft Initial definition. OpenGL ES 3.0The definition of 'glGenQueries' in that specification. ...
WebGL2RenderingContext.createSampler() - Web APIs
Editor's Draft Initial definition. OpenGL ES 3.0The definition of 'glGenSamplers' in that specification. ...
... Editor's Draft Initial definition. OpenGL ES 3.0The definition of 'glGenSamplers' in that specification. ...
... Editor's Draft Initial definition. OpenGL ES 3.0The definition of 'glGenSamplers' in that specification. ...
WebGL2RenderingContext.createTransformFeedback() - Web APIs
Editor's Draft Initial definition for WebGL. OpenGL ES 3.0The definition of 'glGenTransformFeedbacks' in that specification. ...
... Editor's Draft Initial definition for WebGL. OpenGL ES 3.0The definition of 'glGenTransformFeedbacks' in that specification. ...
... Editor's Draft Initial definition for WebGL. OpenGL ES 3.0The definition of 'glGenTransformFeedbacks' in that specification. ...
WebGL2RenderingContext.createVertexArray() - Web APIs
// calls to bindBuffer or vertexAttribPointer // which will be "recorded" in the VAO // ... ...
...// calls to bindBuffer or vertexAttribPointer // which will be "recorded" in the VAO // ... ...
...// calls to bindBuffer or vertexAttribPointer // which will be "recorded" in the VAO // ... ...
WebGL2RenderingContext.vertexAttribIPointer() - Web APIs
Syntax void gl.vertexAttribIPointer(index, size, type, stride, offset); Parameters index A GLuint specifying the index of the vertex attribute that is to be modified. size A GLint specifying the number of components per vertex attribute. Must be 1, 2, 3, or 4. type A GLenum specifying the data type of each component in the array. Must be one of: gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.INT, or gl.UNSIGNED_INT. stride A GLsizei specifying the offset in bytes between the beginning of consecutive vertex attributes. ...
...IGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.INT, or gl.UNSIGNED_INT. stride A GLsizei specifying the offset in bytes between the beginning of consecutive vertex attributes. offset A GLintptr specifying an offset in bytes of the first component in the vertex attribute array. Must be a multiple of type. Return value None. Description Very similar to WebGLRenderingContext.vertexAttribPointer
(). The main difference is that while values specified by vertexAttribPointer are always interpreted as floating-point values in the shader (even if they were originally specified as integers in the buffer), this method allows specifying values which are interpreted as integers in the shader. Examples Linear Blend Skinning //Describe the layout of the buffer: //1. position gl.vertexAttribPointer...
...ex shader gl.bindAttribLocation(shaderProgram, 0, "position"); gl.bindAttribLocation(shaderProgram, 1, "boneWeights"); gl.bindAttribLocation(shaderProgram, 2, "boneIndices"); <script id="shader-vs" type="x-shader/x-vertex">#version 300 es uniform mat4 mvMatrix; uniform mat4 bones[120]; in vec3 position; in vec4 boneWeights; in uvec4 boneIndices;//read as 4-component unsigned integer void main
() { vec4 skinnedPosition = bones[boneIndices.s] * vec4(position, 1.0) * boneWeights.s + bones[boneIndices.t] * vec4(position, 1.0) * boneWeights.t + bones[boneIndices.p] * vec4(position, 1.0) * boneWeights.p + bones[boneIndices.q] * vec4(position, 1.0) * boneWeights.q; gl_Position = mvMatrix * skinnedPosition; } </script> Specifications Specificat...
WebGLRenderingContext.compressedTexImage[23]D() - Web APIs
Compressed image formats must be enabled by WebGL extensions before using these methods. ...
... Compressed image formats must be enabled by WebGL extensions before using these methods. ...
...ead from the buffer bound to gl.PIXEL_UNPACK_BUFFER. pixels An ArrayBufferView that be used as a data store for the compressed image data in memory. Return value None. ...
WebGLRenderingContext.createBuffer() - Web APIs
Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenBuffers' in that specification. ...
... Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenBuffers' in that specification. ...
... Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenBuffers' in that specification. ...
WebGLRenderingContext.createFramebuffer() - Web APIs
Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenFramebuffers' in that specification. ...
... Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenFramebuffers' in that specification. ...
... Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenFramebuffers' in that specification. ...
WebGLRenderingContext.createRenderbuffer() - Web APIs
Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenRenderbuffers' in that specification. ...
... Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenRenderbuffers' in that specification. ...
... Recommendation Initial definition. ...
WebGLRenderingContext.createTexture() - Web APIs
Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenTextures' in that specification. ...
... Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenTextures' in that specification. ...
... Recommendation Initial definition. ...
WebGLRenderingContext.stencilOp() - Web APIs
Syntax void gl.stencilOp(fail, zfail, zpass); Parameters All three parameters accept all constants listed below. fail A GLenum specifying the function to use when the stencil test fails. The default value is gl.KEEP. zfail A GLenum specifying the function to use when the stencil test passes, but the depth test fails. The default value is gl.KEEP. zpass A GLenum specifying the function to use when both the stencil test and the depth test pass, or when the stencil test passes and there is no depth buffer or depth testing is disabled. The default value is gl.KEEP. Return value None. ...
... both the stencil test and the depth test pass, or when the stencil test passes and there is no depth buffer or depth testing is disabled. The default value is gl.KEEP. Return value None. Constants gl.KEEP Keeps the current value. gl.ZERO Sets the stencil buffer value to 0. gl.REPLACE Sets the stencil buffer value to the reference value as specified by WebGLRenderingContext.stencilFunc
(). gl.INCR Increments the current stencil buffer value. Clamps to the maximum representable unsigned value. gl.INCR_WRAP Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing the maximum representable unsigned value. gl.DECR Decrements the current stencil buffer value. Clamps to 0. gl.DECR_WRAP Decrements the current stencil buffer value. Wraps st...
...ents the current stencil buffer value. Clamps to 0. gl.DECR_WRAP Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable unsigned value when decrementing a stencil buffer value of 0. gl.INVERT Inverts the current stencil buffer value bitwise. Examples The stencil testing is disabled by default. To enable or disable stencil testing, use the enable
() and disable
() methods with the argument gl.STENCIL_TEST. gl.enable(gl.STENCIL_TEST); gl.stencilOp(gl.INCR, gl.DECR, gl.INVERT); To get the current information about stencil and depth pass or fail, query the following constants with getParameter
(). gl.getParameter(gl.STENCIL_FAIL); gl.getParameter(gl.STENCIL_PASS_DEPTH_PASS); gl.getParameter(gl.STENCIL_PASS_DEPTH_FAIL); gl.getParameter(gl.STEN...
WebGLRenderingContext.stencilOpSeparate() - Web APIs
Syntax void gl.stencilOpSeparate(face, fail, zfail, zpass); Parameters The fail, zfail and zpass parameters accept all constants listed below. face A GLenum specifying whether the front and/or back stencil state is updated. The possible values are: gl.FRONT gl.BACK gl.FRONT_AND_BACK fail A GLenum specifying the function to use when the stencil test fails. The default value is gl.KEEP. zfail A GLenum specifying the function to use when the stencil test passes, but the depth test fails. The default value is gl.KEEP. ...
... both the stencil test and the depth test pass, or when the stencil test passes and there is no depth buffer or depth testing is disabled. The default value is gl.KEEP. Return value None. Constants gl.KEEP Keeps the current value. gl.ZERO Sets the stencil buffer value to 0. gl.REPLACE Sets the stencil buffer value to the reference value as specified by WebGLRenderingContext.stencilFunc
(). gl.INCR Increments the current stencil buffer value. Clamps to the maximum representable unsigned value. gl.INCR_WRAP Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing the maximum representable unsigned value. gl.DECR Decrements the current stencil buffer value. Clamps to 0. gl.DECR_WRAP Decrements the current stencil buffer value. Wraps st...
...ents the current stencil buffer value. Clamps to 0. gl.DECR_WRAP Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable unsigned value when decrementing a stencil buffer value of 0. gl.INVERT Inverts the current stencil buffer value bitwise. Examples The stencil testing is disabled by default. To enable or disable stencil testing, use the enable
() and disable
() methods with the argument gl.STENCIL_TEST. gl.enable(gl.STENCIL_TEST); gl.stencilOpSeparate(gl.FRONT, gl.INCR, gl.DECR, gl.INVERT); To get the current information about stencil and depth pass or fail, query the following constants with getParameter
(). gl.getParameter(gl.STENCIL_FAIL); gl.getParameter(gl.STENCIL_PASS_DEPTH_PASS); gl.getParameter(gl.STENCIL_PASS_DEPTH_FAIL); gl.ge...
Window.close() - Web APIs
The Window.close
() method closes the current window, or the window on which it was called. This method can only be called on windows that were opened by a script using the Window.open
() method. If the window was not opened by a script, an error similar to this one appears in the console: Scripts may not close windows that were not opened by script. Note also that close
() has no effect when called on Window objects returned by HTMLIFrameElement.contentWindow. Syntax window.close
(); Examples Closing a window opened with window.open
() This example shows a method which opens a window and a second one which closes the window; this demonstrates how to use Window.close
() to close a window opened by calling window.open
(). //Global var to store a reference to the opened window var openedWind...
...ned by HTMLIFrameElement.contentWindow. Syntax window.close
(); Examples Closing a window opened with window.open
() This example shows a method which opens a window and a second one which closes the window; this demonstrates how to use Window.close
() to close a window opened by calling window.open
(). //Global var to store a reference to the opened window var openedWindow; function openWindow
() { openedWindow = window.open('moreinfo.htm'); } function closeOpenedWindow
() { openedWindow.close
(); } Closing the current window In the past, when you called the window object's close
() method directly, rather than calling close
() on a window instance, the browser closed the frontmost window, whether your script created that window or not. This is no longer the case; for security reasons...
...led the window object's close
() method directly, rather than calling close
() on a window instance, the browser closed the frontmost window, whether your script created that window or not. This is no longer the case; for security reasons, scripts are no longer allowed to close windows they didn't open. (Firefox 46.0.1: scripts can not close windows, they had not opened) function closeCurrentWindow
() { window.close
(); } Specification Specification Status Comment HTML Living StandardThe definition of 'window.close
()' in that specification. Living Standard HTML5The definition of 'Window.close
()' in that specification. Recommendation ...
window.dump() - Web APIs
window.dump
() prints messages to the (native) console. Syntax window.dump(message); dump(message); Parameters message is the string message to log. Notes A common use of dump
() is to debug JavaScript. The message passed to dump
() is sent to the System Console (Native Console) if the Firefox process was started with the -console option. If the -console option was not specified then the output goes to stderr. Output from dump
() is not sent to the Browser Console. Output can be sent to the Browser Console using console.log
(). Privileged code can also use Components.utils.reportError and nsIConsoleService to log messages to the Error Console/Browser Console. ...
...It is also explicitly made available in sandboxes. ...
...mentioned below -- it will always be shown. It is therefore advisable to either check this preference yourself or use a debugging preference of your own to make sure you don't send lots of debugging content to a user's console when they might not be interested in it at all. Note that dump output from XPCOM components goes to stderr, while dump called elsewhere will output to stdout. In Gecko dump
() is disabled by default - it doesn't do anything but doesn't raise an error either. To see the dump output you have to enable it by setting the preference browser.dom.window.dump.enabled to true. You can set the preference in about:config or in a user.js file. Note: this preference is not listed in about:config by default, you may need to create it (right-click the content area -> New -> Boolean).
Window.getComputedStyle() - Web APIs
Individual CSS property values are accessed through APIs provided by the object, or by indexing with CSS property names. Syntax var style = window.getComputedStyle(element [, pseudoElt]); element The Element for which to get the computed style. pseudoEltOptional A string specifying the pseudo-element to match. Omitted (or null) for real elements. The returned style is a live CSSStyleDeclaration object, which updates automatically when the element's styles are changed. ...
...t for which to get the computed style. pseudoEltOptional A string specifying the pseudo-element to match. Omitted (or null) for real elements. The returned style is a live CSSStyleDeclaration object, which updates automatically when the element's styles are changed. Throws TypeError If the passed object is not an Element or the pseudoElt is not a valid pseudo-element selector or is ::part
() or ::slotted
(). Note: Valid pseudo-element selector refers to syntactic validity, e.g. ::unsupported is considered valid, even though the pseudo-element itself is not supported. Examples In this example we style a <p> element, then retrieve those styles using getComputedStyle
(), and print them into the text content of the <p>. HTML <p>Hello</p> CSS p { width: 400px; margin: 0 ...
...Kit. In Firefox, properties with the value auto return the used value, not the value auto. So if you apply top:auto and bottom:0 on an element with height:30px and a containing block of height:100px, Firefox's computed style for top returns 70px, as 100 - 30 = 70. Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'getComputedStyle
()' in that specification. Working Draft Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'getComputedStyle
()' in that specification. Obsolete Initial definition ...
Window.matchMedia() - Web APIs
Syntax mqList = window.matchMedia(mediaQueryString) Parameters mediaQueryString A string specifying the media query to parse into a MediaQueryList. Return value A new MediaQueryList object for the media query. Use this object's properties and events to detect matches and to monitor for changes to those matches over time. Usage notes You can use the returned media query to perform both instantanteous and event-driven checks to see if the document matches the media query. ...
...diaQueryList's matches property in a <span>; as a result, the output will say "true" if the viewport is less than or equal to 600 pixels wide, and will say "false" if the window is wider than that. JavaScript let mql = window.matchMedia('(max-width: 600px)'); document.querySelector(".mq-value").innerText = mql.matches; The JavaScript code simply passes the media query to match into matchMedia
() to compile it, then sets the <span>'s innerText to the value of the results' matches property, so that it indicates whether or not the document matches the media query at the moment the page was loaded. HTML <span class="mq-value"></span> A simple <span> to receive the output. CSS .mq-value { font: 18px arial, sans-serif; font-weight: bold; color: #88f; padding: 0.4em; border: 1px...
...mple <span> to receive the output. CSS .mq-value { font: 18px arial, sans-serif; font-weight: bold; color: #88f; padding: 0.4em; border: 1px solid #dde; } Result See Testing media queries programmatically for additional code examples. Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'Window.matchMedia
()' in that specification. Working Draft Initial definition ...
Window.resizeBy() - Web APIs
The Window.resizeBy
() method resizes the current window by a specified amount. Syntax window.resizeBy(xDelta, yDelta) Parameters xDelta is the number of pixels to grow the window horizontally. yDelta is the number of pixels to grow the window vertically. Example // Shrink the window window.resizeBy(-200, -200); Notes This method resizes the window relative to its current size. To resize the window in absolute terms, use window.resizeTo
(). Creating and resizing an external window For security reasons, it's no longer possible in Firefox for a website to change the default size of a window in a browser if the window wasn't created by window.open
(), or contains more than one tab. See the compatability table for details on the change. ...
...To make the window resizable, you must open it with the "resizable" feature. ...
... Working Draft ...
self.createImageBitmap() - Web APIs
The method exists on the global scope in both windows and workers. It accepts a variety of different image sources, and returns a Promise which resolves to an ImageBitmap. Syntax const imageBitmapPromise = createImageBitmap(image[, options]); const imageBitmapPromise = createImageBitmap(image, sx, sy, sw, sh[, options]); Parameters image An image source, which can be an <img>, SVG <image>, <video>, <canvas>, HTMLImageElement, SVGImageElement, HTMLVideoElement, HTMLCanvasElement, Blob, ImageData, ImageBitmap, or OffscreenCanvas object. ...
...from the given rectangle. Example Creating sprites from a sprite sheet This example loads a sprite sheet, extracts individual sprites, and then renders each sprite to the canvas. A sprite sheet is an image containing multiple smaller images, each of which you want to be able to render separately. ...
...e sheet This example loads a sprite sheet, extracts individual sprites, and then renders each sprite to the canvas. A sprite sheet is an image containing multiple smaller images, each of which you want to be able to render separately. ...
Worker() - Web APIs
This script must obey the same-origin policy. Note: that there is a disagreement among browser manufacturers about whether a data URI is of the same origin or not. Though Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7) and later accept data URIs, that's not the case in all other browsers. Syntax var myWorker = new Worker(aURL, options); Parameters aURL A USVString representing the URL of the script the worker will execute. It must obey the same-origin policy. options Optional An object containing option properties that can be set when creating the object instance. Available properties are as follows: type: A DOMString specifying the type of worker to create. ...
...Error is raised if the document is not allowed to start workers, e.g. if the URL has an invalid syntax or if the same-origin policy is violated. A NetworkError is raised if the MIME type of the worker script is incorrect. It should always be text/javascript. A SyntaxError is raised if aURL cannot be parsed. Examples The following code snippet shows creation of a Worker object using the Worker
() constructor and subsequent usage of the object: var myWorker = new Worker('worker.js'); first.onchange = function
() { myWorker.postMessage([first.value,second.value]); console.log('Message posted to worker'); } For a full example, see our Basic dedicated worker example (run dedicated worker). Specifications Specification Status Comment HTML Living StandardThe defi...
...subsequent usage of the object: var myWorker = new Worker('worker.js'); first.onchange = function
() { myWorker.postMessage([first.value,second.value]); console.log('Message posted to worker'); } For a full example, see our Basic dedicated worker example (run dedicated worker). Specifications Specification Status Comment HTML Living StandardThe definition of 'Worker
()' in that specification. Living Standard ...
XMLHttpRequest.overrideMimeType() - Web APIs
Syntax XMLHttpRequest.overrideMimeType(mimeType) Parameters mimeType A DOMString specifying the MIME type to use instead of the one specified by the server. If the server doesn't specify a type, XMLHttpRequest assumes "text/xml". Return value undefined. ...
... Syntax XMLHttpRequest.overrideMimeType(mimeType) Parameters mimeType A DOMString specifying the MIME type to use instead of the one specified by the server. If the server doesn't specify a type, XMLHttpRequest assumes "text/xml". Return value undefined. ...
...turn value undefined. Example This example specifies a MIME type of "text/plain", overriding the server's stated type for the data being received. Note: If the server doesn't provide a Content-Type header, XMLHttpRequest assumes that the MIME type is "text/xml". If the content isn't valid XML, an "XML Parsing Error: not well-formed" error occurs. You can avoid this by calling overrideMimeType
() to specify a different type. // Interpret the received data as plain text req = new XMLHttpRequest
(); req.overrideMimeType("text/plain"); req.addEventListener("load", callback, false); req.open("get", url); req.send
(); Specifications Specification Status Comment XMLHttpRequestThe definition of 'overrideMimeType
()' in that specification. Living Standard WHATWG l...
XMLSerializer.serializeToString() - Web APIs
Syntax xmlString = anXMLSerializer.serializeToString(rootNode); Parameters rootNode The Node to use as the root of the DOM tree or subtree for which to construct an XML representation. Return value A DOMString containing the XML representation of the specified DOM tree. Exceptions TypeError The specified rootNode is not a compatible node type. The root node must be either Node or Attr. InvalidStateError The tree could not be successfully serialized, probably due to issues with the content's compatibility with XML serialization. ...
...er a Node or Attr object. The following types are also permitted as descendants of the root node, in addition to Node and Attr: DocumentType Document DocumentFragment Element Comment Text ProcessingInstruction Attr If any other type is encountered, a TypeError exception is thrown. Notes on the resulting XML There are some things worth noting about the XML output by serializeToString
(): For XML serializations, Element and Attr nodes are always serialized with their namespaceURI intact. This may mean that a previously-specified prefix or default namespace may be dropped or altered. The resulting XML is compatible with the HTML parser. Elements in the HTML namespace that have no child nodes (thereby representing empty tags) are serialized with both begin and end tags ("<some...
...L is compatible with the HTML parser. Elements in the HTML namespace that have no child nodes (thereby representing empty tags) are serialized with both begin and end tags ("<someelement></someelement>") instead of using the empty-element tag ("<someelement/>"). Specifications Specification Status Comment DOM Parsing and SerializationThe definition of 'serializeToString
()' in that specification. Working Draft ...
XPathEvaluator.createExpression() - Web APIs
tions INVALID_EXPRESSION_ERR If the expression is not legal according to the rules of the XPathEvaluator, an XPathException of type INVALID_EXPRESSION_ERR is raised. NAMESPACE_ERR If the expression contains namespace prefixes which cannot be resolved by the specified XPathNSResolver, a DOMException of type NAMESPACE_ERROR is raised. ...
...d. NAMESPACE_ERR If the expression contains namespace prefixes which cannot be resolved by the specified XPathNSResolver, a DOMException of type NAMESPACE_ERROR is raised. Example The following example shows the use of the evaluate
() method. ...
...or
(); var expression = evaluator.createExpression("//div"); var result = expression.evaluate(document, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE); document.querySelector("output").textContent = result.snapshotLength; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathEvaluator.createExpression
()' in that specification. Recommendation Initial definition ...
XPathEvaluator.evaluate() - Web APIs
Syntax XPathResult XPathEvaluator.evaluate(expression, contextNode, resolver, type, result); Parameters expression A DOMString representing the XPath expression to be parsed and evaluated. contextNode A Node representing the context to use for evaluating the expression. resolver Optional Permits translation of all prefixes, including the xml namespace prefix, within the XPath expression into appropriate namespace URIs. type Optional Specifies the type of result to be returned by evaluating the expression. This must be one of the XPathResult.Constants. ...
...ontext node is from a document that is not supported by the XPathEvaluator, a DOMException of type WRONG_DOCUMENT_ERR is raised. NOT_SUPPORTED_ERR If the provided context node is not a type permitted as an XPath context node or the request type is not permitted by the XPathEvaluator, a DOMException of type NOT_SUPPORTED_ERR is raised. ...
...ERR If the provided context node is not a type permitted as an XPath context node or the request type is not permitted by the XPathEvaluator, a DOMException of type NOT_SUPPORTED_ERR is raised. Example The following example shows the use of the evaluate
() method. HTML <div>XPath example</div> <div>Number of <div>s: <output></output></div> JavaScript var evaluator = new XPathEvaluator
(); var result = evaluator.evaluate("//div", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE); document.querySelector("output").textContent = result.snapshotLength; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathEvaluator.evaluate
()' in that specification. Recommendation Init...
XRFrame.getViewerPose() - Web APIs
The getViewerPose
() method, a member of the XRFrame interface, returns a XRViewerPose object which describes the viewer's pose (position and orientation) relative to the specified reference space. See the getPose
() method for a way to calculate a pose that represents the difference between two spaces. Syntax var xrViewerPose = xrFrame.getViewerPose(referenceSpace); Parameters referenceSpace An XRReferenceSpace object specifying the space to use as the reference point or base for the computation of the viewer's current pose. Return value A XRViewerPose describing the viewer's position and orientation relative to the specified reference space. ...
....getViewerPose(referenceSpace); Parameters referenceSpace An XRReferenceSpace object specifying the space to use as the reference point or base for the computation of the viewer's current pose. Return value A XRViewerPose describing the viewer's position and orientation relative to the specified reference space. Exceptions InvalidStateError A DOMException indicating that getViewerPose
() was not called within the context of a callback to a session's XRSession.requestAnimationFrame
(). Examples In this callback function for requestAnimationFrame
(), the XRViewerPose describing the viewer's viewpoint on the world is obtained by calling getViewerPose
() on the XRFrame passed into the callback. viewerPose = xrFrame.getViewerPose(xrReferenceSpace); if (viewerPose) { /* render the ...
... world is obtained by calling getViewerPose
() on the XRFrame passed into the callback. viewerPose = xrFrame.getViewerPose(xrReferenceSpace); if (viewerPose) { /* render the pose's views */ } To see a complete example, take a look at Movement, orientation, and motion. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRFrame.getViewerPose
()' in that specification. Working Draft Initial definition. ...
XRInputSourceArray.keys() - Web APIs
The keys
() method in the XRInputSourceArray interface returns a JavaScript iterator which can then be used to iterate over the keys used to reference each item in the array of input sources. Syntax xrInputSourceArray.keys
(); Parameters None. Return value A JavaScript iterator that can be used to walk through the keys for each entry in the list of input sources. The values returned by the iterator are the indexes of each entry in the list; that is, the numbers 0, 1, 2, and so forth through the index of the last item in the list. Examples This example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using. ...
...or each entry in the list of input sources. The values returned by the iterator are the indexes of each entry in the list; that is, the numbers 0, 1, 2, and so forth through the index of the last item in the list. Examples This example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using. for (const inputIdx of xrSession.inputSources.keys
()) { /* the keys are the indexes into the list of inputs */ checkInput(xrSession.inputSources[inputIdx]); } Here, for...of is used to iterate over each of the keys. For each key, the input is retrieved using the index with array notation: xrSession.inputSources[inputIdx]. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRInputSource...
...ession.inputSources[inputIdx]. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRInputSourceArray' in that specification.1 Working Draft XRInputSourceArray interface [1] See Iterator-like methods in Information contained in a WebIDL file for information on how an iterable declaration in an interface definition causes entries
(), forEach
(), keys
(), and values
() methods to be exposed from objects that implement the interface. ...
XRInputSourceArray.values() - Web APIs
The XRInputSourceArray method values
() returns a JavaScript iterator that can walk over the list of XRInputSource objects contained in the array, from first to last. Syntax xrInputSourceArray.values
(); Parameters None. Return value A JavaScript iterator that can be used to walk through the list of XRInputSource objects in the array, starting with the first entry (at index 0) and proceeding straight through the list. Examples This example snippet walks through each input and calls the function checkInput
() with each returned value. for (const source of xrSession.inputSources.values
()) { checkInput(source); } Here, for...of is used to iterate over the array's contents. Each pass through the loop, source is the next XRInputSource in the list. The loop exits once every input h...
...xamples This example snippet walks through each input and calls the function checkInput
() with each returned value. for (const source of xrSession.inputSources.values
()) { checkInput(source); } Here, for...of is used to iterate over the array's contents. Each pass through the loop, source is the next XRInputSource in the list. The loop exits once every input has been delivered to checkInput
(). ...
...een delivered to checkInput
(). Specifications Specification Status Comment WebXR Device APIThe definition of 'XRInputSourceArray' in that specification.1 Working Draft XRInputSourceArray interface [1] See Iterator-like methods in Information contained in a WebIDL file for information on how an iterable declaration in an interface definition causes entries
(), forEach
(), keys
(), and values
() methods to be exposed from objects that implement the interface. ...
XRRigidTransform() - Web APIs
Among other things, XRRigidTransform is used when providing a transform to translate between coordinate systems across spaces. Syntax let xrRigidTransform = new XRRigidTransform(position, orientation); Parameters position Optional An object conforming to DOMPointInit which specifies the coordinates at which the point or object is located. These dimensions are specified in meters. If this parameter is left out or is not compatible with DOMPointInit, the position used is assumed to be {x: 0, y: 0, z: 0, w: 1}. w must always be 1. ...
...rOrientation)); animationFrameRequestID = xrSession.requestAnimationFrame(drawFrame); }); After requesting a reference space of type local-floor, the returned promise is eventually resolved, at which time we receive a new reference space object, refSpace. After creating an XRRigidTransform from the viewer's initial position and orientation, we pass the new transform into getOffsetReferenceSpace
() to create another reference space, now offset so that its origin is located at the same place in space as the coordinates given by viewerPosition, with the orientation also revised in the same fashion. Then requestAnimationFrame
() is called to ask for a new animation frame to draw into. The drawFrame
() callback will be executed when the system is ready to draw the next frame. You can find more ...
...o revised in the same fashion. Then requestAnimationFrame
() is called to ask for a new animation frame to draw into. The drawFrame
() callback will be executed when the system is ready to draw the next frame. You can find more examples in Movement, orientation, and motion. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRRigidTransform
()' in that specification. Working Draft Initial definition. ...
XRSession.requestReferenceSpace() - Web APIs
The "Interface" column in the table below indicates which of the two types is returned for each reference space type constant.. ...
...s appropriate given the type of reference space requested. Syntax refSpacePromise = xrSession.requestReferenceSpace(referenceSpaceType); Parameters type A DOMString specifying the type of reference space for which an instance is to be returned. The string must be one of those found in the XRReferenceSpaceType enumerated type. The reference space returned by XRSession.requestReferenceSpace
() is either XRReferenceSpace or XRBoundedReferenceSpace. The "Interface" column in the table below indicates which of the two types is returned for each reference space type constant.. Reference space descriptors The types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. XRReferenceSpaceType ...
...r inline sessions. It's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces. Otherwise, typically, one of the other reference space types will be used more often. XRReferenceSpace Return value A Promise that resolves with an XRReferenceSpace object. Exceptions Rather than throwing true exceptions, requestReferenceSpace
() rejects the returned promise with a DOMException whose name is found in the list below: NotSupportedError The requested reference space is not supported. Specifications Specification Status Comment WebXR Device APIThe definition of 'requestReferenceSpace
()' in that specification. Working Draft Initial definition. ...
XRSession.updateRenderState() - Web APIs
Syntax xrSession.updateRenderState(newState) Parameters newState An object conforming to the XRRenderStateInit dictionary specifying the properties of the session's renderState to update before rendering the next frame. The specified object may have any combination of the following fields. baseLayer Optional An XRWebGLLayer object from which the WebXR compositor will obtain imagery. This is null by default. ...
...Exceptions This method may throw any of the following exceptions. These are true exceptions, since this method does not return a promise. InvalidStateError This may occur for one of the following reasons: The XRSession has already ended, so you cannot change its render state. The baseLayer specified in newState was created by an XRSession other than the one on which updateRenderState
() was called. The inlineVerticalFieldOfView property was set, but the session is immersive and therefore does not allow this property to be used. Examples This example creates a WebGL context that is compatible with an immersive XR device and then uses it to create an XRWebGLLayer. updateRenderState
() is then called to associate the new XRWebGLLayer. function onXRSessionStarted(xrSession)...
... used. Examples This example creates a WebGL context that is compatible with an immersive XR device and then uses it to create an XRWebGLLayer. updateRenderState
() is then called to associate the new XRWebGLLayer. function onXRSessionStarted(xrSession) { let glCanvas = document.createElement("canvas"); let gl = glCanvas.getContext("webgl", { xrCompatible: true }); loadWebGLResources
(); xrSession.updateRenderState({ baseLayer: new XRWebGLLayer(xrSession, gl) }); } Specifications Specification Status Comment WebXR Device APIThe definition of 'XRSession.updateRenderState
()' in that specification. Working Draft Initial definition. ...
XRSessionEvent() - Web APIs
These objects represent events announcing state changes in an XRSession representing an augmented or virtual reality session. Syntax newXRSessionEvent = new XRSessionEvent(type, eventInitDict); Parameters type A DOMString indicating which of the events represented by objects of type XRSessionEvent this particular object represents. See Event types for a list of the permitted values. eventInitDict An object conforming to the XRSessionEventInit dictionary which contains values to be applied to the newly-created event object. Permitted values are: session The XRSession to which the event is to be delivered. ...
...rface, and are permitted values for its type property. end Fired at the session when it has ended, after being terminated by the application or the user agent. visibilitychange Fired at the session whenever its visibility state changes. Examples This example creates a listiener that watches for the visibility state of the session to change. It reacts by calling a function mySessionVisible
() with a Boolean indicating whether or not the session is visible; this function might, for instance, spin up or reconfigure a worker that handles rendering the scene. xrSession.addEventListener("visibilitystate", e => { switch(e.session.visibilitystate) { case "visible": case "visible-blurred": mySessionVisible(true); break; case "hidden": mySessionVisible(false); ...
... rendering the scene. xrSession.addEventListener("visibilitystate", e => { switch(e.session.visibilitystate) { case "visible": case "visible-blurred": mySessionVisible(true); break; case "hidden": mySessionVisible(false); break; } }); Specifications Specification Status Comment WebXR Device APIThe definition of 'XRSessionEvent
() constructor' in that specification. Working Draft Initial definition. ...
XRWebGLLayer() - Web APIs
Syntax let glLayer = new XRWebGLLayer(session, context, layerInit); Parameters session An XRSession object specifying the WebXR session which will be rendered using the WebGL context. context A WebGLRenderingContext or WebGL2RenderingContext identifying the WebGL drawing context to use for rendering the scene for the specified WebXR session. layerInit Optional An object conforming to the XRWebGLLayerInit dictionary, providing configuration options for the new XRWebGLLayer. ...
...lean value which, if true, requests that the new layer have a depth buffer; otherwise, no depth layer is allocated. The default is true. framebufferScaleFactor Optional A floating-point value which is used to scale the image during compositing, with a value of 1.0 represents the default pixel size for the frame buffer. The static XRWebGLLayer function XRWebGLLayer.getNativeFramebufferScaleFactor
() returns the scale that would result in a 1:1 pixel ratio, thereby ensuring that the rendering is occurring at the device's native resolution. The default is 1.0. ignoreDepthValues Optional A Boolean value which indicates whether or not to ignore the contents of the depth buffer while compositing the scene. The default is false. stencil Optional A Boolean value which, if true, requests that th...
... Working Draft Initial definition. ...
XRWebGLLayer.getViewport() - Web APIs
For WebXR devices which use a single framebuffer for both the left and right eyes, the returned viewport represents the region of the framebuffer into which the scene should be rendered for the eye represented by the view. Syntax let viewport = xrWebGLLayer.getViewport(view); Parameters view An XRView object indicating the view for which the viewport is to be returned. Return value A XRViewport object representing the viewport which will restrict drawing to the portion of the layer corresponding to the specified view. ...
...ue A XRViewport object representing the viewport which will restrict drawing to the portion of the layer corresponding to the specified view. Exceptions InvalidStateError Either the specified view is not in an active XRFrame or that XRFrame and the XRWebGLLayer are not part of the same WebXR session. Example This example demonstrates in part what the callback for the requestAnimationFrame
() function might look like, using getViewport
() to get the viewport so that drawing can be constrained to the area set aside for the eye whose viewpoint is currently being rendered. This works because the set of views returned by an XRViewerPose each represent one eye's perspective on the scene. Since the framebuffer is split in half, one half for each eye, setting the WebGL viewport to match the ...
... Working Draft Initial definition. ...
:dir() - CSS: Cascading Style Sheets
The :dir
() CSS pseudo-class matches elements based on the directionality of the text contained in them. /* Selects any element with right-to-left text */ :dir(rtl) { background-color: red; } The :dir
() pseudo-class uses only the semantic value of the directionality, i.e., the one defined in the document itself. It doesn't account for styling directionality, i.e., the directionality set by CSS properties such as direction. Note: Be aware that the behavior of the :dir
() pseudo-class is not equivalent to the [dir=...] attribute selectors. The latter match the HTML dir attribute, and ignore elements that lack it -- even if they inherit a direction from their parent. ...
...ity, i.e., the directionality set by CSS properties such as direction. Note: Be aware that the behavior of the :dir
() pseudo-class is not equivalent to the [dir=...] attribute selectors. The latter match the HTML dir attribute, and ignore elements that lack it -- even if they inherit a direction from their parent. (Similarly, [dir=rtl] and [dir=ltr] won't match the auto value.) In contrast, :dir
() will match the value calculated by the user agent, even if inherited. Note: In HTML, the direction is determined by the dir attribute. Other document types may have different methods. Syntax The :dir
() pseudo-class requires one parameter, representing the text directionality you want to target. Parameters ltr Target left-to-right elements. rtl Target right-to-left elements. Formal ...
... Working Draft Initial definition. ...
:host-context() - CSS: Cascading Style Sheets
In other words, this allows a custom element, or anything within that custom element's shadow DOM, to apply different styles based on its position within the outer DOM or classes/attributes applied to ancestor elements. One typical use of this is with a descendant selector expression -- for example h1 -- to select only instances of the custom element that are inside an <h1>. ...
...-context(h1):after { content: " - no links in headers!" } rules style the instance of the <context-span> element (the shadow host in this instance) inside the <h1>. We've used it to make it clear that the custom element shouldn't appear inside the <h1> in our design. Specifications Specification Status Comment CSS Scoping Module Level 1The definition of ':host-context
()' in that specification. Working Draft Initial definition. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for ...
... 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. ...
:lang() - CSS: Cascading Style Sheets
The :lang
() CSS pseudo-class matches elements based on the language they are determined to be in. /* Selects any <p> in English (en) */ p:lang(en) { quotes: '\201C' '\201D' '\2018' '\2019'; } Note: In HTML, the language is determined by a combination of the lang attribute, the <meta> element, and possibly by information from the protocol (such as HTTP headers). For other document types there may be other document methods for determining the language. Syntax Formal syntax :lang( <language-code> ) Parameter <language-code> A <string> representing the language you want to target. Acceptable values are specified in the HTML spec. Examples In this example, the :lang
() pseudo-class is used to match the parents of quote elements (<q>) using child combinators. Note that this doesn'...
... Recommendation Initial definition. ...
...8' '\2019'; } :lang(fr) > q { quotes: '<< ' ' >>'; } :lang(de) > q { quotes: '>>' '<<' '\2039' '\203A'; } Result Specifications Specification Status Comment Selectors Level 4The definition of ':lang
()' in that specification. Working Draft Adds wildcard language matching and comma-separated list of languages. Selectors Level 3The definition of ':lang
()' in that specification. Recommendation No significant change. CSS Level 2 (Revision 1)The definition of ':lang
()' in that specification. Recommendation Initial definition. ...
drop-shadow() - CSS: Cascading Style Sheets
The drop-shadow
() CSS function applies a drop shadow effect to the input image. Its result is a <filter-function>. 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. A drop shadow is effectively a blurred, offset version of the input image's alpha mask, drawn in a specific color and composited below the image. Note: This function is somewhat similar to the box-shadow property. The box-shadow property creates a rectangular shadow behind an element's entire box, while the drop-shadow
() filter function creates a shadow that conforms to the shape (alpha channel) of the image itself. Syntax drop-shadow(offset-x offse...
...a specific color and composited below the image. Note: This function is somewhat similar to the box-shadow property. The box-shadow property creates a rectangular shadow behind an element's entire box, while the drop-shadow
() filter function creates a shadow that conforms to the shape (alpha channel) of the image itself. Syntax drop-shadow(offset-x offset-y blur-radius color) The drop-shadow
() function accepts a parameter of type <shadow> (defined in the box-shadow property), with the exception that the inset keyword and spread parameters are not allowed. Parameters offset-x offset-y (required) Two <length> values that determine the shadow offset. offset-x specifies the horizontal distance, where negative values place the shadow to the left of the element. offset-y specifies the v...
...is used. Examples Setting a drop shadow using pixel offsets and blur radius /* Black shadow with 10px blur */ drop-shadow(16px 16px 10px black) Setting a drop shadow using rem offsets and blur radius /* Reddish shadow with 1rem blur */ drop-shadow(.5rem .5rem 1rem #e23) Specifications Specification Status Filter Effects Module Level 1The definition of 'drop-shadow
()' in that specification. Working Draft ...
minmax() - CSS: Cascading Style Sheets
It is used with CSS Grids. 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. ...
...tems occupying the grid track. auto As a maximum, identical to max-content. As a minimum it represents the largest minimum size (as specified by min-width/min-height) of the grid items occupying the grid track. ...
... Candidate Recommendation Initial definition ...
repeat() - CSS: Cascading Style Sheets
This function can be used in the CSS Grid properties grid-template-columns and grid-template-rows. ...
...ks being collapsed, if they're all empty.) A collapsed track is treated as having a single fixed track sizing function of 0px, and the gutters on either side of it collapse. For the purpose of finding the number of auto-repeated tracks, the user agent floors the track size to a user agent specified value (e.g., 1px), to avoid division by zero. Examples Specifying grid columns using repeat
() HTML <div id="container"> <div> This item is 50 pixels wide. </div> <div> Item with flexible width. </div> <div> This item is 50 pixels wide. </div> <div> Item with flexible width. </div> <div> Inflexible item of 100 pixels width. </div> </div> CSS #container { display: grid; grid-template-columns: repeat(2, 50px 1fr) 100px; grid-gap: 5px; box-s...
... Candidate Recommendation Initial definition ...
repeating-linear-gradient() - CSS: Cascading Style Sheets
The function's result is an object of the <gradient> data type, which is a special kind of <image>. 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. The length of the gradient that repeats is the distance between the first and last color stop. ...
...he first color again as the last color. As with any gradient, a repeating linear gradient has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. Its concrete size will match the size of the element it applies to. Because <gradient>s belong to the <image> data type, they can only be used where <image>s can be used. For this reason, repeating-linear-gradient
() won't work on background-color and other properties that use the <color> data type. Syntax /* A repeating gradient tilted 45 degrees, starting blue and finishing red, repeating 3 times */ repeating-linear-gradient(45deg, blue, red 33.3%); /* A repeating gradient going from the bottom right to the top left, starting blue and finishing red, repeating every 20px */ repeating-linear-gradient...
... Candidate Recommendation Initial definition. ...
repeating-radial-gradient() - CSS: Cascading Style Sheets
The function's result is an object of the <gradient> data type, which is a special kind of <image>. 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. ...
...ting the first color as the last color. As with any gradient, a repeating radial gradient has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. Its concrete size will match the size of the element it applies to. Because <gradient>s belong to the <image> data type, they can only be used where <image>s can be used. For this reason, repeating-radial-gradient
() won't work on background-color and other properties that use the <color> data type. Syntax /* A gradient at the center of its container, starting red, changing to blue, and finishing green, with the colors repeating every 30px */ repeating-radial-gradient(circle at center, red 0, blue, green 30px); /* An elliptical gradient near the top left of its container, starting red, changing to...
...pporting multi position color stops will display a red and green striped ellipse. Browsers not supporting the syntax yet will see a gradient that goes from red to black and then from blue to green. Note: Please see Using CSS gradients for more examples. Specifications Specification Status Comment CSS Images Module Level 3The definition of 'repeating-radial-gradient
()' in that specification. Candidate Recommendation Initial definition. ...
perspective() - CSS: Cascading Style Sheets
This differs from the perspective and perspective-origin properties which are attached to the parent of a child transformed in 3-dimensional space. ...
...z=0 plane, the perspective from which the viewer would be if the 2-dimensional interface were 3-dimensional. Its result is a <transform-function> data type. 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. The perspective
() transform function is part of the transform value applied on the element being transformed. This differs from the perspective and perspective-origin properties which are attached to the parent of a child transformed in 3-dimensional space. Syntax The perspective distance used by perspective
() is specified by a <length> value, which represents the distance between the user and the z=0 plane. The...
... Editor's Draft Initial definition ...
rotate() - CSS: Cascading Style Sheets
If positive, the movement will be clockwise; if negative, it will be counter-clockwise. A rotation by 180? is called point reflection. rotate(a) Values a Is an <angle> representing the angle of the rotation. ...
...nt around a fixed point on the 2D plane, without deforming it. Its result is a <transform-function> data type. The fixed point that the element rotates around -- mentioned above -- is also known as the transform origin. This defaults to the center of the element, but you can set your own custom transform origin using the transform-origin property. Syntax The amount of rotation created by rotate
() is specified by an <angle>. If positive, the movement will be clockwise; if negative, it will be counter-clockwise. A rotation by 180? is called point reflection. rotate(a) Values a Is an <angle> representing the angle of the rotation. A positive angle denotes a clockwise rotation, a negative angle a counter-clockwise one. Cartesian coordinates on R2 Homogeneous coordinates o...
... Working Draft Initial definition ...
rotate3d() - CSS: Cascading Style Sheets
Its result is a <transform-function> data type. 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. In 3D space, rotations have three degrees of liberty, which together describe a single axis of rotation. The axis of rotation is defined by an [x, y, z] vector and pass by the origin (as defined by the transform-origin property). ...
...ze it internally. A non-normalizable vector, such as the null vector, [0, 0, 0], will cause the rotation to be ignored, but without invaliding the whole CSS property. Note: Unlike rotations in the 2D plane, the composition of 3D rotations is usually not commutative. In other words, the order in which the rotations are applied impacts the result. Syntax The amount of rotation created by rotate3d
() is specified by three <number>s and one <angle>. The <number>s represent the x-, y-, and z-coordinates of the vector denoting the axis of rotation. The <angle> represents the angle of rotation; if positive, the movement will be clockwise; if negative, it will be counter-clockwise. rotate3d(x, y, z, a) Values x Is a <number> describing the x-coordinate of the vector denoting the axis of rot...
... Editor's Draft Initial definition ...
rotateX() - CSS: Cascading Style Sheets
The rotateX
() CSS function defines a transformation that rotates an element around the abscissa (horizontal axis) without deforming it. Its result is a <transform-function> data type. 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. The axis of rotation passes through an origin, defined by the transform-origin CSS property. Note: rotateX(a) is equivalent to rotate3d(1, 0, 0, a). Note: Unlike rotations in the 2D plane, the composition of 3D rotations is usually not commutative. In other words, the order in which the rotations are applied impacts the result. ...
... pull request. The axis of rotation passes through an origin, defined by the transform-origin CSS property. Note: rotateX(a) is equivalent to rotate3d(1, 0, 0, a). Note: Unlike rotations in the 2D plane, the composition of 3D rotations is usually not commutative. In other words, the order in which the rotations are applied impacts the result. Syntax The amount of rotation created by rotateX
() is specified by an <angle>. If positive, the movement will be clockwise; if negative, it will be counter-clockwise. rotateX(a) Values a Is an <angle> representing the angle of the rotation. A positive angle denotes a clockwise rotation, a negative angle a counter-clockwise one. Cartesian coordinates on R2 Homogeneous coordinates on RP2 Cartesian coordinates on R3 Homoge...
... Editor's Draft Initial definition ...
rotateY() - CSS: Cascading Style Sheets
The rotateY
() CSS function defines a transformation that rotates an element around the ordinate (vertical axis) without deforming it. Its result is a <transform-function> data type. 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. The axis of rotation passes through an origin, defined by the transform-origin CSS property. Note: rotateY(a) is equivalent to rotate3d(0, 1, 0, a). Note: Unlike rotations in the 2D plane, the composition of 3D rotations is usually not commutative. In other words, the order in which the rotations are applied impacts the result. ...
... pull request. The axis of rotation passes through an origin, defined by the transform-origin CSS property. Note: rotateY(a) is equivalent to rotate3d(0, 1, 0, a). Note: Unlike rotations in the 2D plane, the composition of 3D rotations is usually not commutative. In other words, the order in which the rotations are applied impacts the result. Syntax The amount of rotation created by rotateY
() is specified by an <angle>. If positive, the movement will be clockwise; if negative, it will be counter-clockwise. rotateY(a) Values a Is an <angle> representing the angle of the rotation. A positive angle denotes a clockwise rotation, a negative angle a counter-clockwise one. Cartesian coordinates on R2 Homogeneous coordinates on RP2 Cartesian coordinates on R3 Homoge...
... Editor's Draft Initial definition ...
rotateZ() - CSS: Cascading Style Sheets
The rotateZ
() CSS function defines a transformation that rotates an element around the z-axis without deforming it. Its result is a <transform-function> data type. 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. The axis of rotation passes through an origin, defined by the transform-origin CSS property. Note: rotateZ(a) is equivalent to rotate(a) or rotate3d(0, 0, 1, a). Note: Unlike rotations in the 2D plane, the composition of 3D rotations is usually not commutative. In other words, the order in which the rotations are applied impacts the result. ...
.... The axis of rotation passes through an origin, defined by the transform-origin CSS property. Note: rotateZ(a) is equivalent to rotate(a) or rotate3d(0, 0, 1, a). Note: Unlike rotations in the 2D plane, the composition of 3D rotations is usually not commutative. In other words, the order in which the rotations are applied impacts the result. Syntax The amount of rotation created by rotateZ
() is specified by an <angle>. If positive, the movement will be clockwise; if negative, it will be counter-clockwise. rotateZ(a) Values a Is an <angle> representing the angle of the rotation. A positive angle denotes a clockwise rotation, a negative angle a counter-clockwise one. Cartesian coordinates on R2 Homogeneous coordinates on RP2 Cartesian coordinates on R3 Homoge...
... Editor's Draft Initial definition ...
scale() - CSS: Cascading Style Sheets
The scale
() CSS function defines a transformation that resizes an element on the 2D plane. Because the amount of scaling is defined by a vector, it can resize the horizontal and vertical dimensions at different scales. Its result is a <transform-function> data type. This scaling transformation is characterized by a two-dimensional vector. Its coordinates define how much scaling is done in each direction. If both coordinates are equal, the scaling is uniform (isotropic) and the aspect ratio of the element is preserved (this is a homothetic transformation). When a coordinate value is outside the [-1, 1] range, the element grows along that dimension; when inside, it shrinks. If it is negative, the result a point reflection in that dimension. A value of 1 has no effect. ...
...ch direction. If both coordinates are equal, the scaling is uniform (isotropic) and the aspect ratio of the element is preserved (this is a homothetic transformation). When a coordinate value is outside the [-1, 1] range, the element grows along that dimension; when inside, it shrinks. If it is negative, the result a point reflection in that dimension. A value of 1 has no effect. Note: The scale
() function only scales in 2D. To scale in 3D, use scale3d
() instead. Syntax The scale
() function is specified with either one or two values, which represent the amount of scaling to be applied in each direction. scale(sx) scale(sx, sy) Values sx A <number> representing the abscissa of the scaling vector. sy A <number> representing the ordinate of the scaling vector. If not defined, its ...
... Working Draft Initial definition ...
scale3d() - CSS: Cascading Style Sheets
Because the amount of scaling is defined by a vector, it can resize different dimensions at different scales. Its result is a <transform-function> data type. 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. This scaling transformation is characterized by a three-dimensional vector. Its coordinates define how much scaling is done in each direction. If all three coordinates are equal, the scaling is uniform (isotropic) and the aspect ratio of the element is preserved (this is a homothetic transformation). ...
...ion. If all three coordinates are equal, the scaling is uniform (isotropic) and the aspect ratio of the element is preserved (this is a homothetic transformation). When a coordinate value is outside the [-1, 1] range, the element grows along that dimension; when inside, it shrinks. If it is negative, the result a point reflection in that dimension. A value of 1 has no effect. Syntax The scale3d
() function is specified with three values, which represent the amount of scaling to be applied in each direction. scale3d(sx, sy, sz) Values sx Is a <number> representing the abscissa of the scaling vector. sy Is a <number> representing the ordinate of the scaling vector. sz Is a <number> representing the z-component of the scaling vector. Cartesian coordinates on R2 Homoge...
... Editor's Draft Initial definition ...
skew() - CSS: Cascading Style Sheets
The skew
() CSS function defines a transformation that skews an element on the 2D plane. Its result is a <transform-function> data type. 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. This transformation is a shear mapping (transvection) that distorts each point within an element by a certain angle in the horizontal and vertical directions. The coordinates of each point are modified by a value proportionate to the specified angle and the distance to the origin; thus, the farther from the origin a point is, the greater will be the value added it. ...
...pull request. This transformation is a shear mapping (transvection) that distorts each point within an element by a certain angle in the horizontal and vertical directions. The coordinates of each point are modified by a value proportionate to the specified angle and the distance to the origin; thus, the farther from the origin a point is, the greater will be the value added it. Syntax The skew
() function is specified with either one or two values, which represent the amount of skewing to be applied in each direction. skew(ax) skew(ax, ay) Values ax Is an <angle> representing the angle to use to distort the element along the abscissa. ay Is an <angle> representing the angle to use to distort the element along the ordinate. If not defined, its default value is 0, resulting in a p...
... Working Draft Initial definition ...
translateZ() - CSS: Cascading Style Sheets
Its result is a <transform-function> data type. 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. This transformation is defined by a <length> which specifies how far inward or outward the element or elements move. In the above interactive examples, perspective: 550px; (to create a 3D space) and transform-style: preserve-3d; (so the children, the 6 sides of the cube, are also positioned in the 3D space), have been set on the cube. ...
...D space, then moved towards the user. HTML <div>Static</div> <div class="moved">Moved</div> CSS div { position: relative; width: 60px; height: 60px; left: 100px; background-color: skyblue; } .moved { transform: perspective(500px) translateZ(200px); background-color: pink; } What really matters here is the class "moved"; let's take a look at what it does. First, the perspective
() function positions the viewer relative to the plane that lies where z=0 (in essence, the surface of the screen). A value of 500px means the user is 500 pixels "in front of" the imagery located at z=0. Then, the translateZ
() function moves the element 200 pixels "outward" from the screen, toward the user. This has the effect of making the element appear larger when viewed on a 2D display, or clos...
...the surface of the screen). A value of 500px means the user is 500 pixels "in front of" the imagery located at z=0. Then, the translateZ
() function moves the element 200 pixels "outward" from the screen, toward the user. This has the effect of making the element appear larger when viewed on a 2D display, or closer when viewed using a VR headset or other 3D display device. Note if the perspective
() value is less than the translateZ
() value, such as transform: perspective(200px) translateZ(300px); the transformed element will not be visible as it is further than the user's viewport. The smaller the difference between the perspective and transform values, the closer the user is to the element and the larger the translated element will seem. Result Specifications Specification ...
var() - CSS: Cascading Style Sheets
(Doing so usually produces invalid syntax, or else a value whose meaning has no connection to the variable.) Syntax The first argument to the function is the name of the custom property to be substituted. An optional second argument to the function serves as a fallback value. ...
...(Doing so usually produces invalid syntax, or else a value whose meaning has no connection to the variable.) Syntax The first argument to the function is the name of the custom property to be substituted. An optional second argument to the function serves as a fallback value. ...
... Candidate Recommendation Initial definition ...
Array.isArray() - JavaScript
The Array.isArray
() method determines whether the passed value is an Array. Array.isArray([1, 2, 3]); // true Array.isArray({foo: 123}); // false Array.isArray('foobar'); // false Array.isArray(undefined); // false Syntax Array.isArray(value) Parameters value The value to be checked. Return value true if the value is an Array; otherwise, false. Description If the value is an Array, true is returned; otherwise, false is. See the article "Determining with absolute accuracy whether or not a JavaScript object is an array" for more details. Given a TypedArray instance, false is always returned. Polyfill Running the following code before any other code will create Array.isArray
() if it's not natively available. if (!Array.isArray) { Array.isArray = function(arg) { re...
...lways returned. Polyfill Running the following code before any other code will create Array.isArray
() if it's not natively available. ...
... var iframe = document.creat...
Array.prototype.slice() - JavaScript
The original array will not be modified. The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax arr.slice([start[, end]]) Parameters start Optional Zero-based index at which to start extraction. A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence. If start is undefined, slice starts from the index 0. ...
...: {cylinders: 4, size: 2.2}}, 2] myCar[0].color = red newCar[0].color = red The new color of my Honda is purple myCar[0].color = purple newCar[0].color = purple Array-like objects slice method can also be called to convert Array-like objects/collections to a new Array. You just bind the method to the object. The arguments inside a function is an example of an 'array-like object'. function list
() { return Array.prototype.slice.call(arguments) } let list1 = list(1, 2, 3) // [1, 2, 3] Binding can be done with the call
() method of Function.prototype and it can also be reduced using [].slice.call(arguments) instead of Array.prototype.slice.call. Anyway, it can be simplified using bind. let unboundSlice = Array.prototype.slice let slice = Function.prototype.call.bind(unboundSlice) func...
...rn Array.prototype.slice.call(arguments) } let list1 = list(1, 2, 3) // [1, 2, 3] Binding can be done with the call
() method of Function.prototype and it can also be reduced using [].slice.call(arguments) instead of Array.prototype.slice.call. Anyway, it can be simplified using bind. let unboundSlice = Array.prototype.slice let slice = Function.prototype.call.bind(unboundSlice) function list
() { return slice(arguments) } let list1 = list(1, 2, 3) // [1, 2, 3] Specifications Specification ECMAScript (ECMA-262)The definition of 'Array.prototype.slice' in that specification. ...
Array.prototype.toLocaleString() - JavaScript
Return value A string representing the elements of the array. ...
...ated by a locale-specific String (such as a comma ","). Syntax arr.toLocaleString([locales[, options]]); Parameters locales Optional A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the Intl page. options Optional An object with configuration properties, for numbers see Number.prototype.toLocaleString
(), and for dates see Date.prototype.toLocaleString
(). Return value A string representing the elements of the array. Polyfill // https://tc39.github.io/ecma402/#sup-array.prototype.tolocalestring if (!Array.prototype.toLocaleString) { Object.defineProperty(Array.prototype, 'toLocaleString', { value: function(locales, options) { // 1. Let O be ? ToObject(this value). if (this ...
... R. return r; } }); } If you need to support truly obsolete JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable. Examples Using locales and options The elements of the array are converted to strings using their toLocaleString methods. Object: Object.prototype.toLocaleString
() Number: Number.prototype.toLocaleString
() Date: Date.prototype.toLocaleString
() Always display the currency for the strings and numbers in the prices array: var prices = ['?7', 500, 8123, 12]; prices.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }); // "?7,?500,?8,123,?12" For more examples, see also the Intl, NumberFormat, and DateTimeFormat pages. Specifications ...
ArrayBuffer.isView() - JavaScript
The ArrayBuffer.isView
() method determines whether the passed value is one of the ArrayBuffer views, such as typed array objects or a DataView. 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 ArrayBuffer.isView(value) Parameters value The value to be checked. Return value true if the given argument is one of the ArrayBuffer views; otherwise, false. ...
...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 ArrayBuffer.isView(value) Parameters value The value to be checked. Return value true if the given argument is one of the ArrayBuffer views; otherwise, false. ...
...the ArrayBuffer views; otherwise, false. Examples Using isView ArrayBuffer.isView
(); // false ArrayBuffer.isView([]); // false ArrayBuffer.isView({}); // false ArrayBuffer.isView(null); // false ArrayBuffer.isView(undefined); // false ArrayBuffer.isView(new ArrayBuffer(10)); // false ArrayBuffer.isView(new Uint8Array
()); // true ArrayBuffer.isView(new Float32Array
()); // true ArrayBuffer.isView(new Int8Array(10).subarray(0, 3)); // true const buffer = new ArrayBuffer(2); const dv = new DataView(buffer); ArrayBuffer.isView(dv); // true Specifications Specification ECMAScript (ECMA-262)The definition of 'ArrayBuffer.isView' in that specification. ...
Date.prototype.setMonth() - JavaScript
The setMonth
() method sets the month for a specified date according to the currently set year. Syntax dateObj.setMonth(monthValue[, dayValue]) Versions prior to JavaScript 1.3 dateObj.setMonth(monthValue) Parameters monthValue A zero-based integer representing the month of the year offset from the start of the year. So, 0 represents January, 11 represents December, -1 represents December of the previous year, and 12 represents January of the following year. dayValue Optional. An integer from 1 to 31, representing the day of the month. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If you do not specify the dayValue parameter, the value returned from the getDate
() method is used. If a parameter you specify is o...
...ts January of the following year. dayValue Optional. An integer from 1 to 31, representing the day of the month. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If you do not specify the dayValue parameter, the value returned from the getDate
() method is used. If a parameter you specify is outside of the expected range, setMonth
() attempts to update the date information in the Date object accordingly. For example, if you use 15 for monthValue, the year will be incremented by 1, and 3 will be used for month. The current day of month will have an impact on the behaviour of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter...
...e an impact on the behaviour of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st August 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days. Examples Using setMonth
() var theBigDay = new Date
(); theBigDay.setMonth(6); //Watch out for end of month transitions var endOfMonth = new Date(2016, 7, 31); endOfMonth.setMonth(1); console.log(endOfMonth); //Wed Mar 02 2016 00:00:00 Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.setMonth' in that specification. ...
Date.prototype.setUTCMonth() - JavaScript
The setUTCMonth
() method sets the month for a specified date according to universal time. 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 dateObj.setUTCMonth(monthValue[, dayValue]) Parameters monthValue An integer between 0 and 11, representing the months January through December. dayValue Optional. An integer from 1 to 31, representing the day of the month. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If you do not specify the dayValue parameter, the value returned from the getUTCDate
() method is used. If a parameter you specif...
...s January through December. dayValue Optional. An integer from 1 to 31, representing the day of the month. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If you do not specify the dayValue parameter, the value returned from the getUTCDate
() method is used. If a parameter you specify is outside of the expected range, setUTCMonth
() attempts to update the date information in the Date object accordingly. ...
...Description If you do not specify the dayValue parameter, the value returned from the getUTCDate
() method is used. If a parameter you specify is outside of the expected range, setUTCMonth
() attempts to update the date information in the Date object accordingly. For example, if you use 15 for monthValue, the year will be incremented by 1, and 3 will be used for month. Examples Using setUTCMonth
() var theBigDay = new Date
(); theBigDay.setUTCMonth(11); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.setUTCMonth' in that specification. ...
Date.prototype.setUTCSeconds() - JavaScript
The setUTCSeconds
() method sets the seconds for a specified date according to universal time. 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 dateObj.setUTCSeconds(secondsValue[, msValue]) Parameters secondsValue An integer between 0 and 59, representing the seconds. msValue Optional. A number between 0 and 999, representing the milliseconds. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If you do not specify the msValue parameter, the value returned from the getUTCMilliseconds
() method is used. If a parameter you specify is outsi...
...senting the seconds. msValue Optional. A number between 0 and 999, representing the milliseconds. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If you do not specify the msValue parameter, the value returned from the getUTCMilliseconds
() method is used. If a parameter you specify is outside of the expected range, setUTCSeconds
() attempts to update the date information in the Date object accordingly. ...
... parameter, the value returned from the getUTCMilliseconds
() method is used. If a parameter you specify is outside of the expected range, setUTCSeconds
() attempts to update the date information in the Date object accordingly. For example, if you use 100 for secondsValue, the minutes stored in the Date object will be incremented by 1, and 40 will be used for seconds. Examples Using setUTCSeconds
() var theBigDay = new Date
(); theBigDay.setUTCSeconds(20); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.setUTCSeconds' in that specification. ...
Date.prototype.toTimeString() - JavaScript
The toTimeString
() method returns the time portion of a Date object in human readable form in American English. 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 dateObj.toTimeString
() Return value A string representing the time portion of the given date in human readable form in American English. Description Date instances refer to a specific point in time. Calling toString
() will return the date formatted in a human readable form in American English. In SpiderMonkey, this consists of the date portion (day, month, and year) followed by the time portion (hours, minutes, seconds, and time zone). Sometimes...
...ces refer to a specific point in time. Calling toString
() will return the date formatted in a human readable form in American English. In SpiderMonkey, this consists of the date portion (day, month, and year) followed by the time portion (hours, minutes, seconds, and time zone). Sometimes it is desirable to obtain a string of the time portion; such a thing can be accomplished with the toTimeString
() method. The toTimeString
() method is especially useful because compliant engines implementing ECMA-262 may differ in the string obtained from toString
() for Date objects, as the format is implementation-dependent; simple string slicing approaches may not produce consistent results across multiple engines. ...
...a thing can be accomplished with the toTimeString
() method. The toTimeString
() method is especially useful because compliant engines implementing ECMA-262 may differ in the string obtained from toString
() for Date objects, as the format is implementation-dependent; simple string slicing approaches may not produce consistent results across multiple engines. Examples A basic usage of toTimeString
() var d = new Date(1993, 6, 28, 14, 39, 7); console.log(d.toString
()); // Wed Jul 28 1993 14:39:07 GMT-0600 (PDT) console.log(d.toTimeString
()); // 14:39:07 GMT-0600 (PDT) Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.toTimeString' in that specification. ...
Generator.prototype.return() - JavaScript
The return
() method returns the given value and finishes the generator. Syntax gen.return(value) Parameters value The value to return. Return value The value that is given as an argument. Examples Using return
() The following example shows a simple generator and the return method. function* gen
() { yield 1; yield 2; yield 3; } const g = gen
(); g.next
(); // { value: 1, done: false } g.return('foo'); // { value: "foo", done: true } g.next
(); // { value: undefined, done: true } If return(value) is called on a generator that is already in "completed" state, the generator will remain in "completed" state. If no argument is provided, the value property of returned object is the same as if .next
(). If an argument is provided, it will be set to the value of th...
...true } g.next
(); // { value: undefined, done: true } If return(value) is called on a generator that is already in "completed" state, the generator will remain in "completed" state. If no argument is provided, the value property of returned object is the same as if .next
(). If an argument is provided, it will be set to the value of the value property of the returned object. ...
...rue } If return(value) is called on a generator that is already in "completed" state, the generator will remain in "completed" state. If no argument is provided, the value property of returned object is the same as if .next
(). If an argument is provided, it will be set to the value of the value property of the returned object. function* gen
() { yield 1; yield 2; yield 3; } const g = gen
(); g.next
(); // { value: 1, done: false } g.next
(); // { value: 2, done: false } g.next
(); // { value: 3, done: false } g.next
(); // { value: undefined, done: true } g.return
(); // { value: undefined, done: true } g.return(1); // { value: 1, done: true } Specifications Specification ECMAScript (ECMA-262)The definition of 'Generator.prototype.return' in that specification. ...
Intl.Collator.prototype.resolvedOptions() - JavaScript
Description The resulting object has the following properties: locale The BCP 47 language tag for the locale actually used. ...
...od returns a new object with properties reflecting the locale and collation options computed during initialization of this Collator object. 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 collator.resolvedOptions
() Return value A new object with properties reflecting the locale and collation options computed during the initialization of the given Collator object. Description The resulting object has the following properties: locale The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-val...
...locale, or "default". numeric caseFirst The values requested for these properties in the options argument or using the Unicode extension keys "kn" and "kf" or filled in as defaults. If the implementation does not support these properties, they are omitted. ...
Intl​.List​Format​.prototype​.formatToParts() - JavaScript
Each element of the resulting array has two properties: type and value. ...
...y of objects representing the different components that can be used to format a list of values in a locale-aware fashion. Syntax Intl.ListFormat.prototype.formatToParts(list) Parameters list An Array of values to be formatted according to a locale. Return value An Array of components which contains the formatted parts from the list. Description Whereas Intl.ListFormat.prototype.format
() returns a string being the formated version of the list (according to the given locale and style options), formatToParts
() returns an array of the different components of the formated string. Each element of the resulting array has two properties: type and value. The type property may be either "element", which refers to a value from the list, or "literal" which refers to a linguistic construct.
... ...
Intl.Locale.prototype.toString() - JavaScript
Description The Locale object is a JavaScript representation of a concept Unicode locale identifier. Information about a particular locale (language, script, calendar type, etc.) can be encoded in a locale identifier string. To make it easier to work with these locale identifiers, the Locale object was introduced to JavaScript. ...
... Description The Locale object is a JavaScript representation of a concept Unicode locale identifier. Information about a particular locale (language, script, calendar type, etc.) can be encoded in a locale identifier string. To make it easier to work with these locale identifiers, the Locale object was introduced to JavaScript. ...
...Locale. ...
Intl.NumberFormat.prototype.formatToParts() - JavaScript
The Intl.Numberformat.prototype.formatToParts
() method allows locale-aware formatting of strings produced by NumberFormat formatters. Syntax Intl.NumberFormat.prototype.formatToParts(number) Parameters number Optional A Number or BigInt to format. Return value An Array of objects containing the formatted number in parts. Description The formatToParts
() method is useful for custom formatting of number strings. It returns an Array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. ...
...ptional A Number or BigInt to format. Return value An Array of objects containing the formatted number in parts. Description The formatToParts
() method is useful for custom formatting of number strings. It returns an Array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. The structure the formatToParts
() method returns, looks like this: [ { type: "integer", value: "3" }, { type: "group", value: "." }, { type: "integer", value: "500" } ] Possible types are the following: currency The currency string, such as the symbols "$" and "EUR" or the name "Dollar", "Euro" depending on how currencyDisplay is specified. decimal The decimal separator string ("."). fraction The fraction number. ...
...alue: "3" }, { type: "group", value: "." }, { type: "integer", value: "500" }, { type: "decimal", value: "," }, { type: "fraction", value: "00" }, { type: "literal", value: " " }, { type: "currency", value: "EUR" } ] Now the information is available separately and it can be formatted and concatenated again in a customized way. For example by using Array.prototype.map
(), arrow functions, a switch statement, template literals, and Array.prototype.reduce
(). var numberString = formatter.formatToParts(number).map(({type, value}) => { switch (type) { case 'currency': return `<strong>${value}</strong>`; default : return value; } }).reduce((string, part) => string + part); This will make the currency bold, when using the formatToParts
() method. console.
Intl.PluralRules() constructor - JavaScript
Syntax new Intl.PluralRules([locales[, options]]) Parameters locales Optional. A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the Intl page. options Optional. An object with some or all of the following properties: localeMatcher The locale matching algorithm to use. Possible values are "lookup" and "best fit"; the default is "best fit". For information about this option, see the Intl page. type The type to use. Possible values are: "cardinal" for cardinal numbers (refering to the quantity of things). This is the default value. ...
... maximumSignificantDigits The maximum number of significant digits to use. Possible values are from 1 to 21; the default is 21. Examples Basic usage In basic use without specifying a locale, a formatted string in the default locale and with default options is returned. This is useful to distinguish between singular and plural forms, e.g. "dog" and "dogs". var pr = new Intl.PluralRules
(); pr.select(0); // -> 'other' if in US English locale pr.select(1); // -> 'one' if in US English locale pr.select(2); // -> 'other' if in US English locale Using options The results can be customized using the options argument, which has one property called type which you can set to ordinal. This is useful to figure out the ordinal indicator, e.g. "1st", "2nd", "3rd", "4th", "42nd" and so fo...
...", "2nd", "3rd", "4th", "42nd" and so forth. var pr = new Intl.PluralRules('en-US', { type: 'ordinal' }); pr.select(0); // -> 'other' pr.select(1); // -> 'one' pr.select(2); // -> 'two' pr.select(3); // -> 'few' pr.select(4); // -> 'other' pr.select(42); // -> 'two' Specifications Specification ECMAScript Internationalization API (ECMA-402)The definition of 'Intl.PluralRules
() constructor' in that specification. ...
Map.prototype.entries() - JavaScript
The entries
() method returns a new Iterator object that contains the [key, value] pairs for each element in the Map object in insertion order. 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 myMap.entries
() Return value A new Map iterator object. ...
...ins the [key, value] pairs for each element in the Map object in insertion order. 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 myMap.entries
() Return value A new Map iterator object. ...
...irs for each element in the Map object in insertion order. 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 myMap.entries
() Return value A new Map iterator object. Examples Using entries
() let myMap = new Map
() myMap.set('0', 'foo') myMap.set(1, 'bar') myMap.set({}, 'baz') let mapIter = myMap.entries
() console.log(mapIter.next
().value) // ["0", "foo"] console.log(mapIter.next
().value) // [1, "bar"] console.log(mapIter.next
().value) // [Object, "baz"] Specifications Specification ECMAScript (ECMA-262)The definition of 'Map.prototype.entries' in that specification. ...
Math.abs() - JavaScript
The Math.abs
() function returns the absolute value of a number, that is Math.abs(x)=|x|={xifx>00ifx=0-xifx<0{\mathtt{\operatorname{Math.abs}(z)}} = {|z|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ x & \text{if} \quad x < 0 \end{cases} The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.abs(x) Parameters x A number. Return value The absolute value of the given number. Description Because abs
() is a static method of Math, you always use it as Math.abs
(), rather than as a method of a Math object you created (Math is not a constructor). ...
...roject, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.abs(x) Parameters x A number. Return value The absolute value of the given number. Description Because abs
() is a static method of Math, you always use it as Math.abs
(), rather than as a method of a Math object you created (Math is not a constructor). Examples Behavior of Math.abs
() Passing an empty object, an array with more than one member, a non-numeric string or undefined/empty variable returns NaN. Passing null, an empty string or an empty array returns 0. Math.abs('-1'); // 1 Math.abs(-2); // 2 Math.abs(null); // 0 Math.abs(''); // 0 Math.abs([]); // 0 Math.abs([2]); // 2 Math.abs([1,2]); // NaN Math.abs({}); // NaN Math.abs('s...
...t, an array with more than one member, a non-numeric string or undefined/empty variable returns NaN. Passing null, an empty string or an empty array returns 0. Math.abs('-1'); // 1 Math.abs(-2); // 2 Math.abs(null); // 0 Math.abs(''); // 0 Math.abs([]); // 0 Math.abs([2]); // 2 Math.abs([1,2]); // NaN Math.abs({}); // NaN Math.abs('string'); // NaN Math.abs
(); // NaN Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.abs' in that specification. ...
Math.acosh() - JavaScript
The Math.acosh
() function returns the hyperbolic arc-cosine of a number, that is ?x>=1,Math.acosh(x)=arcosh(x)= the unique y>=0such thatcosh(y)=x\forall x \geq 1, \mathtt{\operatorname{Math.acosh}(x)} = \operatorname{arcosh}(x) = \text{ the unique } \; y \geq 0 \; \text{such that} \; \cosh(y) = x The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.acosh(x) Parameters x A number. Return value The hyperbolic arc-cosine of the given number. If the number is less than 1, NaN. ...
...The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.acosh(x) Parameters x A number. Return value The hyperbolic arc-cosine of the given number. If the number is less than 1, NaN. Description Because acosh
() is a static method of Math, you always use it as Math.acosh
(), rather than as a method of a Math object you created (Math is no constructor). Polyfill For all x>=1x \geq 1, we have arcosh(x)=ln(x+x2-1)\operatorname {arcosh} (x) = \ln \left(x + \sqrt{x^{2} - 1} \right) and so this can be emulated with the following function: Math.acosh = Math.acosh || function(x) { return Math.log(x + Math.sq...
...as Math.acosh
(), rather than as a method of a Math object you created (Math is no constructor). Polyfill For all x>=1x \geq 1, we have arcosh(x)=ln(x+x2-1)\operatorname {arcosh} (x) = \ln \left(x + \sqrt{x^{2} - 1} \right) and so this can be emulated with the following function: Math.acosh = Math.acosh || function(x) { return Math.log(x + Math.sqrt(x * x - 1)); }; Examples Using Math.acosh
() Math.acosh(-1); // NaN Math.acosh(0); // NaN Math.acosh(0.5); // NaN Math.acosh(1); // 0 Math.acosh(2); // 1.3169578969248166 For values less than 1 Math.acosh
() returns NaN. Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.acosh' in that specification. ...
Math.atan2() - JavaScript
The Math.atan2
() function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0,0) to the point (x,y), for Math.atan2(y,x). The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.atan2(y, x) Parameters y The y coordinate of the point. x The x coordinate of the point Return value The angle in radians (in [-?,?][-\pi, \pi]) between the positive x-axis and the ray from (0,0) to the point (x,y). Description The Math.atan2
() method returns a numeric value between -? and ? representing the angle theta of an (x, y) point. This is the counterclockwise angle, measured...
...ve x-axis and the ray from (0,0) to the point (x,y). Description The Math.atan2
() method returns a numeric value between -? and ? ...
...Description The Math.atan2
() method returns a numeric value between -? and ? representing the angle theta of an (x, y) point. This is the counterclockwise angle, measured in radians, between the positive X axis, and the point (x, y). Note that the arguments to this function pass the y-coordinate first and the x-coordinate second. Math.atan2
() is passed separate x and y arguments, and Math.atan
() is passed the ratio of those two arguments. Because atan2
() is a static method of Math, you always use it as Math.atan2
(), rather than as a method of a Math object you created (Math is not a constructor). Examples Using Math.atan2
() Math.atan2(90, 15); // 1.4056476493802699 Math.atan2(15, 90); // 0.16514867741462683 Math.atan2(+-0, -0); // +-PI. Math.atan2(+-0, +0); ...
Math.atanh() - JavaScript
The Math.atanh
() function returns the hyperbolic arctangent of a number, that is ?x?(-1,1),Math.atanh(x)=arctanh(x)= the unique ysuch thattanh(y)=x\forall x \in \left( -1, 1 \right), \mathtt{\operatorname{Math.atanh}(x)} = \operatorname{arctanh}(x) = \text{ the unique } \; y \; \text{such that} \; \tanh(y) = x The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.atanh(x) Parameters x A number. Return value The hyperbolic arctangent of the given number. ...
...text{such that} \; \tanh(y) = x The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.atanh(x) Parameters x A number. Return value The hyperbolic arctangent of the given number. Description Because atanh
() is a static method of Math, you always use it as Math.atanh
(), rather than as a method of a Math object you created (Math is not a constructor). Polyfill For |x|<1\left|x\right| < 1, we have artanh(x)=12ln(1+x1-x)\operatorname {artanh} (x) = \frac{1}{2}\ln \left( \frac{1 + x}{1 - x} \right) so this can be emulated by the following function: Math.atanh = Math.atanh || function(x) { return Ma...
... Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.atanh' in that specification. ...
Math.clz32() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.clz32(x) Parameters x A number. Return value The number of leading zero bits in the 32-bit binary representation of the given number. Description "clz32" is short for CountLeadingZeroes32. If x is not a number, then it will be converted to a number first, then converted to a 32-bit unsigned integer. If the converted 32-bit unsigned integer is 0, then return 32, because all bits are 0. ...
...32 = (function(log, LN2){ return function(x) { // Let n be ToUint32(x). // Let p be the number of leading zero bits in // the 32-bit binary representation of n. // Return p. ...
.... // Let p be the number of leading zero bits in // the 32-bit binary representation of n. // Return p. var asUint = x >>> 0; if (asUint === 0) { return 32; } return 31 - (log(asUint) / LN2 | 0) |0; // the "| 0" acts like math.floor }; })(Math.log, Math.LN2); Examples Using Math.clz32
() Math.clz32(1); // 31 Math.clz32(1000); // 22 Math.clz32
(); // 32 var stuff = [NaN, Infinity, -Infinity, 0, -0, false, null, undefined, 'foo', {}, []]; stuff.every(n => Math.clz32(n) == 32); // true Math.clz32(true); // 31 Math.clz32(3.5); // 30 Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.clz32' in that specification. ...
Math.cos() - JavaScript
The Math.cos
() static function returns the cosine of the specified angle, which must be specified in radians. This value is length adjacent length hypotenuse . The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.cos(x) Parameters x The angle in radians for which to return the cosine. Return value The cosine of the given number. Description The Math.cos
() method returns a numeric value between -1 and 1, which represents the cosine of the angle. ...
...ibute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.cos(x) Parameters x The angle in radians for which to return the cosine. Return value The cosine of the given number. Description The Math.cos
() method returns a numeric value between -1 and 1, which represents the cosine of the angle. ...
...s://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.cos(x) Parameters x The angle in radians for which to return the cosine. Return value The cosine of the given number. Description The Math.cos
() method returns a numeric value between -1 and 1, which represents the cosine of the angle. Because cos
() is a static method of Math, you always use it as Math.cos
(), rather than as a method of a Math object you created (Math is not a constructor). Examples Using Math.cos
() Math.cos(0); // 1 Math.cos(1); // 0.5403023058681398 Math.cos(Math.PI); // -1 Math.cos(2 * Math.PI); // 1 Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.cos' in that specification. ...
Math.cosh() - JavaScript
The Math.cosh
() function returns the hyperbolic cosine of a number, that can be expressed using the constant e: Math.cosh(x)=ex+e-x2\mathtt{\operatorname{Math.cosh(x)}} = \frac{e^x + e^{-x}}{2} The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.cosh(x) Parameters x A number. Return value The hyperbolic cosine of the given number. Description Because cosh
() is a static method of Math, you always use it as Math.cosh
(), rather than as a method of a Math object you created (Math is not a constructor). ...
...com/mdn/interactive-examples and send us a pull request. Syntax Math.cosh(x) Parameters x A number. Return value The hyperbolic cosine of the given number. Description Because cosh
() is a static method of Math, you always use it as Math.cosh
(), rather than as a method of a Math object you created (Math is not a constructor). ...
...cosine of the given number. Description Because cosh
() is a static method of Math, you always use it as Math.cosh
(), rather than as a method of a Math object you created (Math is not a constructor). Polyfill This can be emulated with the help of the Math.exp
() function: Math.cosh = Math.cosh || function(x) { return (Math.exp(x) + Math.exp(-x)) / 2; } or using only one call to the Math.exp
() function: Math.cosh = Math.cosh || function(x) { var y = Math.exp(x); return (y + 1 / y) / 2; }; Examples Using Math.cosh
() Math.cosh(0); // 1 Math.cosh(1); // 1.5430806348152437 Math.cosh(-1); // 1.5430806348152437 Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.cosh' in that specification. ...
Math.imul() - JavaScript
The Math.imul
() function returns the result of the C-like 32-bit multiplication of the two parameters. 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 product = Math.imul(a, b); Parameters a First number. b Second number. Return value The result of the C-like 32-bit multiplication of the given arguments. Description Math.imul
() allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like Emscripten. ...
...://github.com/mdn/interactive-examples and send us a pull request. Syntax var product = Math.imul(a, b); Parameters a First number. b Second number. Return value The result of the C-like 32-bit multiplication of the given arguments. Description Math.imul
() allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like Emscripten. Because imul
() is a static method of Math, you always use it as Math.imul
(), rather than as a method of a Math object you created (Math is not a constructor). If you use normal JavaScript floating point numbers in imul, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back int...
...E_INTEGER /*0x1fffffffffffff*/ var result = (opA & 0x003fffff) * opB; // 2. We can remove an integer coersion from the statement above because: // 0x1fffff7fc00001 + 0xffc00000 = 0x1fffffff800001 // 0x1fffffff800001 < Number.MAX_SAFE_INTEGER /*0x1fffffffffffff*/ if (opA & 0xffc00000 /*!== 0*/) result += (opA & 0xffc00000) * opB |0; return result |0; }; Examples Using Math.imul
() Math.imul(2, 4); // 8 Math.imul(-1, 8); // -8 Math.imul(-2, -2); // 4 Math.imul(0xffffffff, 5); // -5 Math.imul(0xfffffffe, 5); // -10 Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.imul' in that specification. ...
Math.log() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.log(x) Parameters x A number. Return value The natural logarithm (base e) of the given number. If the number is negative, NaN is returned. Description If the value of x is 0, the return value is always -Infinity. ...
..., please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.log(x) Parameters x A number. Return value The natural logarithm (base e) of the given number. If the number is negative, NaN is returned. Description If the value of x is 0, the return value is always -Infinity. If the value of x is negative, the return value is always NaN. Because log
() is a static method of Math, you always use it as Math.log
(), rather than as a method of a Math object you created (Math is not a constructor). If you need the natural log of 2 or 10, use the constants Math.LN2 or Math.LN10 . If you need a logarithm to base 2 or 10, use Math.log2
() or Math.log10
() . If you need a logarithm to other bases, use Math.log(x) / Math.log(otherBase) as in the example ...
...a Math object you created (Math is not a constructor). If you need the natural log of 2 or 10, use the constants Math.LN2 or Math.LN10 . If you need a logarithm to base 2 or 10, use Math.log2
() or Math.log10
() . If you need a logarithm to other bases, use Math.log(x) / Math.log(otherBase) as in the example below; you might want to precalculate 1 / Math.log(otherBase) . Examples Using Math.log
() Math.log(-1); // NaN, out of range Math.log(0); // -Infinity Math.log(1); // 0 Math.log(10); // 2.302585092994046 Using Math.log
() with a different base The following function returns the logarithm of y with base x (ie. logxy\log_x y): function getBaseLog(x, y) { return Math.log(y) / Math.log(x); } If you run getBaseLog(10, 1000) it returns 2.9999999999999996 due to floating-point roun...
Math.log1p() - JavaScript
If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.log1p(x) Parameters x A number. Return value The natural logarithm (base e) of 1 plus the given number. If the number is less than -1, NaN is returned. Description For very small values of x, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. ...
...0000111022 (the roundoff is in binary so sometimes it gets ugly), so you get the answer 1.11022...e-15, with only 3 correct digits. If, instead, you calculate Math.log1p(1.1111111111e-15) you will get a much more accurate answer 1.1111111110999995e-15 with 15 correct digits of precision (actually 16 in this case). If the value of x is less than -1, the return value is always NaN. Because log1p
() is a static method of Math, you always use it as Math.log1p
(), rather than as a method of a Math object you created (Math is not a constructor). Polyfill This can be emulated with the following function: Math.log1p = Math.log1p || function(x) { x = Number(x); if (x < -1 || x !== x) return NaN; if (x === 0 || x === Infinity) return x; var nearX = (x + 1) - 1; return nearX ==...
...han as a method of a Math object you created (Math is not a constructor). Polyfill This can be emulated with the following function: Math.log1p = Math.log1p || function(x) { x = Number(x); if (x < -1 || x !== x) return NaN; if (x === 0 || x === Infinity) return x; var nearX = (x + 1) - 1; return nearX === 0 ? x : x * (Math.log(x + 1) / nearX); }; Examples Using Math.log1p
() Math.log1p(1); // 0.6931471805599453 Math.log1p(0); // 0 Math.log1p(-1); // -Infinity Math.log1p(-2); // NaN Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.log1p' in that specification. ...
Math.max() - JavaScript
The Math.max
() function returns the largest of the zero or more numbers given as input parameters. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.max([value1[, value2[, ...]]]) Parameters value1, value2, ... Numbers. Return value The largest of the given numbers. If at least one of the arguments cannot be converted to a number, NaN is returned. Description Because Math is not a constructor, max
() is a static method of Math (You always use it as Math.max
(), rather than as a method of an instanced Math object). -Infinity is the initial comparant because almost every other value is bigger, th...
...e Math is not a constructor, max
() is a static method of Math (You always use it as Math.max
(), rather than as a method of an instanced Math object). -Infinity is the initial comparant because almost every other value is bigger, that's why when no arguments are given, -Infinity is returned. If at least one of arguments cannot be converted to a number, the result is NaN. ...
... object). -Infinity is the initial comparant because almost every other value is bigger, that's why when no arguments are given, -Infinity is returned. If at least one of arguments cannot be converted to a number, the result is NaN. Examples Using Math.max
() Math.max(10, 20); // 20 Math.max(-10, -20); // -10 Math.max(-10, 20); // 20 Getting the maximum element of an array Array.reduce
() can be used to find the maximum element in a numeric array, by comparing each value: var arr = [1,2,3]; var max = arr.reduce(function(a, b) { return Math.max(a, b); }); The following function uses Function.prototype.apply
() to get the maximum of an array. getMaxOfArray([1, 2, 3]) is equivalent to Math.max(1, 2, 3), but you can use getMaxOfArray
() on programmatically constructed arrays. Thi...
Math.pow() - JavaScript
The Math.pow
() function returns the base to the exponent power, that is, baseexponent. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.pow(base, exponent) Parameters base The base number. exponent The exponent used to raise the base. Return value A number representing the given base taken to the power of the given exponent. Description The Math.pow
() function returns the base to the exponent power, that is, baseexponent, the base and the exponent are in decimal numeral system. ...
... pull request. Syntax Math.pow(base, exponent) Parameters base The base number. exponent The exponent used to raise the base. Return value A number representing the given base taken to the power of the given exponent. Description The Math.pow
() function returns the base to the exponent power, that is, baseexponent, the base and the exponent are in decimal numeral system. Because pow
() is a static method of Math, you always use it as Math.pow
(), rather than as a method of a Math object you created (Math has no constructor). ...
...Math.pow
() function returns the base to the exponent power, that is, baseexponent, the base and the exponent are in decimal numeral system. Because pow
() is a static method of Math, you always use it as Math.pow
(), rather than as a method of a Math object you created (Math has no constructor). If the base is negative and the exponent is not an integer, the result is NaN. ...
Math.sinh() - JavaScript
The Math.sinh
() function returns the hyperbolic sine of a number, that can be expressed using the constant e: Math.sinh(x)=ex-e-x2\mathtt{\operatorname{Math.sinh(x)}} = \frac{e^x - e^{-x}}{2} The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.sinh(x) Parameters x A number. Return value The hyperbolic sine of the given number. Description Because sinh
() is a static method of Math, you always use it as Math.sinh
(), rather than as a method of a Math object you created (Math is not a constructor). ...
....com/mdn/interactive-examples and send us a pull request. Syntax Math.sinh(x) Parameters x A number. Return value The hyperbolic sine of the given number. Description Because sinh
() is a static method of Math, you always use it as Math.sinh
(), rather than as a method of a Math object you created (Math is not a constructor). ...
... sine of the given number. Description Because sinh
() is a static method of Math, you always use it as Math.sinh
(), rather than as a method of a Math object you created (Math is not a constructor). Polyfill This can be emulated with the help of the Math.exp
() function: Math.sinh = Math.sinh || function(x) { return (Math.exp(x) - Math.exp(-x)) / 2; } or using only one call to the Math.exp
() function: Math.sinh = Math.sinh || function(x) { var y = Math.exp(x); return (y - 1 / y) / 2; } Examples Using Math.sinh
() Math.sinh(0); // 0 Math.sinh(1); // 1.1752011936438014 Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.sinh' in that specification. ...
Math.sqrt() - JavaScript
The Math.sqrt
() function returns the square root of a number, that is ?x>=0,Math.sqrt(x)=x=the uniquey>=0such thaty2=x\forall x \geq 0, \mathtt{Math.sqrt(x)} = \sqrt{x} = \text{the unique} \; y \geq 0 \; \text{such that} \; y^2 = x The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.sqrt(x) Parameters x A number. Return value The square root of the given number. If the number is negative, NaN is returned. Description If the value of x is negative, Math.sqrt
() returns NaN. ...
... GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.sqrt(x) Parameters x A number. Return value The square root of the given number. If the number is negative, NaN is returned. Description If the value of x is negative, Math.sqrt
() returns NaN. ...
...ctive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.sqrt(x) Parameters x A number. Return value The square root of the given number. If the number is negative, NaN is returned. Description If the value of x is negative, Math.sqrt
() returns NaN. Because sqrt
() is a static method of Math, you always use it as Math.sqrt
(), rather than as a method of a Math object you created (Math is not a constructor). Examples Using Math.sqrt
() Math.sqrt(9); // 3 Math.sqrt(2); // 1.414213562373095 Math.sqrt(1); // 1 Math.sqrt(0); // 0 Math.sqrt(-1); // NaN Math.sqrt(-0); // -0 Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.sqrt' in that specification. ...
Math.tanh() - JavaScript
The Math.tanh
() function returns the hyperbolic tangent of a number, that is tanhx=sinhxcoshx=ex-e-xex+e-x=e2x-1e2x+1\tanh x = \frac{\sinh x}{\cosh x} = \frac {e^x - e^{-x}} {e^x + e^{-x}} = \frac{e^{2x} - 1}{e^{2x}+1} Syntax Math.tanh(x) Parameters x A number. Return value The hyperbolic tangent of the given number. Description Because tanh
() is a static method of Math, you always use it as Math.tanh
(), rather than as a method of a Math object you created (Math is not a constructor). ...
...e^{-x}} {e^x + e^{-x}} = \frac{e^{2x} - 1}{e^{2x}+1} Syntax Math.tanh(x) Parameters x A number. Return value The hyperbolic tangent of the given number. Description Because tanh
() is a static method of Math, you always use it as Math.tanh
(), rather than as a method of a Math object you created (Math is not a constructor). ...
... a static method of Math, you always use it as Math.tanh
(), rather than as a method of a Math object you created (Math is not a constructor). Polyfill This can be emulated with the help of the Math.exp
() function: Math.tanh = Math.tanh || function(x){ var a = Math.exp(+x), b = Math.exp(-x); return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (a + b); } Examples Using Math.tanh
() Math.tanh(0); // 0 Math.tanh(Infinity); // 1 Math.tanh(1); // 0.7615941559557649 Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.tanh' in that specification. ...
Number.isNaN() - JavaScript
The Number.isNaN
() method determines whether the passed value is NaN and its type is Number. It is a more robust version of the original, global isNaN
(). 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 Number.isNaN(value) Parameters value The value to be tested for NaN. Return value true if the given value is NaN and its type is Number; otherwise, false. Description Due to both equality operators, == and ===, evaluating to false when checking if NaN is NaN, the function Number.isNaN
() has become necessary. This situation is unlike all other possible value comparisons in JavaScript. In comparison...
... value The value to be tested for NaN. Return value true if the given value is NaN and its type is Number; otherwise, false. Description Due to both equality operators, == and ===, evaluating to false when checking if NaN is NaN, the function Number.isNaN
() has become necessary. This situation is unlike all other possible value comparisons in JavaScript. In comparison to the global isNaN
() function, Number.isNaN
() doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to NaN, but aren't actually the same value as NaN. This also means that only values of the type number, that are also NaN, return true. Polyfill The following works because NaN is the only value in javascript which is not eq...
... Polyfill The following works because NaN is the only value in javascript which is not equal to itself. Number.isNaN = Number.isNaN || function isNaN(input) { return typeof input === 'number' && input !== input; } Examples Using isNaN Number.isNaN(NaN); // true Number.isNaN(Number.NaN); // true Number.isNaN(0 / 0); // true // e.g. ...
Object() constructor - JavaScript
The Object constructor creates an object wrapper for the given value. If the value is null or undefined, it will create and return an empty object. Otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value. When called in a non-constructor context, Object behaves identically to new Object
(). ...
...Object constructor creates an object wrapper for the given value. If the value is null or undefined, it will create and return an empty object. Otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value. When called in a non-constructor context, Object behaves identically to new Object
(). ...
...will create and return an empty object. Otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value. When called in a non-constructor context, Object behaves identically to new Object
(). Syntax new Object
() new Object(value) Parameters value Any value. Examples Creating a new Object let o = new Object
() o.foo = 42 console.log(o) // Object { foo: 42 } Using Object given undefined and null types The following examples store an empty Object object in o: let o = new Object
() let o = new Object(undefined) let o = new Object(null) Specifications Specification ECMAScript (ECMA-262)The definition of 'Object constructor' in that specification. ...
Object.prototype.__defineGetter__() - JavaScript
While this feature is widely implemented, it is only described in the ECMAScript specification because of legacy usage. This method should not be used since better alternatives exist. The __defineGetter__ method binds an object's property to a function to be called when that property is looked up. Syntax obj.__defineGetter__(prop, func) Parameters prop A string containing the name of the property to bind to the given function. func A function to be bound to a lookup of the specified property. Return value undefined. ...
...etter__(prop, func) Parameters prop A string containing the name of the property to bind to the given function. func A function to be bound to a lookup of the specified property. Return value undefined. Description The __defineGetter__ allows a getter to be defined on a pre-existing object. ...
...function to be bound to a lookup of the specified property. Return value undefined. Description The __defineGetter__ allows a getter to be defined on a pre-existing object. Examples Non-standard and deprecated way var o = {}; o.__defineGetter__('gimmeFive', function
() { return 5; }); console.log(o.gimmeFive); // 5 Standard-compliant ways // Using the get operator var o = { get gimmeFive
() { return 5; } }; console.log(o.gimmeFive); // 5 // Using Object.defineProperty var o = {}; Object.defineProperty(o, 'gimmeFive', { get: function
() { return 5; } }); console.log(o.gimmeFive); // 5 Specifications Specification ECMAScript (ECMA-262)The definition of 'Object.prototype.__defineGetter__
()' in that specification. ...
Object.fromEntries() - JavaScript
The Object.fromEntries
() method transforms a list of key-value pairs into an object. 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 Object.fromEntries(iterable); Parameters iterable An iterable such as Array or Map or other objects implementing the iterable protocol. Return value A new object whose properties are given by the entries of the iterable. Description The Object.fromEntries
() method takes a list of key-value pairs and returns a new object whose properties are given by those entries. The iterable argument is expected to be an object that implements an @@iterator method, that returns an...
...and returns a new object whose properties are given by those entries. The iterable argument is expected to be an object that implements an @@iterator method, that returns an iterator object, that produces a two element array-like object, whose first element is a value that will be used as a property key, and whose second element is the value to associate with that property key. Object.fromEntries
() performs the reverse of Object.entries
(). Examples Converting a Map to an Object With Object.fromEntries, you can convert from Map to Object: const map = new Map([ ['foo', 'bar'], ['baz', 42] ]); const obj = Object.fromEntries(map); console.log(obj); // { foo: "bar", baz: 42 } Converting an Array to an Object With Object.fromEntries, you can convert from Array to Object: const arr = [ ['0...
...For more details, refer to: https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-p...
Object.getOwnPropertyDescriptor() - JavaScript
The object returned is mutable but mutating it has no effect on the original property's configuration. 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 Object.getOwnPropertyDescriptor(obj, prop) Parameters obj The object in which to look for the property. prop The name or Symbol of the property whose description is to be retrieved. ...
...lue A property descriptor of the given property if it exists on the object, undefined otherwise. Description This method permits examination of the precise description of a property. A property in JavaScript consists of either a string-valued name or a Symbol and a property descriptor. Further information about property descriptor types and their attributes can be found in Object.defineProperty
(). A property descriptor is a record with some of the following attributes: value The value associated with the property (data descriptors only). writable true if and only if the value associated with the property may be changed (data descriptors only). get A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). set A function...
...f there is no setter (accessor descriptors only). configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. ...
Object.preventExtensions() - JavaScript
The Object.preventExtensions
() method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). 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 Object.preventExtensions(obj) Parameters obj The object which should be made non-extensible. Return value The object being made non-extensible. Description An object is extensible if new properties can be added to it. Object.preventExtensions
() marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the pro...
...ensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Note that the properties of a non-extensible object, in general, may still be deleted. Attempting to add new properties to a non-extensible object will fail, either silently or by throwing a TypeError (most commonly, but not exclusively, when in strict mode). Object.preventExtensions
() only prevents addition of own properties. Properties can still be added to the object prototype. This method makes the [[prototype]] of the target immutable; any [[prototype]] re-assignment will throw a TypeError. This behavior is specific to the internal [[prototype]] property, other properties of the target object will remain mutable. There is no way to make an object extensible again once ...
...(empty); // === false // Object.defineProperty throws when adding // a new property to a non-extensible object. var nonExtensible = { removable: true }; Object.preventExtensions(nonExtensible); Object.defineProperty(nonExtensible, 'new', { value: 8675309 }); // throws a TypeError // In strict mode, attempting to add new properties // to a non-extensible object throws a TypeError. function fail
() { 'use strict'; // throws a TypeError nonExtensible.newProperty = 'FAIL'; } fail
(); A non-extensible object's prototype is immutable: var fixed = Object.preventExtensions({}); // throws a 'TypeError'. fixed.__proto__ = { oh: 'hai' }; Non-object coercion In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. In ES2015, a non-object argumen...
handler.apply() - JavaScript
The handler.apply
() method is a trap for a function call. 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 p = new Proxy(target, { apply: function(target, thisArg, argumentsList) { } }); Parameters The following parameters are passed to the apply
() method. this is bound to the handler. target The target object. thisArg The this argument for the call. argumentsList The list of arguments for the call. Return value The apply
() method can return any value. Description The handler.apply
() method is a trap for a function call. Interceptions This trap can intercept these operations: ...
...apply
() method. this is bound to the handler. target The target object. thisArg The this argument for the call. argumentsList The list of arguments for the call. Return value The apply
() method can return any value. Description The handler.apply
() method is a trap for a function call. Interceptions This trap can intercept these operations: proxy(...args) Function.prototype.apply
() and Function.prototype.call
() Reflect.apply
() Invariants If the following invariants are violated, the proxy will throw a TypeError. The target must be a callable itself. That is, it must be a function object. Examples Trapping a function call The following code traps a function call. ...
...an intercept these operations: proxy(...args) Function.prototype.apply
() and Function.prototype.call
() Reflect.apply
() Invariants If the following invariants are violated, the proxy will throw a TypeError. The target must be a callable itself. That is, it must be a function object. Examples Trapping a function call The following code traps a function call. const p = new Proxy(function
() {}, { apply: function(target, thisArg, argumentsList) { console.log('called: ' + argumentsList.join(', ')); return argumentsList[0] + argumentsList[1] + argumentsList[2]; } }); console.log(p(1, 2, 3)); // "called: 1, 2, 3" // 6 Specifications Specification ECMAScript (ECMA-262)The definition of '[[Call]]' in that specification. ...
handler.getOwnPropertyDescriptor() - JavaScript
The handler.getOwnPropertyDescriptor
() method is a trap for Object.getOwnPropertyDescriptor
(). 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 p = new Proxy(target, { getOwnPropertyDescriptor: function(target, prop) { } }); Parameters The following parameters are passed to the getOwnPropertyDescriptor
() method. this is bound to the handler. target The target object. prop The name of the property whose description should be retrieved. Return value The getOwnPropertyDescriptor
() method must return an object or undefined. ...
...or: function(target, prop) { } }); Parameters The following parameters are passed to the getOwnPropertyDescriptor
() method. this is bound to the handler. target The target object. prop The name of the property whose description should be retrieved. Return value The getOwnPropertyDescriptor
() method must return an object or undefined. Description The handler.getOwnPropertyDescriptor
() method is a trap for Object.getOwnPropertyDescriptor
(). Interceptions This trap can intercept these operations: Object.getOwnPropertyDescriptor
() Reflect.getOwnPropertyDescriptor
() Invariants If the following invariants are violated, the proxy will throw a TypeError: getOwnPropertyDescriptor
() must return an object or undefined. A property cannot be reported as non-existent, if it ex...
...t does not exists as an own property of the target object and the target object is not extensible. A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. The result of Object.getOwnPropertyDescriptor(target) can be applied to the target object using Object.defineProperty
() and will not throw an exception. Examples Trapping of getOwnPropertyDescriptor The following code traps Object.getOwnPropertyDescriptor
(). const p = new Proxy({ a: 20}, { getOwnPropertyDescriptor: function(target, prop) { console.log('called: ' + prop); return { configurable: true, enumerable: true, value: 10 }; } }); console.log(Object.getOwnPropertyDescriptor(p, 'a').value); /...
Proxy.revocable() - JavaScript
The Proxy.revocable
() method is used to create a revocable Proxy object. Syntax Proxy.revocable(target, handler); Parameters target A target object to wrap with Proxy. It can be any sort of object, including a native array, a function, or even another proxy. handler An object whose properties are functions define the behavior of proxy p when an operation is performed on it. Return value A newly created revocable Proxy object is returned. Description A revocable Proxy is an object with following two properties {proxy: proxy, revoke: revoke}. proxy A Proxy object created with new Proxy(target, handler) call. revoke A function with no argument to invalidate (switch off) the proxy. ...
... the behavior of proxy p when an operation is performed on it. Return value A newly created revocable Proxy object is returned. Description A revocable Proxy is an object with following two properties {proxy: proxy, revoke: revoke}. proxy A Proxy object created with new Proxy(target, handler) call. revoke A function with no argument to invalidate (switch off) the proxy. If the revoke
() function gets called, the proxy becomes unusable: Any trap to a handler will throw a TypeError. Once a proxy is revoked, it will remain revoked and can be garbage collected. Calling revoke
() again has no effect. Examples Using Proxy.revocable var revocable = Proxy.revocable({}, { get: function(target, name) { return "[[" + name + "]]"; } }); var proxy = revocable.proxy; console.log(pro...
...s unusable: Any trap to a handler will throw a TypeError. Once a proxy is revoked, it will remain revoked and can be garbage collected. Calling revoke
() again has no effect. Examples Using Proxy.revocable var revocable = Proxy.revocable({}, { get: function(target, name) { return "[[" + name + "]]"; } }); var proxy = revocable.proxy; console.log(proxy.foo); // "[[foo]]" revocable.revoke
(); console.log(proxy.foo); // TypeError is thrown proxy.foo = 1 // TypeError again delete proxy.foo; // still TypeError typeof proxy // "object", typeof doesn't trigger any trap Specifications Specification ECMAScript (ECMA-262)The definition of 'Proxy Revocation Functions' in that specification. ...
Reflect.getPrototypeOf() - JavaScript
It returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.getPrototypeOf(target) Parameters target The target object of which to get the prototype. Return value The prototype of the given object. If there are no inherited properties, null is returned. Exceptions A TypeError, if target is not an Object. ...
...The target object of which to get the prototype. Return value The prototype of the given object. If there are no inherited properties, null is returned. Exceptions A TypeError, if target is not an Object. Description The Reflect.getPrototypeOf method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object. ...
...t. Description The Reflect.getPrototypeOf method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object. ...
Reflect.has() - JavaScript
The static Reflect.has
() method works like the in operator as a function. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.has(target, propertyKey) Parameters target The target object in which to look for the property. propertyKey The name of the property to check. Return value A Boolean indicating whether or not the target has the property. Exceptions A TypeError, if target is not an Object. Description The Reflect.has method allows you to check if a property is in an object. It works like the in operator as a function. ...
... The target object in which to look for the property. propertyKey The name of the property to check. Return value A Boolean indicating whether or not the target has the property. Exceptions A TypeError, if target is not an Object. Description The Reflect.has method allows you to check if a property is in an object. It works like the in operator as a function. ...
...erty. Exceptions A TypeError, if target is not an Object. Description The Reflect.has method allows you to check if a property is in an object. It works like the in operator as a function. ...
Reflect.isExtensible() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.isExtensible(target) Parameters target The target object which to check if it is extensible. Return value A Boolean indicating whether or not the target is extensible. Exceptions A TypeError, if target is not an Object. ...
...) Parameters target The target object which to check if it is extensible. Return value A Boolean indicating whether or not the target is extensible. Exceptions A TypeError, if target is not an Object. Description The Reflect.isExtensible method allows you determine if an object is extensible (whether it can have new properties added to it). It is the same method as Object.isExtensible
(). Examples Using Reflect.isExtensible
() See also Object.isExtensible
(). // New objects are extensible. let empty = {} Reflect.isExtensible(empty) // === true // ...but that can be changed. Reflect.preventExtensions(empty) Reflect.isExtensible(empty) // === false // Sealed objects are by definition non-extensible. let sealed = Object.seal({}) Reflect.isExtensible(sealed) // === false // F...
... // ...but that can be changed. Reflect.preventExtensions(empty) Reflect.isExtensible(empty) // === false // Sealed objects are by definition non-extensible. let sealed = Object.seal({}) Reflect.isExtensible(sealed) // === false // Frozen objects are also by definition non-extensible. let frozen = Object.freeze({}) Reflect.isExtensible(frozen) // === false Difference to Object.isExtensible
() If the target argument to this method is not an object (a primitive), then it will cause a TypeError. With Object.isExtensible
(), a non-object first argument will be coerced to an object at first. Reflect.isExtensible(1) // TypeError: 1 is not an object Object.isExtensible(1) // false Specifications Specification ECMAScript (ECMA-262)The definition of 'Reflect.isExtensible...
Reflect.preventExtensions() - JavaScript
The static Reflect.preventExtensions
() method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to Object.preventExtensions
(), but with some differences. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.preventExtensions(target) Parameters target The target object on which to prevent extensions. Return value A Boolean indicating whether or not the target was successfully set to prevent extensions. Exceptions A TypeError, if target is not an Object. ...
... clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.preventExtensions(target) Parameters target The target object on which to prevent extensions. Return value A Boolean indicating whether or not the target was successfully set to prevent extensions. Exceptions A TypeError, if target is not an Object. Description The Reflect.preventExtensions
() method allows you to prevent new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to Object.preventExtensions
(). Examples Using Reflect.preventExtensions
() See also Object.preventExtensions
(). // Objects are extensible by default. let empty = {} Reflect.isExtensible(empty) // === true // ...but that can be changed. Reflect.prevent...
... extensions to the object). It is similar to Object.preventExtensions
(). Examples Using Reflect.preventExtensions
() See also Object.preventExtensions
(). // Objects are extensible by default. let empty = {} Reflect.isExtensible(empty) // === true // ...but that can be changed. Reflect.preventExtensions(empty) Reflect.isExtensible(empty) // === false Difference from Object.preventExtensions
() If the target argument to this method is not an object (a primitive), then it will cause a TypeError. With Object.preventExtensions
(), a non-object target will be coerced to an object. Reflect.preventExtensions(1) // TypeError: 1 is not an object Object.preventExtensions(1) // 1 Specifications Specification ECMAScript (ECMA-262)The definition of 'Reflect.preventExtensions'...
RegExp.prototype[@@match]() - JavaScript
For example, the following two examples return same result. ...
...roject, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax regexp[Symbol.match](str) Parameters str A String that is a target of the match. Return value An Array containing the entire match result and any parentheses-captured matched results, or null if there were no matches. Description This method is called internally in String.prototype.match
(). For example, the following two examples return same result. 'abc'.match(/a/); /a/[Symbol.match]('abc'); This method exists for customizing match behavior within RegExp subclasses. Examples Direct call This method can be used in almost the same way as String.prototype.match
(), except the different this and the different arguments order. let re = /[0-9]+/g; let str = '2016-01-02'; let resu...
...ehavior within RegExp subclasses. Examples Direct call This method can be used in almost the same way as String.prototype.match
(), except the different this and the different arguments order. let re = /[0-9]+/g; let str = '2016-01-02'; let result = re[Symbol.match](str); console.log(result); // ["2016", "01", "02"] Using @@match in subclasses Subclasses of RegExp can override the [@@match]
() method to modify the default behavior. class MyRegExp extends RegExp { [Symbol.match](str) { let result = RegExp.prototype[Symbol.match].call(this, str); if (!result) return null; return { group(n) { return result[n]; } }; } } let re = new MyRegExp('([0-9]+)-([0-9]+)-([0-9]+)'); let str = '2016-01-02'; let result = str.match(re); // String.prototype.match...
RegExp.prototype[@@search]() - JavaScript
For example, the following two examples return the same result. ...
...xpression and a string. 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 regexp[Symbol.search](str) Parameters str A String that is a target of the search. Return value integer If successful, [@@search]
() returns the index of the first match of the regular expression inside the string. Otherwise, it returns -1. Description This method is called internally in String.prototype.search
(). For example, the following two examples return the same result. 'abc'.search(/a/); /a/[Symbol.search]('abc'); This method exists for customizing the search behavior in RegExp subclasses. Examples Direct call ...
... string. Otherwise, it returns -1. Description This method is called internally in String.prototype.search
(). For example, the following two examples return the same result. 'abc'.search(/a/); /a/[Symbol.search]('abc'); This method exists for customizing the search behavior in RegExp subclasses. Examples Direct call This method can be used in almost the same way as String.prototype.search
(), except the different this and the different arguments order. var re = /-/g; var str = '2016-01-02'; var result = re[Symbol.search](str); console.log(result); // 4 Using @@search in subclasses Subclass of RegExp can override [@@search]
() method to modify the behavior. class MyRegExp extends RegExp { constructor(str) { super(str) this.pattern = str; } [Symbol.search](str) { ...
Set.prototype.entries() - JavaScript
The entries
() method returns a new Iterator object that contains an array of [value, value] for each element in the Set object, in insertion order. For Set objects there is no key like in Map objects. However, to keep the API similar to the Map object, each entry has the same value for its key and value here, so that an array [value, value] is returned. 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 mySet.entries
() Return value A new Iterator object that contains an array of [value, value] for each element in the given Set, in insertion order. ...
...urce 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 mySet.entries
() Return value A new Iterator object that contains an array of [value, value] for each element in the given Set, in insertion order. ...
...ve 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 mySet.entries
() Return value A new Iterator object that contains an array of [value, value] for each element in the given Set, in insertion order. Examples Using entries
() var mySet = new Set
(); mySet.add('foobar'); mySet.add(1); mySet.add('baz'); var setIter = mySet.entries
(); console.log(setIter.next
().value); // ["foobar", "foobar"] console.log(setIter.next
().value); // [1, 1] console.log(setIter.next
().value); // ["baz", "baz"] Specifications Specification ECMAScript (ECMA-262)The definition of 'Set.prototype.entries' in that specification. ...
Set.prototype.has() - JavaScript
The has
() method returns a boolean indicating whether an element with the specified value exists in a Set object or not. 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 mySet.has(value); Parameters value The value to test for presence in the Set object. Return value Returns true if an element with the specified value exists in the Set object; otherwise false. Note: Technically speaking, has
() uses the sameValueZero algorithm to determine whether the given element is found. ...
...us a pull request. Syntax mySet.has(value); Parameters value The value to test for presence in the Set object. Return value Returns true if an element with the specified value exists in the Set object; otherwise false. Note: Technically speaking, has
() uses the sameValueZero algorithm to determine whether the given element is found. ...
...ect. Return value Returns true if an element with the specified value exists in the Set object; otherwise false. Note: Technically speaking, has
() uses the sameValueZero algorithm to determine whether the given element is found. Examples Using the has method var mySet = new Set
(); mySet.add('foo'); mySet.has('foo'); // returns true mySet.has('bar'); // returns false var set1 = new Set
(); var obj1 = {'key1': 1}; set1.add(obj1); set1.has(obj1); // returns true set1.has({'key1': 1}); // returns false because they are different object references set1.add({'key1': 1}); // now set1 contains 2 entries Specifications Specification ECMAScript (ECMA-262)The definition of 'Set.prototype.has' in that specification. ...
String.prototype.concat() - JavaScript
Changes to the original string or the returned string don't affect the other. ...
...xample is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.concat(str2 [, ...strN]) Parameters str2 [, ...strN] Strings to concatenate to str. Return value A new string containing the combined text of the strings provided. Description The concat
() function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other. If the arguments are not of the type string, they are converted to string values before concatenating. Performance It is strongly recommended that the assignment operators (+, +=) are used instead of the concat
() method. Examp...
...nates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other. If the arguments are not of the type string, they are converted to string values before concatenating. Performance It is strongly recommended that the assignment operators (+, +=) are used instead of the concat
() method. Examples Using concat
() The following example combines strings into a new string. let hello = 'Hello, ' console.log(hello.concat('Kevin', '. Have a nice day.')) // Hello, Kevin. Have a nice day. let greetList = ['Hello', ' ', 'Venkat', '!'] "".concat(...greetList) // "Hello Venkat!" "".concat({}) // [object Object] "".concat([]) // "" "".concat(null) // "null" "".concat(true) // "true" "".concat(4, 5) // "...
String.prototype.endsWith() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.endsWith(searchString[, length]) Parameters searchString The characters to be searched for at the end of str. length Optional If provided, it is used as the length of str. Defaults to str.length. Return value true if the given characters are found at the end of the string; otherwise, false. Description This method lets you determine whether or not a string ends with another string. ...
...e true if the given characters are found at the end of the string; otherwise, false. Description This method lets you determine whether or not a string ends with another string. This method is case-sensitive. Polyfill This method has been added to the ECMAScript 6 specification and may not be available in all JavaScript implementations yet. ...
...avaScript implementations yet. However, you can polyfill String.prototype.endsWith
() with the following snippet: if (!String.prototype.endsWith) { String.prototype.endsWith = function(search, this_len) { if (this_len === undefined || this_len > this.length) { this_len = this.length; } return this.substring(this_len - search.length, this_len) === search; }; } Examples Using endsWith
() let str = 'To be, or not to be, that is the question.' console.log(str.endsWith('question.')) // true console.log(str.endsWith('to be')) // false console.log(str.endsWith('to be', 19)) // true Specifications Specification ECMAScript (ECMA-262)The definition of 'String.prototype.endsWith' in that specification. ...
String.prototype.includes() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.includes(searchString[, position]) Parameters searchString A string to be searched for within str. position Optional The position within the string at which to begin searching for searchString. (Defaults to 0.) Return value true if the search string is found anywhere within the given string; otherwise, false if not. Description This method lets you determine whether or not a string includes another string. ...
...rchString A string to be searched for within str. position Optional The position within the string at which to begin searching for searchString. (Defaults to 0.) Return value true if the search string is found anywhere within the given string; otherwise, false if not. Description This method lets you determine whether or not a string includes another string. Case-sensitivity The includes
() method is case sensitive. For example, the following expression returns false: 'Blue Whale'.includes('blue') // returns false Polyfill This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet. However, you can easily polyfill this method: if (!String.prototype.includes) { String.prototype.includes = function(search, st...
...entations yet. ...
String.prototype.startsWith() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.startsWith(searchString[, position]) Parameters searchString The characters to be searched for at the start of this string. position Optional The position in this string at which to begin searching for searchString. Defaults to 0. Return value true if the given characters are found at the beginning of the string; otherwise, false. ...
...he given characters are found at the beginning of the string; otherwise, false. Description This method lets you determine whether or not a string begins with another string. This method is case-sensitive. Polyfill This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet. ...
...defineProperty(String.prototype, 'startsWith', { value: function(search, rawPos) { var pos = rawPos > 0 ? rawPos|0 : 0; return this.substring(pos, pos + search.length) === search; } }); } A more robust (fully ES2015 specification compliant), but less performant and compact, Polyfill is available on GitHub by Mathias Bynens. Examples Using startsWith
() //startswith let str = 'To be, or not to be, that is the question.' console.log(str.startsWith('To be')) // true console.log(str.startsWith('not to be')) // false console.log(str.startsWith('not to be', 10)) // true Specifications Specification ECMAScript (ECMA-262)The definition of 'String.prototype.startsWith' in that specification. ...
String.prototype.strike() - JavaScript
The strike
() method creates a <strike> HTML element that causes a string to be displayed as struck-out text. Syntax str.strike
() Return value A string containing a <strike> HTML element. Description The strike
() method embeds a string in a <strike> tag: "<strike>str</strike>". ...
... The strike
() method creates a <strike> HTML element that causes a string to be displayed as struck-out text. Syntax str.strike
() Return value A string containing a <strike> HTML element. Description The strike
() method embeds a string in a <strike> tag: "<strike>str</strike>". ...
... causes a string to be displayed as struck-out text. Syntax str.strike
() Return value A string containing a <strike> HTML element. Description The strike
() method embeds a string in a <strike> tag: "<strike>str</strike>". Examples Using strike
() The following example uses string methods to change the formatting of a string: var worldString = 'Hello, world'; console.log(worldString.blink
()); // <blink>Hello, world</blink> console.log(worldString.bold
()); // <b>Hello, world</b> console.log(worldString.italics
()); // <i>Hello, world</i> console.log(worldString.strike
()); // <strike>Hello, world</strike> Specifications Specification ECMAScript (ECMA-262)The definition of 'String.prototype.strike' in that specification. ...
String.prototype.trim() - JavaScript
The trim
() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.). The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.trim
() Return value A new string representing the str stripped of whitespace from both ends. Description The trim
() method returns the string stripped of whitespace from both ends. trim
() does not affect the value of the str itself. ...
...e https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.trim
() Return value A new string representing the str stripped of whitespace from both ends. Description The trim
() method returns the string stripped of whitespace from both ends. trim
() does not affect the value of the str itself. Polyfill Running the following code before any other code will create trim
() if it's not natively available. if (!String.prototype.trim) { String.prototype.trim = function
() { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }; } Examples Using trim
() The following example displays the lowercase string 'foo': var orig = ' foo '; console.log(orig.trim
()); // 'foo' // Another example of .trim
() removing whitespace from just one side. var or...
...(!String.prototype.trim) { String.prototype.trim = function
() { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }; } Examples Using trim
() The following example displays the lowercase string 'foo': var orig = ' foo '; console.log(orig.trim
()); // 'foo' // Another example of .trim
() removing whitespace from just one side. var orig = 'foo '; console.log(orig.trim
()); // 'foo' Specifications Specification ECMAScript (ECMA-262)The definition of 'String.prototype.trim' in that specification. ...
String.prototype.trimStart() - JavaScript
The trimStart
() method removes whitespace from the beginning of a string. trimLeft
() is an alias of this method. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.trimStart
(); str.trimLeft
(); Return value A new string representing the calling string stripped of whitespace from its beginning (left end). Description The trimStart
() / trimLeft
() methods return the string stripped of whitespace from its left end. trimLeft
() or trimStart
() do not affect the value of the string itself. Aliasing For consistency with functions like String.prototype.padStart the standard method name is trimStart. However, f...
...bility reasons, trimLeft remains as an alias to trimStart. ...
... if(p in o?o[p]?false:true:true){ var r=/^\s+/; o[p]=o.trimLeft||function
(){ return this.replace(r,'') } } })(Proto,'trimStart'); })(window); /* ES6: (w=>{ const String=w.String, Proto=String.prototype; ((o,p)=>{ if(p in o?o[p]?false:true:true){ const r=/^\s+/; o[p]=o.trimLeft||function
(){ return this.replace(r,'') } } })(Proto,'trimStart'); })(window); */ Examples Using trimStart
() The following example displays the lowercase string 'foo ': var str = ' foo '; console.log(str.length); // 8 str = str.trimStart
(); console.log(str.length); // 5 console.log(str); // 'foo ' Specifications Specification ...
Symbol.prototype.toString() - JavaScript
The toString
() method returns a string representing the specified Symbol object. 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 Symbol
().toString
() Return value A string representing the specified Symbol object. Description The Symbol object overrides the toString method of the Object object; it does not inherit Object.prototype.toString
(). For Symbol objects, the toString method returns a string representation of the object. ...
...les and send us a pull request. Syntax Symbol
().toString
() Return value A string representing the specified Symbol object. Description The Symbol object overrides the toString method of the Object object; it does not inherit Object.prototype.toString
(). For Symbol objects, the toString method returns a string representation of the object. ...
...d of the Object object; it does not inherit Object.prototype.toString
(). For Symbol objects, the toString method returns a string representation of the object. No string concatenation While you can call toString
() on Symbols, you cannot use string concatenation with them: Symbol('foo') + 'bar' // TypeError: Can't convert symbol to string Examples Using toString Symbol('desc').toString
() // "Symbol(desc)" // well-known symbols Symbol.iterator.toString
() // "Symbol(Symbol.iterator) // global symbols Symbol.for('foo').toString
() // "Symbol(foo)" Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.prototype.toString' in that specification. ...
TypedArray.prototype.entries() - JavaScript
The entries
() method returns a new Array iterator object that contains the key/value pairs for each index in the array. 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 arr.entries
() Return value A new Array Iterator object. ...
...ource 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 arr.entries
() Return value A new Array Iterator object. ...
... arr.entries
() Return value A new Array Iterator object. Examples Iteration using for...of loop var arr = new Uint8Array([10, 20, 30, 40, 50]); var eArray = arr.entries
(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of eArray) { console.log(n); } Alternative iteration var arr = new Uint8Array([10, 20, 30, 40, 50]); var eArr = arr.entries
(); console.log(eArr.next
().value); // [0, 10] console.log(eArr.next
().value); // [1, 20] console.log(eArr.next
().value); // [2, 30] console.log(eArr.next
().value); // [3, 40] console.log(eArr.next
().value); // [4, 50] Specifications Specification ECMAScript (ECMA-262)The definition of '%TypedArray%.prototype.entries
()' in that specification. ...
TypedArray.prototype.findIndex() - JavaScript
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 typedarray.findIndex(callback[, thisArg]) Parameters callback Function to execute on each value in the typed array, taking three arguments: element The current element being processed in the typed array. ...
...thisArg) { 'use strict'; if (!this) { throw new TypeError('Array.prototype.some called on null or undefined'); } if (typeof(evaluator) !== 'function') { if (typeof(evaluator) === 'string') { // Attempt to convert it to a function if ( ! ...
...Error('Array.prototype.some called on null or undefined'); } if (typeof(evaluator) !== 'function') { if (typeof(evaluator) === 'string') { // Attempt to convert it to a function if ( ! ...
TypedArray.prototype.forEach() - JavaScript
The forEach
() method executes a provided function once per array element. This method has the same algorithm as Array.prototype.forEach
(). TypedArray is one of the typed array types here. Syntax typedarray.forEach(callback[, thisArg]) Parameters callback Function that produces an element of the new typed array, taking three arguments: currentValue The current element being processed in the typed array. index The index of the current element being processed in the array. array The array forEach
() was called upon. thisArg Optional. Value to use as this when executing callback. Return value undefined. Description The forEach
() method executes the provided callback once for each element present in the typed array in ascending order. It is not invoked for indexes ...
...e provided callback once for each element present in the typed array in ascending order. It is not invoked for indexes that have been deleted or elided. However, it is executed for elements that are present and have the value undefined. callback is invoked with three arguments: the element value the element index the typed array being traversed If a thisArg parameter is provided to forEach
(), it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. The range of elements processed by forEach
() is set before the first invocation of callback. Elements that are appe...
... use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. The range of elements processed by forEach
() is set before the first invocation of callback. Elements that are appended to the typed array after the call to forEach
() begins will not be visited by callback. If the values of existing elements of the typed array are changed, the value passed to callback will be the value at the time forEach
() visits them; elements that are deleted before being visited are not visited. forEach
() executes the callback function once for each typed array element; unlike every
() and some
() it, always returns the value undefined. Ex...
TypedArray.prototype.keys() - JavaScript
The keys
() method returns a new Array Iterator object that contains the keys for each index in the array. 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 arr.keys
() Return value A new Array Iterator object. ...
... 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 arr.keys
() Return value A new Array Iterator object. ...
.... Syntax arr.keys
() Return value A new Array Iterator object. Examples Iteration using for...of loop var arr = new Uint8Array([10, 20, 30, 40, 50]); var eArray = arr.keys
(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of eArray) { console.log(n); } Alternative iteration var arr = new Uint8Array([10, 20, 30, 40, 50]); var eArr = arr.keys
(); console.log(eArr.next
().value); // 0 console.log(eArr.next
().value); // 1 console.log(eArr.next
().value); // 2 console.log(eArr.next
().value); // 3 console.log(eArr.next
().value); // 4 Specifications Specification ECMAScript (ECMA-262)The definition of '%TypedArray%.prototype.keys
()' in that specification. ...
TypedArray.prototype.sort() - JavaScript
The sort
() method sorts the elements of a typed array numerically in place and returns the typed array. This method has the same algorithm as Array.prototype.sort
(), except that sorts the values numerically instead of as strings. TypedArray is one of the typed array types here. 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 typedarray.sort([compareFunction]) Parameters compareFunction Optional Specifies a function that defines the sort order. Return value The sorted typed array. Examples Using sort For more examples, see also the Array.prototype.sort
() method. let numbers = new Uint8Array([40,...
... clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax typedarray.sort([compareFunction]) Parameters compareFunction Optional Specifies a function that defines the sort order. Return value The sorted typed array. Examples Using sort For more examples, see also the Array.prototype.sort
() method. ...
...ted typed array. Examples Using sort For more examples, see also the Array.prototype.sort
() method. let numbers = new Uint8Array([40, 1, 5, 200]); numbers.sort
(); // Uint8Array [ 1, 5, 40, 200 ] // Unlike plain Arrays, a compare function is not required // to sort the numbers numerically. // Regular Arrays require a compare function to sort numerically: numbers = [40, 1, 5, 200]; numbers.sort
(); // [1, 200, 40, 5] numbers.sort((a, b) => a - b); // compare numbers // [ 1, 5, 40, 200 ] Specifications Specification ECMAScript (ECMA-262)The definition of 'TypedArray.prototype.sort' in that specification. ...
TypedArray.prototype.values() - JavaScript
The values
() method returns a new Array Iterator object that contains the values for each index in the array. 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 arr.values
() Return value A new Array Iterator object. ...
... 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 arr.values
() Return value A new Array Iterator object. ...
...tax arr.values
() Return value A new Array Iterator object. Examples Iteration using for...of loop var arr = new Uint8Array([10, 20, 30, 40, 50]); var eArray = arr.values
(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of eArray) { console.log(n); } Alternative iteration var arr = new Uint8Array([10, 20, 30, 40, 50]); var eArr = arr.values
(); console.log(eArr.next
().value); // 10 console.log(eArr.next
().value); // 20 console.log(eArr.next
().value); // 30 console.log(eArr.next
().value); // 40 console.log(eArr.next
().value); // 50 Specifications Specification ECMAScript (ECMA-262)The definition of '%TypedArray%.prototype.values
()' in that specification. ...
WeakRef.prototype.deref() - JavaScript
The deref method returns the WeakRef instance's target object, or undefined if the target object has been garbage-collected. Syntax obj = ref.deref
(); Return value The target object of the WeakRef, or undefined if the object has been garbage-collected. Notes See the Notes on WeakRefs section of the WeakRef page for some important notes. Examples Using deref See the Examples section of the WeakRef page for the complete example. ...
...object, or undefined if the target object has been garbage-collected. Syntax obj = ref.deref
(); Return value The target object of the WeakRef, or undefined if the object has been garbage-collected. Notes See the Notes on WeakRefs section of the WeakRef page for some important notes. Examples Using deref See the Examples section of the WeakRef page for the complete example. ...
...n value The target object of the WeakRef, or undefined if the object has been garbage-collected. Notes See the Notes on WeakRefs section of the WeakRef page for some important notes. Examples Using deref See the Examples section of the WeakRef page for the complete example. const tick =
() => { // Get the element from the weak reference, if it still exists const element = this.ref.deref
(); if (element) { element.textContent = ++this.count; } else { // The element doesn't exist anymore console.log("The element is gone."); this.stop
(); this.ref = null; } }; Specifications Specification WeakRefsThe definition of 'WeakRef.prototype.deref
()' in that specification. ...
WebAssembly.Memory() constructor - JavaScript
A memory created by JavaScript or in WebAssembly code will be accessible and mutable from both JavaScript and WebAssembly. Syntax new WebAssembly.Memory(memoryDescriptor); Parameters memoryDescriptor An object that can contain the following members: initial The initial size of the WebAssembly Memory, in units of WebAssembly pages. maximum Optional The maximum size the WebAssembly Memory is allowed to grow to, in units of WebAssembly pages. When present, the maximum parameter acts as a hint to the engine to reserve memory up front. ...
...ages (6.4MiB). Its buffer property will return an ArrayBuffer. var memory = new WebAssembly.Memory({initial:10, maximum:100}); The second way to get a WebAssembly.Memory object is to have it exported by a WebAssembly module. The following example (see memory.html on GitHub, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the WebAssembly.instantiateStreaming
() method, while importing the memory created in the line above. It then stores some values in that memory, then exports a function and uses it to sum some values. WebAssembly.instantiateStreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new Uint32Array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0...
...rowser 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. ...
WebAssembly.Module() constructor - JavaScript
A WebAssembly.Module
() constructor creates a new Module object containing stateless WebAssembly code that has already been compiled by the browser and can be efficiently shared with Workers, and instantiated multiple times. The WebAssembly.Module
() constructor function can be called to synchronously compile given WebAssembly binary code. However, the primary way to get a Module is through an asynchronous compilation function like WebAssembly.compile
(). Syntax Important: Since compilation for large modules can be expensive, developers should only use the Module
() constructor when synchronous compilation is absolutely required; the asynchronous WebAssembly.compileStreaming
() method should be used at all other times. new WebAssembly.Module(bufferSource); Parameters bufferSource A ty...
...A typed array or ArrayBuffer containing the binary code of the .wasm module you want to compile. Examples Synchronously compiling a WebAssembly module var importObject = { imports: { imported_func: function(arg) { console.log(arg); } } }; function createWasmModule(bytes) { return new WebAssembly.Module(bytes); } fetch('simple.wasm').then(response => response.arrayBuffer
() ).then(bytes => { let mod = createWasmModule(bytes); WebAssembly.instantiate(mod, importObject) .then(result => result.exports.exported_func
() ); }) Specifications Specification WebAssembly JavaScript InterfaceThe definition of 'WebAssembly.Module
()' in that specification. Browser compatibility The compatibility table on this page is generated from st...
...rowser 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. ...
WebAssembly.Module.exports() - JavaScript
The WebAssembly.Module.exports
() function returns an array containing descriptions of all the declared exports of the given Module. Syntax WebAssembly.Module.exports(module); Parameters module A WebAssembly.Module object. Return value An array containing objects representing the exported functions of the given module. Exceptions If module is not a WebAssembly.Module object instance, a TypeError is thrown. Examples Using exports The following example (see our index-compile.html demo on GitHub, and view it live also) compiles the loaded simple.wasm byte code using the WebAssembly.compileStreaming
() method and then sends it to a worker using postMessage
(). var worker = new Worker("wasm_worker.js"); WebAssembly.compileStreaming(fetch('simple.wasm')) .then(mod => worker.postMe...
...Message
(). var worker = new Worker("wasm_worker.js"); WebAssembly.compileStreaming(fetch('simple.wasm')) .then(mod => worker.postMessage(mod) ); In the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. when the module is received, we create an instance from it using the WebAssembly.Instantiate
() method, invoke an exported function from inside it, then show how we can return information on the available exports on a module using WebAssembly.Module.exports. var importObject = { imports: { imported_func: function(arg) { console.log(arg); } } }; onmessage = function(e) { console.log('module received from main thread'); var mod = e.data; WebAssembly.instantiate(mod,...
...eturn information on the available exports on a module using WebAssembly.Module.exports. var importObject = { imports: { imported_func: function(arg) { console.log(arg); } } }; onmessage = function(e) { console.log('module received from main thread'); var mod = e.data; WebAssembly.instantiate(mod, importObject).then(function(instance) { instance.exports.exported_func
(); }); var exports = WebAssembly.Module.exports(mod); console.log(exports[0]); }; The exports[0] output looks like this: { name: "exported_func", kind: "function" } Specifications Specification WebAssembly JavaScript InterfaceThe definition of 'exports
()' in that specification. Browser compatibility The compatibility table on this page is generated from str...
WebAssembly.Table.prototype.grow() - JavaScript
Examples Using grow The following example creates a new WebAssembly Table instance with an initial size of 2 and a maximum size of 10. ...
... Examples Using grow The following example creates a new WebAssembly Table instance with an initial size of 2 and a maximum size of 10. ...
...nitial size of 2 and a maximum size of 10. var table = new WebAssembly.Table({ element: "anyfunc", initial: 2, maximum: 10 }); You can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" Specifications Specification WebAssembly JavaScript InterfaceThe definition of 'grow
()' in that specification. 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. DesktopMobileServerChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on...
WebAssembly.compile() - JavaScript
Syntax Promise<WebAssembly.Module> WebAssembly.compile(bufferSource); Parameters bufferSource A typed array or ArrayBuffer containing the binary code of the .wasm module you want to compile. Return value A Promise that resolves to a WebAssembly.Module object representing the compiled module. Exceptions If bufferSource is not a typed array, a TypeError is thrown. If compilation fails, the promise rejects with a WebAssembly.CompileError. ...
... .wasm module you want to compile. Return value A Promise that resolves to a WebAssembly.Module object representing the compiled module. Exceptions If bufferSource is not a typed array, a TypeError is thrown. If compilation fails, the promise rejects with a WebAssembly.CompileError. Examples Using compile The following example compiles the loaded simple.wasm byte code using the compile
() function and then sends it to a worker using postMessage
(). var worker = new Worker("wasm_worker.js"); fetch('simple.wasm').then(response => response.arrayBuffer
() ).then(bytes => WebAssembly.compile(bytes) ).then(mod => worker.postMessage(mod) ); Note: You'll probably want to use WebAssembly.compileStreaming
() in most cases, as it is more efficient than compile
(). Specifications ...
... 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. ...
WebAssembly.compileStreaming() - JavaScript
Syntax Promise<WebAssembly.Module> WebAssembly.compileStreaming(source); Parameters source A Response object or a promise that will fulfill with one, representing the underlying source of a .wasm module you want to stream and compile. Return value A Promise that resolves to a WebAssembly.Module object representing the compiled module. Exceptions If bufferSource is not a typed array, a TypeError is thrown. ...
... If bufferSource is not a typed array, a TypeError is thrown. If compilation fails, the promise rejects with a WebAssembly.CompileError. Examples Compile streaming The following example (see our compile-streaming.html demo on GitHub, and view it live also) directly streams a .wasm module from an underlying source then compiles it to a WebAssembly.Module object. Because the 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 => insta...
...ise 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.instantiate
(), and the exported function invoked. Specifications Specification WebAssembly features for web embeddingThe definition of 'compileStreaming
()' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to cont...
isNaN() - JavaScript
Syntax isNaN(value) Parameters value The value to be tested. Return value true if the given value is NaN; otherwise, false. Description The necessity of an isNaN function Unlike all other possible values in JavaScript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false. Hence, the necessity of an isNaN function. Origin of NaN values NaN values are generated when arithmetic operations result in undefined or unrepresentable values. ...
...pected; the empty string, for example, is surely "not a number." The confusion stems from the fact that the term, "not a number", has a specific meaning for numbers represented as IEEE-754 floating-point values. The function should be interpreted as answering the question, "is this value, when coerced to a numeric value, an IEEE-754 'Not A Number' value?" ECMAScript 2015 contains the Number.isNaN
() function. Number.isNaN(x) is a reliable way to test whether x is NaN or not. Even with Number.isNaN, however, the meaning of NaN remains the precise numeric meaning and not simply, "not a number". Alternatively, in the absence of Number.isNaN, the expression (x != x) is a more reliable way to test whether variable x is NaN or not, as the result is not subject to the false positives that make isNa...
... which is not NaN isNaN('37.37'); // false: "37.37" is converted to the number 37.37 which is not NaN isNaN("37,5"); // true isNaN('123ABC'); // true: parseInt("123ABC") is 123 but Number("123ABC") is NaN isNaN(''); // false: the empty string is converted to 0 which is not NaN isNaN(' '); // false: a string with spaces is converted to 0 which is not NaN // dates isNaN(new Date
()); // false isNaN(new Date
().toString
()); // true // This is a false positive and the reason why isNaN is not entirely reliable isNaN('blabla'); // true: "blabla" is converted to a number. // Parsing this as a number fails and returns NaN Useful special-case behavior There is a more usage oriented way to think of isNaN
(): If isNaN(x) returns false, you c...
Array.observe() - Archive of obsolete content
However, this API has been deprecated and removed from Browsers. You can use the more general Proxy object instead. Syntax Array.observe(arr, callback) Parameters arr The array to be observed. callback The function called each time changes are made, with the following argument: changes An array of objects each representing a change. The properties of these change objects are: name: The name of the property which was changed. ...
...dex at which the change occurred. removed: Only for the "splice" type. An array of the removed elements. addedCount: Only for the "splice" type. The number of elements added. Description The callback function is called each time a change is made to arr, with an array of all changes in the order in which they occurred. Changes done via Array methods, such as Array.prototype.pop
() will be reported as "splice" changes. Index assignment changes which do not change the length of the array may be reported as "update" changes. Examples Logging different change types var arr = ['a', 'b', 'c']; Array.observe(arr, function(changes) { console.log(changes); }); arr[1] = 'B'; // [{type: 'update', object: <arr>, name: '1', oldValue: 'b'}] arr[3] = 'd'; // [{type: 'splice', ob...
ArrayBuffer.transfer() - Archive of obsolete content
The static ArrayBuffer.transfer
() method returns a new ArrayBuffer whose contents have been taken from the oldBuffer's data and then is either truncated or zero-extended by newByteLength. If newByteLength is undefined, the byteLength of the oldBuffer is used. This operation leaves oldBuffer in a detached state. Syntax ArrayBuffer.transfer(oldBuffer [, newByteLength]); Parameters oldBuffer An ArrayBuffer object from which to transfer. newByteLength The byte length of the new ArrayBuffer object. Return value A new ArrayBuffer object. Description The ArrayBuffer.transfer
() method allows you to grow and detach ArrayBuffer objects. The ability to grow an ArrayBuffer without copying has the advantage of being much faster for large buffers (similar to realloc). The ability ...
...e polyfill then the value is still 40 buf2.byteLength; // 80 new Int32Array(buf2)[0]; // 42 var buf3 = ArrayBuffer.transfer(buf2, 0); buf2.byteLength; // 0 but if you use the polyfill then the value is still 80 buf3.byteLength; // 0 Polyfill You can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of transfer
() in browsers that do not natively support it. This is not the exact equivalent of this API because browsers that natively support it are be able to internally use the C++ function realloc
() which extends the length of the memory and only copies it to a new location as-needed as opposed to the following pollyfill which always copies the whole thing to a new space of memory, but this function transf...
Object.unobserve() - Archive of obsolete content
The Object.unobserve
() method was used to remove observers set by Object.observe
(), but has been deprecated and removed from Browsers. You can use the more general Proxy object instead. Syntax Object.unobserve(obj, callback) Parameters obj The object to stop observing. callback The reference to the observer to stop calling each time changes are made on the object obj. Return value The specified object. Description Object.unobserve
() should be called after Object.observe
() in order to remove an observer from an object. The callback should be a reference to a function and not an anonymous function, because this reference will be used to unset the previous observer. ...
...p calling each time changes are made on the object obj. Return value The specified object. Description Object.unobserve
() should be called after Object.observe
() in order to remove an observer from an object. The callback should be a reference to a function and not an anonymous function, because this reference will be used to unset the previous observer. It's useless to call Object.unobserve
() with an anonymous function as callback, it will not remove any observer. Examples Unobserving an object var obj = { foo: 0, bar: 1 }; var observer = function(changes) { console.log(changes); } Object.observe(obj, observer); obj.newProperty = 2; // [{name: 'newProperty', object: <obj>, type: 'add'}] Object.unobserve(obj, observer); obj.foo = 1; // The callback wasn't called Using an...
Reflect.enumerate() - Archive of obsolete content
The static Reflect.enumerate
() method used to return an iterator with the enumerable own and inherited properties of the target object, but has been removed in ECMAScript 2016 and is deprecated in browsers. Syntax Reflect.enumerate(target) Parameters target The target object on which to get the property. Return value An iterator with the enumerable own and inherited properties of the target object. Exceptions A TypeError, if target is not an Object. Description The Reflect.enumerate method returns an iterator with the enumerable own and inherited properties of the target object. ...
...arget) Parameters target The target object on which to get the property. Return value An iterator with the enumerable own and inherited properties of the target object. Exceptions A TypeError, if target is not an Object. Description The Reflect.enumerate method returns an iterator with the enumerable own and inherited properties of the target object. Examples Using Reflect.enumerate
() var obj = { x: 1, y: 2 }; for (var name of Reflect.enumerate(obj)) { console.log(name); } // logs "x" and "y" Specifications Not part of any standard. ...
String.prototype.quote() - Archive of obsolete content
Obsolete since Gecko 37 (Firefox 37 / Thunderbird 37 / SeaMonkey 2.34)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. The non-standard quote
() method returns a copy of the string, replacing various special characters in the string with their escape sequences and wrapping the result in double-quotes ("). Syntax str.quote
() Return value A new string representing the original string wrapped in double-quotes, with any special characters escaped. Examples Using quote In the table below the quote
() method replaces any special characters and wraps the strings in double-quotes. Also note the third column where a wrapped eval
() evaluates the escape sequences again. s...
...s ("). Syntax str.quote
() Return value A new string representing the original string wrapped in double-quotes, with any special characters escaped. Examples Using quote In the table below the quote
() method replaces any special characters and wraps the strings in double-quotes. Also note the third column where a wrapped eval
() evaluates the escape sequences again. str str.quote
() eval(str.quote
()) Hello world! "Hello world!" Hello world! Hello world! "Hello\n\tworld!" Hello world! " \ -- ' "\" \\ \u2014 '" " \ -- ' Specifications Not part of any standard. Implemented in JavaScript 1.3. ...
handler.enumerate() - Archive of obsolete content
The handler.enumerate
() method used to be a trap for for...in statements, but has been removed from the ECMAScript standard in ES2016 and is deprecated in browsers. Syntax var p = new Proxy(target, { enumerate(target) { } }); Parameters The following parameter is passed to the enumerate method. this is bound to the handler. target The target object. Return value An iterator object. Description The handler.enumerate method is a trap for for...in statements. Interceptions This trap can intercept these operations: Property enumeration / for...in: for (var name in proxy) {...} Reflect.enumerate
() Invariants If the following invariants are violated, the proxy will throw a TypeError: The enumerate method must return an object. Examples The following code...
... Property enumeration / for...in: for (var name in proxy) {...} Reflect.enumerate
() Invariants If the following invariants are violated, the proxy will throw a TypeError: The enumerate method must return an object. Examples The following code traps for...in statements. var p = new Proxy({}, { enumerate(target) { console.log('called'); return ['a', 'b', 'c'][Symbol.iterator]
(); } }); for (var x in p) { // "called" console.log(x); // "a" } // "b" // "c" The following code violates the invariant. var p = new Proxy({}, { enumerate(target) { return 1; } }); for (var x in p) {} // TypeError is thrown Note: Both examples make use of the shorthand syntax for method definitions. Specifications Not part of any standard. ...
Window.importDialog() - Archive of obsolete content
use is discouraged since it could be removed at any time. Try to avoid using it. This function was only available in the original, XUL-based version of Firefox for Android, which is no longer supported; for that reason, this function is obsolete and should never be used. Summary Because opening windows on mobile isn't necessarily appropriate, the Firefox Mobile team designed the importDialog
() method to replace window.openDialog
(). Instead of opening a new window, it merges the specified XUL dialog into the main window. Syntax newDialog = importDialog(aParent, aSrc, aArguments) newDialog The opened window aParent The dialog's parent; can be null. aSrc The chrome URL of the XUL dialog. aArguments A JavaScript object containing data to pass to the dialog. Example var dial...
...main window. Syntax newDialog = importDialog(aParent, aSrc, aArguments) newDialog The opened window aParent The dialog's parent; can be null. aSrc The chrome URL of the XUL dialog. aArguments A JavaScript object containing data to pass to the dialog. Example var dialog = importDialog(null, "chrome://myextension/content/dialog.xul", myObject); Notes The XUL passed to importDialog
() is very similar to XUL passed to window.openDialog
(), with some limitations and caveats: Only <dialog> top level elements are permitted. Scripts are loaded via an attribute on the <dialog> element, not via the <script> tag. The XUL is merged into the existing window, almost like a XUL overlay. Because of this, element ID and JavaScript conflicts are possible, just like overlays. So be caref...
HTMLIFrameElement.download()
Syntax var instanceOfDOMRequest = instanceOfHTMLIframeElement.download(url, options); Returns A DOMRequest for handling the download request. Its request.onsuccess handler handles the success case, and its request.onerror handler handles the failure case. Parameters url The URL of the file to be downloaded. options Optional An options object allowing optional settings to be specified for the download. The available options are: filename: The filename to save the downloaded file as. If this is not specified, the filename used will be the original filename, as specified in the url. ...
...o save the downloaded file as. If this is not specified, the filename used will be the original filename, as specified in the url. referrer: Specifies a referrer for the downloaded file. If this is not specified there will be no referrer. Examples var browser = document.querySelector('iframe'); var request = browser.download(fooURL, { filename: 'foo.bin' }); request.onsuccess = function
() { console.log("File downladed"); } request.onerror = function
() { console.log("Download error"); } Specification Not part of any specification. ...
HTMLIFrameElement.executeScript()
Note: Use of the Browser API requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. See Using the Browser API for more details. Syntax var myDOMRequest = instanceOfHTMLIframeElement.executeScript(script, options); Return value A DOMRequest object that returns an onsuccess handler if the script is successfully executed against the loaded content, or an onerror handler if not. Parameters script The script to be executed. ...
...xpected context: origin: an origin, e.g. http://example.com url: a URL, e.g. http://example.com/index.html Note: The options parameter does not currently seem to have much effect. The script seems to execute even if a URL/origin is specified. Examples var request1 = browser.executeScript( var a = 3; a + 3 , {url: 'http://example.com/index.html'}); request1.onsuccess = function
() { console.log(request1.result); // 6 } var request2 = browser.executeScript( new Promise((resolve, reject) => { setTimeout(function
() { resolve(6); }, 1000}) ) , {origin: 'http://example.com'}); request2.onsuccess = function
() { console.log(request2.result); // 6 } If the script value is a not a Promise, it is simply returned as the request value. If the script value is a...
HTMLIFrameElement.findAll()
Invoking this method results in a mozbrowserfindchange event firing, which carries details about the search results. Note: Use of the Browser API requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. See Using the Browser API for more details. Syntax instanceOfHTMLIframeElement.findAll(searchString, caseSensitivity); Returns Void. Parameters searchString The string you want to search for in the browser <iframe>'s text. ...
...e>'s text. caseSensitivity A string to declare whether you want the search to be case sensitive (case-sensitive) or insensitive (case-insensitive.) Example The following function is taken from our Browser API demo, and executes a search when a search form is submitted. See Implementing the search bar for more explanation. searchForm.addEventListener('submit', function(e) { e.preventDefault
(); browser.findAll(searchBar.value, 'case-sensitive'); searchActive = true; prev.disabled = false; next.disabled = false; searchBar.blur
(); }); Specification Not part of any specification. ...
HTMLIFrameElement.findNext()
Invoking this method results in a mozbrowserfindchange event firing, which carries details about the search results. Note: Use of the Browser API requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. See Using the Browser API for more details. Syntax instanceOfHTMLIframeElement.findNext(direction); Return value Void. Parameters direction A string indicating the direction in which you want to cycle through the available search results. Available values are forward and backward. ...
...n value Void. Parameters direction A string indicating the direction in which you want to cycle through the available search results. Available values are forward and backward. Examples The following functions are taken from our Browser API demo, and cycle through the available search results. See Implementing the search bar for more explanation. prev.addEventListener('touchend',function
() { browser.findNext('backward'); }); next.addEventListener('touchend',function
() { browser.findNext('forward'); }); Specification Not part of any specification. ...
HTMLIFrameElement.getContentDimensions()
Warning: Removed in Firefox 65. The getContentDimensions
() method of the HTMLIFrameElement interface retrieves the X and Y dimensions of the content window. Note: The values returned are equivalent to document.body.scrollWidth and document.body.scrollHeight. Syntax var instanceOfDOMRequest = instanceOfHTMLIframeElement.getContentDimensions
(); Returns A DOMRequest for handling the dimensions request. Its request.onsuccess handler handles the success case, and its request.onerror handler handles the failure case. The X and Y dimensions are available in the request.result.x and request.result.y properties, respectively. Parameters None. ...
...urns A DOMRequest for handling the dimensions request. Its request.onsuccess handler handles the success case, and its request.onerror handler handles the failure case. The X and Y dimensions are available in the request.result.x and request.result.y properties, respectively. Parameters None. Examples var browser = document.querySelector('iframe'); var request = browser.getContentDimensions
(); request.onsuccess = function
() { console.log("page size:", request.result.width + "x" + request.result.height); } request.onerror = function
() { console.log("Download error"); } Specification Not part of any specification. ...
HTMLIFrameElement.getVisible()
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The getVisible
() method of the HTMLIFrameElement is used to request the current visible state of the browser <iframe>. Syntax instanceOfDOMRequest = instanceOfHTMLIframeElement.getVisible
(); Returns A DOMRequest object to handle the getVisible
() request's success and error cases. If the request is successful, the request's result is a Boolean indicating the visible state of the browser <iframe>. Parameters None. Example var browser = document.querySelector('iframe'); var request = browser.ge...
...rame>. Syntax instanceOfDOMRequest = instanceOfHTMLIframeElement.getVisible
(); Returns A DOMRequest object to handle the getVisible
() request's success and error cases. If the request is successful, the request's result is a Boolean indicating the visible state of the browser <iframe>. Parameters None. Example var browser = document.querySelector('iframe'); var request = browser.getVisible
(); request.onsuccess = function
() { console.log('The visible state is: ' + this.result ? 'true' : 'false'); } Specification Not part of any specification. ...
HTMLIFrameElement.getVolume()
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The getVolume
() method of the HTMLIFrameElement gets the current volume of the browser <iframe>. Syntax There are two versions of this method, a callback version: var request = instanceOfHTMLIframeElement.getVolume
(); and a Promise version: instanceOfHTMLIframeElement.getVolume
().then(function(volume) { ... }); Returns Callback version: A DOMRequest that represents the get volume request. It has an onsuccess handler to handle the success case, and an onerror handler to handle the failure ca...
..., and an onerror handler to handle the failure case. The volume value is available in the request.result property, and is a floating point number between 0 and 1. Promise version: A Promise that resolves with the volume value -- a floating point number between 0 and 1. Parameters None. Example Callback version: var browser = document.querySelector('iframe'); var request = browser.getVolume
(); request.onsuccess = function
() { console.log('The current browser volume is ' + request.result); } Promise version: var browser = document.querySelector('iframe'); browser.getVolume
().then(function(volume) { console.log('The current browser volume is ' + volume); }); Specification Not part of any specification. ...
HTMLIFrameElement.goBack()
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The goBack
() method of the HTMLIFrameElement interface is used to navigate backwards in the browser <iframe>'s history. ...
... The goBack
() method of the HTMLIFrameElement interface is used to navigate backwards in the browser <iframe>'s history. By calling this method, the browser <iframe> changes its location for the previous location available in its navigation history, which sends a series of related events: mozbrowserlocationchange, mozbrowserloadstart, and so on. Syntax instanceOfHTMLIframeElement.goBack
(); Returns Void. Parameters None. Examples back.addEventListener('touchend',function
() { browser.goBack
(); }); Specification Not part of any specification. ...
HTMLIFrameElement.goForward()
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The goForward
() method of the HTMLIFrameElement is used to navigate forward in the browser <iframe>'s history. ...
... the future. The goForward
() method of the HTMLIFrameElement is used to navigate forward in the browser <iframe>'s history. By calling this method, the browser <iframe> changes its location to the next location available in its navigation history, which sends a series of related events: mozbrowserlocationchange, mozbrowserloadstart and so on. Syntax instanceOfHTMLIframeElement.goForward
(); Returns Void. Parameters None. Examples fwd.addEventListener('touchend',function
() { browser.goForward
(); }); Specification Not part of any specification. ...
HTMLIFrameElement.reload()
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The reload
() method of the HTMLIFrameElement interface is used to reload the content of the <iframe>. Syntax instanceOfHTMLIframeElement.reload(hardReload); Returns Void. ...
...thod of the HTMLIFrameElement interface is used to reload the content of the <iframe>. Syntax instanceOfHTMLIframeElement.reload(hardReload); Returns Void. Parameters hardReload Optional A boolean that indicates whether all the resources to reload must be revalidated (true) or may be taken directly from the browser cache (false). Examples stopReload.addEventListener('touchend',function
() { if(stopReload.textContent === 'x') { browser.stop
(); } else { browser.reload
(); } }); Specification Not part of any specification. ...
HTMLIFrameElement.zoom()
Warning: Removed in Firefox 65. The zoom
() method of the HTMLIFrameElement interface changes the zoom factor of the browser <iframe>'s content. This is particularly useful for zooming in/out on non-touch-enabled devices. Syntax var instanceOfDOMRequest = instanceOfHTMLIframeElement.zoom(zoomFactor); Returns Void. Parameters zoomFactor A unitless number value representing the amount to zoom in or out. It acts like a percentage, so for example 1.1 would zoom in by 10%, whereas 0.9 would zoom out by 10%. ...
...eOfDOMRequest = instanceOfHTMLIframeElement.zoom(zoomFactor); Returns Void. Parameters zoomFactor A unitless number value representing the amount to zoom in or out. It acts like a percentage, so for example 1.1 would zoom in by 10%, whereas 0.9 would zoom out by 10%. Examples var browser = document.querySelector('iframe'); var zoomFactor = 1; zoomIn.addEventListener('touchend',function
() { zoomFactor += 0.1; browser.zoom(zoomFactor); }); zoomOut.addEventListener('touchend',function
() { zoomFactor -= 0.1; browser.zoom(zoomFactor); }); Specification Not part of any specification. ...
ANGLE_instanced_arrays.vertexAttribDivisorANGLE() - Web APIs
Syntax void ext.vertexAttribDivisorANGLE(index, divisor); Parameters index A GLuint specifying the index of the generic vertex attributes. divisor A GLuint specifying the number of instances that will pass between updates of the generic attribute. Return value None. ...
... Syntax void ext.vertexAttribDivisorANGLE(index, divisor); Parameters index A GLuint specifying the index of the generic vertex attributes. divisor A GLuint specifying the number of instances that will pass between updates of the generic attribute. Return value None. ...
AmbientLightSensor.AmbientLightSensor() - 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. Syntax var ambientLightSensor = new AmbientLightSensor(options) Parameters options Optional Currently only one option is supported: frequency: The desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called. ...
... Candidate Recommendation ...
AnalyserNode.AnalyserNode() - Web APIs
is. The default is -30. minDecibels: The desired initial minimum power in dB for FFT analysis. The default is -100. smoothingTimeConstant: The desired initial smoothing constant for the FFT analysis. The default is 0.8. Return value A new AnalyserNode object instance. Specifications Specification Status Comment Web Audio APIThe definition of 'AnalyserNode
() constructor' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for Androi...
... 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. ...
Animation() - Web APIs
Syntax var animation = new Animation([effect][, timeline]); Parameters effect Optional The target effect, as an object based on the AnimationEffectReadOnly interface, to assign to the animation. Although in the future other effects such as SequenceEffects or GroupEffects might be possible, the only kind of effect currently available is KeyframeEffect. This can be null (which is the default) to indicate that there should be no effect applied. timeline Optional Specifies the timeline with which to associate the animation, as an object of a type based on the AnimationTimeline interface. ...
...th which to associate the animation, as an object of a type based on the AnimationTimeline interface. Currently the only timeline type available is DocumentTimeline, but in the future there my be timelines associated with gestures or scrolling, for example. The default value is Document.timeline, but this can be set to null as well. Examples In the Follow the White Rabbit example, the Animation
() constructor is used to create an Animation for the rabbitDownKeyframes using the document's timeline: var rabbitDownAnimation = new Animation(rabbitDownKeyframes, document.timeline); Specifications Specification Status Comment Web AnimationsThe definition of 'Animation
()' in that specification. Working Draft Editor's draft. ...
Animation.commitStyles() - Web APIs
The commitStyles
() method of the Web Animations API's Animation interface commits the end styling state of an animation to the element being animated, even after that animation has been removed. It will cause the end styling state to be written to the element being animated, in the form of properties inside a style attribute. Syntax animation.commitStyles
(); Parameters None. Return value None. ...
...form of properties inside a style attribute. Syntax animation.commitStyles
(); Parameters None. Return value None. Examples const divElem = document.querySelector('div'); document.body.addEventListener('mousemove', evt => { let anim = divElem.animate( { transform: `translate(${ evt.clientX}px, ${evt.clientY}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitStyles
(); }); Specifications Specification Status Comment Web AnimationsThe definition of 'commitStyles
()' in that specification. Working Draft ...
AnimationEffect.getComputedTiming() - Web APIs
The getComputedTiming
() method of the AnimationEffect interface returns the calculated timing properties for this animation effect. Although many of the attributes of the returned object are common to the EffectTiming contained in the object returned by the AnimationEffect.getTiming
() method, the values returned by this object differ in the following ways: duration Returns the calculated value of the iteration duration. If EffectTiming.duration is the string auto, this attribute will return 0. fill The auto value is replaced with the appropriate EffectTiming.fill value. These values are comparable to the computed styles of an Element returned using window.getComputedStyle(elem). Syntax var currentTimeValues = animation.getComputedTiming
(); Parameters None. Return Value ...
... Working Draft Editor's draft. ...
AnimationEvent.initAnimationEvent() - Web APIs
Syntax animationEvent.initAnimationEvent(typeArg, canBubbleArg, cancelableArg, animationNameArg, elapsedTimeArg); Parameters typeArg A DOMString identifying the specific type of animation event that occurred. ...
... animation event created using the deprecated Document.createEvent("AnimationEvent") method. AnimationEvent created this way are untrusted. Note: During the standardization process, this method was removed from the specification. It has been deprecated and is in the progress of being removed from most implementations. Do not use this method; instead, use the standard constructor, AnimationEvent
(), to create a synthetic AnimationEvent. Syntax animationEvent.initAnimationEvent(typeArg, canBubbleArg, cancelableArg, animationNameArg, elapsedTimeArg); Parameters typeArg A DOMString identifying the specific type of animation event that occurred. The following values are allowed: Value Meaning animationstart The animation has started. an...
AnimationPlaybackEvent.AnimationPlaybackEvent() - Web APIs
Syntax var animationPlaybackEvent = new AnimationPlaybackEvent(type, eventInitDict); Parameters type A DOMString representing the name of the event. eventInitDict Optional An optional EventInit dictionary object containing the following fields: bubbles Optional Defaults to false, of type Boolean, indicating if the event bubbles or not. cancelable Optional Defaults to false, of type Boolean, indicating if the event can be canceled or not. detail Optional Defaults to null, of type any -- an event-dependent value associated with the event. ...
...of type Boolean, indicating if the event bubbles or not. cancelable Optional Defaults to false, of type Boolean, indicating if the event can be canceled or not. detail Optional Defaults to null, of type any -- an event-dependent value associated with the event. Specifications Specification Status Comment Web AnimationsThe definition of 'AnimationPlaybackEvent
()' in that specification. Working Draft Editor's draft. ...
AudioContext() - Web APIs
Available properties are as follows: latencyHint Optional The type of playback that the context will be used for, as a value from the AudioContextLatencyCategory enum or a double-precision floating-point value indicating the preferred maximum latency of the context in seconds. ...
... Working Draft Initial definition. ...
AudioParam.cancelScheduledValues() - Web APIs
The cancelScheduledValues
() method of the AudioParam Interface cancels all scheduled future changes to the AudioParam. Syntax var AudioParam = AudioParam.cancelScheduledValues(startTime) Parameters startTime A double representing the time (in seconds) after the AudioContext was first created after which all scheduled changes will be cancelled. Returns A reference to this AudioParam object. In some older implementations this method returns void. ...
...e AudioParam. Syntax var AudioParam = AudioParam.cancelScheduledValues(startTime) Parameters startTime A double representing the time (in seconds) after the AudioContext was first created after which all scheduled changes will be cancelled. Returns A reference to this AudioParam object. In some older implementations this method returns void. Examples var gainNode = audioCtx.createGain
(); gainNode.gain.setValueCurveAtTime(waveArray, audioCtx.currentTime, 2); //'gain' is the AudioParam gainNode.gain.cancelScheduledValues(audioCtx.currentTime); Specifications Specification Status Comment Web Audio APIThe definition of 'cancelScheduledValues' in that specification. Working Draft ...
BaseAudioContext.createIIRFilter() - Web APIs
Syntax var iirFilter = AudioContext.createIIRFilter(feedforward, feedback); Parameters feedforward An array of floating-point values specifying the feedforward (numerator) coefficients for the transfer function of the IIR filter. The maximum length of this array is 20, and at least one value must be nonzero. feedback An array of floating-point values specifying the feedback (denominator) coefficients for the transfer function of the IIR filter. This array may have up to 20 members, the first of which must not be zero. ...
... Working Draft ...
BaseAudioContext.createOscillator() - Web APIs
The createOscillator
() method of the BaseAudioContext interface creates an OscillatorNode, a source representing a periodic waveform. It basically generates a constant tone. Syntax var oscillatorNode = audioCtx.createOscillator
(); Returns An OscillatorNode. Example The following example shows basic usage of an AudioContext to create an oscillator node. For applied examples/information, check out our Violent Theremin demo (see app.js for relevant code); also see our OscillatorNode page for more information. ...
...scillator
(); Returns An OscillatorNode. Example The following example shows basic usage of an AudioContext to create an oscillator node. For applied examples/information, check out our Violent Theremin demo (see app.js for relevant code); also see our OscillatorNode page for more information. // create web audio api context var audioCtx = new (window.AudioContext || window.webkitAudioContext)
(); // create Oscillator node var oscillator = audioCtx.createOscillator
(); oscillator.type = 'square'; oscillator.frequency.setValueAtTime(3000, audioCtx.currentTime); // value in hertz oscillator.connect(audioCtx.destination); oscillator.start
(); Specifications Specification Status Comment Web Audio APIThe definition of 'createOscillator' in that specification. Worki...
Blob() - Web APIs
The content of the blob consists of the concatenation of the values given in the parameter array. Syntax var newBlob = new Blob(array, options); Parameters array An Array of ArrayBuffer, ArrayBufferView, Blob, USVString objects, or a mix of any of such objects, that will be put inside the Blob. USVString objects are encoded as UTF-8. options Optional An optional object of type BlobPropertyBag which may specify any of the following properties: type Optional The MIME type of the data that will be stored into the blob. The default value is the empty string, (""). endings Optional How to interpret newline characters (\n) within the contents, if the data is text. ...
...s native convention, specify the value native. Return value A new Blob object containing the specified data. Example var aFileParts = ['<a id="a"><b id="b">hey!</b></a>']; // an array consisting of a single DOMString var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob Specification Specification Status Comment File APIThe definition of 'Blob
()' in that specification. Working Draft Initial definition. ...
Blob.arrayBuffer() - Web APIs
The arrayBuffer
() method in the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. Syntax var bufferPromise = blob.arrayBuffer
(); blob.arrayBuffer
().then(buffer => /* process the ArrayBuffer */); var buffer = await blob.arrayBuffer
(); Parameters None. Returns A promise that resolves with an ArrayBuffer that contains the blob's data in binary form. Exceptions While this method doesn't throw exceptions, it may reject the promise. This can happen, for example, if the reader used to fetch the blob's data throws an exception. Any exceptions thrown while getting the data will be converted into rejections. ...
...at resolves with an ArrayBuffer that contains the blob's data in binary form. Exceptions While this method doesn't throw exceptions, it may reject the promise. This can happen, for example, if the reader used to fetch the blob's data throws an exception. Any exceptions thrown while getting the data will be converted into rejections. Usage notes While similar to the FileReader.readAsArrayBuffer
() method, arrayBuffer
() returns a promise rather than being an event-based API, as is the case with the FileReader interface's method. Specifications Specification Status Comment File APIThe definition of 'Blob.arrayBuffer
()' in that specification. Working Draft ...
Blob.slice() - Web APIs
Syntax var newBlob = blob.slice(start, end, contentType); Parameters start Optional An index into the Blob indicating the first byte to include in the new Blob. If you specify a negative value, it's treated as an offset from the end of the Blob toward the beginning. For example, -10 would be the 10th from last byte in the Blob. The default value is 0. If you specify a value for start that is larger than the size of the source Blob, the returned Blob has size 0 and contains no data. end Optional An index into the Blob indicating the first byte that will *not* be included in the new Blob (i.e. ...
... Working Draft Initial definition ...
Blob.stream() - Web APIs
The Blob interface's stream
() method returns a ReadableStream which upon reading returns the data contained within the Blob. Syntax var stream = blob.stream
(); Parameters None. Returns A ReadableStream which, upon reading, returns the contents of the Blob. Usage notes With stream
() and the returned ReadableStream, you gain several interesting capabilities: Call getReader
() on the returned stream to get an object to use to read the data from the blob using methods such as the ReadableStreamDefaultReader interface's read
() method. Call the returned stream's pipeTo
() method to pipe the blob's data to a writable stream. Call the returned stream's tee
() method to tee the readable stream. This returns an array containing two new ReadableStream objects, each of which returns the conte...
...he blob using methods such as the ReadableStreamDefaultReader interface's read
() method. Call the returned stream's pipeTo
() method to pipe the blob's data to a writable stream. Call the returned stream's tee
() method to tee the readable stream. This returns an array containing two new ReadableStream objects, each of which returns the contents of the Blob. Call the returned stream's pipeThrough
() method to pipe the stream through a TransformStream or any other readable and writable pair. Specifications Specification Status Comment File APIThe definition of 'Blob.stream
()' in that specification. Working Draft ...
Blob.text() - Web APIs
The text
() method in the Blob interface returns a Promise that resolves with a string containing the contents of the blob, interpreted as UTF-8. Syntax var textPromise = blob.text
(); blob.text
().then(text => /* do something with the text */); var text = await blob.text
(); Parameters None. Returns A promise that resolves with a USVString which contains the blob's data as a text string. The data is always presumed to be in UTF-8 format. Usage notes The FileReader method readAsText
() is an older method that performs a similar function. It works on both Blob and File objects. There are two key differences: Blob.text
() returns a promise, whereas FileReader.readAsText
() is an event based API. ...
...t resolves with a USVString which contains the blob's data as a text string. The data is always presumed to be in UTF-8 format. Usage notes The FileReader method readAsText
() is an older method that performs a similar function. It works on both Blob and File objects. There are two key differences: Blob.text
() returns a promise, whereas FileReader.readAsText
() is an event based API. Blob.text
() always uses UTF-8 as encoding, while FileReader.readAsText
() can use a different encoding depending on the blob's type and a specified encoding name. Specifications Specification Status Comment File APIThe definition of 'Blob.text
()' in that specification. Working Draft ...
CSSStyleDeclaration.removeProperty() - Web APIs
Syntax var oldValue = style.removeProperty(property); Parameters property is a DOMString representing the property name to be removed. Note that multi-word property names are hyphenated and not camel-cased. Return value oldValue is a DOMString equal to the value of the CSS property before it was removed. Exceptions DOMException NO_MODIFICATION_ALLOWED_ERR: if the property or declaration block is read only. ...
... block is read only. Example The following JavaScript code removes the background-color CSS property from a selector rule: var declaration = document.styleSheets[0].rules[0].style; var oldValue = declaration.removeProperty('background-color'); Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleDeclaration.removeProperty
()' in that specification. Working Draft Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSStyleDeclaration' in that specification. Obsolete ...
CSSStyleSheet.removeRule() - Web APIs
The obsolete CSSStyleSheet method removeRule
() removes a rule from the stylesheet object. It is functionally identical to the standard, preferred method deleteRule
(). Note: This is a legacy method which has been replaced by the standard method deleteRule
(). You should use that instead. Syntax cssStyleSheet.removeRule(index) Parameters index The index into the stylesheet's CSSRuleList indicating the rule to be removed. Return value undefined Example This example removes the first rule from the stylesheet myStyles. ...
...replaced by the standard method deleteRule
(). You should use that instead. Syntax cssStyleSheet.removeRule(index) Parameters index The index into the stylesheet's CSSRuleList indicating the rule to be removed. Return value undefined Example This example removes the first rule from the stylesheet myStyles. myStyles.removeRule(0); You can rewrite this to use the standard deleteRule
() method very easily: myStyles.deleteRule(0); Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleSheet.removeRule
()' in that specification. Working Draft ...
CSSStyleValue.parse() - Web APIs
Syntax CSSStyleValue.parse(property, cssText) Parameters property A CSS property to set. cssText A comma-separated string containing one or more values to apply to the provided property. Return value A CSSStyleValue object containing the first supplied value. Example The code below parses a set of declarations for the transform property. The second code block shows the structure of the returned object as it would be rendered in a developer tools console. ...
.... The second code block shows the structure of the returned object as it would be rendered in a developer tools console. const css = CSSStyleValue.parse( 'transform', 'translate3d(10px,10px,0) scale(0.5)'); CSSTransformValue {0: CSSTranslate, 1: CSSScale, length: 2, is2D: false} Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'parse
()' in that specification. Working Draft Initial definition. ...
CSSUnparsedValue.forEach() - Web APIs
The CSSUnparsedValue.forEach
() method executes a provided function once for each element of the CSSUnparsedValue. Syntax CSSUnparsedValue.forEach(function callback(currentValue[, index[, array]]) { // your iterator }[, thisArg]); Parameters callback The function to execute for each element, taking three arguments: currentValue The value of the current element being processed. indexOptional The index of the current element being processed. arrayOptional The CSSUnparsedValue that forEach
() is being called on. thisArg Optional Value to use as this (i.e the reference Object) when executing callback. Return value undefined. ...
...ing processed. indexOptional The index of the current element being processed. arrayOptional The CSSUnparsedValue that forEach
() is being called on. thisArg Optional Value to use as this (i.e the reference Object) when executing callback. Return value undefined. Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'forEach
()' in that specification. Working Draft Initial definition. ...
Cache.delete() - Web APIs
If no Cache entry is found, it resolves to false. Syntax cache.delete(request, {options}).then(function(found) { // your cache entry has been deleted if found }); Parameters request The Request you are looking to delete. This can be a Request object or a URL. options Optional An object whose properties control how matching is done in the delete operation. The available options are: ignoreSearch: A Boolean that specifies whether the matching process should ignore the query string in the url. ...
...t defaults to false. ignoreVary: A Boolean that, when set to true, tells the matching operation not to perform VARY header matching. In other words, if the URL matches you will get a match regardless of whether the Response object has a VARY header. It defaults to false. cacheName: A DOMString that represents a specific cache to search within. Note that this option is ignored by Cache.delete
(). Return value a Promise that resolves to true if the cache entry is deleted, or false otherwise. Examples caches.open('v1').then(function(cache) { cache.delete('/images/image.png').then(function(response) { someUIUpdateFunction
(); }); }) Specifications Specification Status Comment Service WorkersThe definition of 'Cache: delete' in that specification. ...
Cache.keys() - Web APIs
The requests are returned in the same order that they were inserted. Note: Requests with duplicate URLs but different headers can be returned if their responses have the VARY header set on them. Syntax cache.keys(request, {options}).then(function(keys) { // do something with your array of requests }); Parameters request Optional The Request want to return, if a specific key is desired. This can be a Request object or a URL. options Optional An object whose properties control how matching is done in the keys operation. The available options are: ignoreSearch: A Boolean that specifies whether the matching process should ignore the query string in the url. ...
... It defaults to false. ignoreVary: A Boolean that, when set to true, tells the matching operation not to perform VARY header matching. In other words, if the URL matches you will get a match regardless of whether the Response object has a VARY header. It defaults to false. cacheName: A DOMString that represents a specific cache to search within. Note that this option is ignored by Cache.keys
(). Return value A Promise that resolves to an array of Cache keys. Examples caches.open('v1').then(function(cache) { cache.keys
().then(function(keys) { keys.forEach(function(request, index, array) { cache.delete(request); }); }); }) Specifications Specification Status Comment Service WorkersThe definition of 'Cache: keys' in that specification. ...
Cache.matchAll() - Web APIs
Syntax cache.matchAll(request, {options}).then(function(response) { // do something with the response array }); Parameters request Optional The Request for which you are attempting to find responses in the Cache. This can be a Request object or a URL. If this argument is omitted, you will get a copy of all responses in this cache. options Optional An options object allowing you to set specific control options for the matching performed. The available options are: ignoreSearch: A Boolean that specifies whether the matching process should ignore the query string in the url. ...
...e allowed.) It defaults to false. ignoreVary: A Boolean that when set to true tells the matching operation not to perform VARY header matching -- i.e. if the URL matches you will get a match regardless of the Response object having a VARY header or not. It defaults to false. Return value A Promise that resolves to an array of all matching responses in the Cache object. Note: Cache.match
() is basically identical to Cache.matchAll
(), except that rather than resolving with an array of all matching responses, it resolves with the first matching response only (that is, response[0]). Examples caches.open('v1').then(function(cache) { cache.matchAll('/images/').then(function(response) { response.forEach(function(element, index, array) { cache.delete(element); }); }); ...
CacheStorage.has() - Web APIs
The has
() method of the CacheStorage interface returns a Promise that resolves to true if a Cache object matches the cacheName. You can access CacheStorage through the global caches property. Syntax caches.has(cacheName).then(function(boolean) { // true: your cache exists! }); Parameters cacheName A DOMString representing the name of the Cache object you are looking for in the CacheStorage. Return value a Promise that resolves to true if the cache exists or false if not. Examples The following example first checks whether a cache called 'v1' exists. If so, we add a list of assets to it. If not then we run some kind of cache set-up function. caches.has('v1').then(function(hasCache) { if (!hasCache) { someCacheSetupfunction
(); } else { caches.open('v1').then(funct...
...e if not. Examples The following example first checks whether a cache called 'v1' exists. If so, we add a list of assets to it. If not then we run some kind of cache set-up function. caches.has('v1').then(function(hasCache) { if (!hasCache) { someCacheSetupfunction
(); } else { caches.open('v1').then(function(cache) { return cache.addAll(myAssets); }); } }).catch(function
() { // Handle exception here. }); Specifications Specification Status Comment Service WorkersThe definition of 'CacheStorage: has' in that specification. Working Draft Initial definition. ...
CacheStorage.open() - Web APIs
The open
() method of the CacheStorage interface returns a Promise that resolves to the Cache object matching the cacheName. You can access CacheStorage through the global caches property. Note: If the specified Cache does not exist, a new cache is created with that cacheName and a Promise that resolves to this new Cache object is returned. Syntax caches.open(cacheName).then(function(cache) { // Do something with your cache }); Parameters cacheName The name of the cache you want to open. Return value A Promise that resolves to the requested Cache object. Examples This example is from the MDN sw-test example (see sw-test running live). Here we wait for an InstallEvent to fire, then runs waitUntil
() to handle the install process for the app. This consists of calling CacheSto...
...omething with your cache }); Parameters cacheName The name of the cache you want to open. Return value A Promise that resolves to the requested Cache object. Examples This example is from the MDN sw-test example (see sw-test running live). Here we wait for an InstallEvent to fire, then runs waitUntil
() to handle the install process for the app. This consists of calling CacheStorage.open
() to create a new cache, then using Cache.addAll
() to add a series of assets to it. self.addEventListener('install', function(event) { event.waitUntil( caches.open('v1').then(function(cache) { return cache.addAll([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-lo...
CanvasCaptureMediaStreamTrack.requestFrame() - Web APIs
The CanvasCaptureMediaStreamTrack method requestFrame
() requests that a frame be captured from the canvas and sent to the stream. Applications that need to carefully control the timing of rendering and frame capture can use requestFrame
() to directly specify when it's time to capture a frame. To prevent automatic capture of frames, so that frames are only captured when requestFrame
() is called, specify a value of 0 for the captureStream
() method when creating the stream. Syntax stream.requestFrame
(); Return value undefined Usage notes There is currently an issue flagged in the specification pointing out that at this time, no exceptions are being thrown if the canvas isn't origin-clean. This may change in the future, so it would be wise to plan ahead and watch for exceptions such as ...
...ns such as SecurityError (although the specific error that might be thrown is not mentioned in the spec, this is a likely candidate). Example // Find the canvas element to capture var canvasElt = document.getElementsByTagName("canvas")[0]; // Get the stream var stream = canvasElt.captureStream(25); // 25 FPS // Send the current state of the canvas as a frame to the stream stream.getVideoTracks
()[0].requestFrame
(); Specifications Specification Status Comment Media Capture from DOM ElementsThe definition of 'CanvasCaptureMediaStream.requestFrame
()' in that specification. Working Draft Initial definition ...
CanvasRenderingContext2D.beginPath() - Web APIs
The CanvasRenderingContext2D.beginPath
() method of the Canvas 2D API starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path. Note: To create a new sub-path, i.e., one matching the current canvas state, you can use CanvasRenderingContext2D.moveTo
(). Syntax void ctx.beginPath
(); Examples Creating distinct paths This example creates two paths, each of which contains a single line. HTML <canvas id="canvas"></canvas> JavaScript The beginPath
() method is called before beginning each line, so that they may be drawn with different colors. ...
...tx.beginPath
(); Examples Creating distinct paths This example creates two paths, each of which contains a single line. HTML <canvas id="canvas"></canvas> JavaScript The beginPath
() method is called before beginning each line, so that they may be drawn with different colors. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // First path ctx.beginPath
(); ctx.strokeStyle = 'blue'; ctx.moveTo(20, 20); ctx.lineTo(200, 20); ctx.stroke
(); // Second path ctx.beginPath
(); ctx.strokeStyle = 'green'; ctx.moveTo(20, 20); ctx.lineTo(120, 120); ctx.stroke
(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.beginPath' in that specification. Living Standard ...
CanvasRenderingContext2D.createRadialGradient() - Web APIs
The CanvasRenderingContext2D.createRadialGradient
() method of the Canvas 2D API creates a radial gradient using the size and coordinates of two circles. This method returns a CanvasGradient. To be applied to a shape, the gradient must first be assigned to the fillStyle or strokeStyle properties. Note: Gradient coordinates are global, i.e., relative to the current coordinate space. When applied to a shape, the coordinates are NOT relative to the shape's coordinates. Syntax CanvasGradient ctx.createRadialGradient(x0, y0, r0, x1, y1, r1); The createRadialGradient
() method is specified by six parameters, three defining the gradient's start circle, and three defining the end circle. Parameters x0 The x-axis coordinate of the start circle. y0 The y-axis coordinate of the start circ...
... finite. x1 The x-axis coordinate of the end circle. y1 The y-axis coordinate of the end circle. r1 The radius of the end circle. Must be non-negative and finite. Return value CanvasGradient A radial CanvasGradient initialized with the two specified circles. Examples Filling a rectangle with a radial gradient This example initializes a radial gradient using the createRadialGradient
() method. Three color stops between the gradient's two circles are then created. Finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangle. HTML <canvas id="canvas" width="200" height="200"></canvas> JavaScript var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); // Create a radial gradient // The inner circle is at x=110, y=9...
CanvasRenderingContext2D.drawWindow() - Web APIs
The contents of the window's viewport are rendered, ignoring viewport clipping and scrolling. This API cannot be used by Web content. It is synchronous, and as such can't be compatible with Fission. If you're using it from an extension, you should switch to tabs.captureTab. If you're writing chrome code, you probably want WindowGlobalParent.drawSnapshot from the parent process. Syntax void ctx.drawWindow(window, x, y, w, h, bgColor [, flags]); Parameters window The Window to render. x The x-axis coordinate of the window. ...
...ags]); Parameters window The Window to render. x The x-axis coordinate of the window. y The y-axis coordinate of the window. w The width of the window. h The height of the window. bgColor A DOMString that specifies the color the canvas is filled with before the window is rendered into it. This color may be transparent/translucent. It is given as a CSS color string (for example, rgb
() or rgba
()). Notes: If "rgba(0,0,0,0)" is used for the background color, the drawing will be transparent wherever the window is transparent. Top-level browsed documents are usually not transparent because the user's background-color preference is applied, but iframes are transparent if the page doesn't set a background. If an opaque color is used for the background color, rendering will b...
CanvasRenderingContext2D.getLineDash() - Web APIs
The getLineDash
() method of the Canvas 2D API's CanvasRenderingContext2D interface gets the current line dash pattern. Syntax ctx.getLineDash
(); Return value An Array of numbers that specify distances to alternately draw a line and a gap (in coordinate space units). If the number, when setting the elements, is odd, the elements of the array get copied and concatenated. For example, setting the line dash to [5, 15, 25] will result in getting back [5, 15, 25, 5, 15, 25]. Examples Getting the current line dash setting This example demonstrates the getLineDash
() method. HTML <canvas id="canvas"></canvas> JavaScript As set by setLineDash
(), strokes consist of lines that are 10 units wide, with spaces of 20 units in between each line. const canvas = document.getElementById('canvas');...
...ng the current line dash setting This example demonstrates the getLineDash
() method. HTML <canvas id="canvas"></canvas> JavaScript As set by setLineDash
(), strokes consist of lines that are 10 units wide, with spaces of 20 units in between each line. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.setLineDash([10, 20]); console.log(ctx.getLineDash
()); // [10, 20] // Draw a dashed line ctx.beginPath
(); ctx.moveTo(0, 50); ctx.lineTo(300, 50); ctx.stroke
(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.getLineDash' in that specification. Living Standard ...
CanvasRenderingContext2D.moveTo() - Web APIs
The CanvasRenderingContext2D.moveTo
() method of the Canvas 2D API begins a new sub-path at the point specified by the given (x, y) coordinates. Syntax void ctx.moveTo(x, y); Parameters x The x-axis (horizontal) coordinate of the point. y The y-axis (vertical) coordinate of the point. Examples Creating multiple sub-paths This example uses moveTo
() to create two sub-paths within a single path. Both sub-paths are then rendered with a single stroke
() call. HTML <canvas id="canvas"></canvas> JavaScript The first line begins at (50, 50) and ends at (200, 50). The second line begins at (50, 90) and ends at (280, 120). ...
...This example uses moveTo
() to create two sub-paths within a single path. Both sub-paths are then rendered with a single stroke
() call. HTML <canvas id="canvas"></canvas> JavaScript The first line begins at (50, 50) and ends at (200, 50). The second line begins at (50, 90) and ends at (280, 120). var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.beginPath
(); ctx.moveTo(50, 50); // Begin first sub-path ctx.lineTo(200, 50); ctx.moveTo(50, 90); // Begin second sub-path ctx.lineTo(280, 120); ctx.stroke
(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.moveTo' in that specification. Living Standard ...
CanvasRenderingContext2D.restore() - Web APIs
The CanvasRenderingContext2D.restore
() method of the Canvas 2D API restores the most recently saved canvas state by popping the top entry in the drawing state stack. If there is no saved state, this method does nothing. Fore more information about the drawing state, see CanvasRenderingContext2D.save
(). Syntax void ctx.restore
(); Examples Restoring a saved state This example uses the save
() method to save the default state and restore
() to restore it later, so that you are able to draw a rect with the default state later. ...
...Syntax void ctx.restore
(); Examples Restoring a saved state This example uses the save
() method to save the default state and restore
() to restore it later, so that you are able to draw a rect with the default state later. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Save the default state ctx.save
(); ctx.fillStyle = 'green'; ctx.fillRect(10, 10, 100, 100); // Restore the default state ctx.restore
(); ctx.fillRect(150, 40, 100, 100); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.restore' in that specification. Living Standard ...
CanvasRenderingContext2D.scale() - Web APIs
By default, one unit on the canvas is exactly one pixel. A scaling transformation modifies this behavior. For instance, a scaling factor of 0.5 results in a unit size of 0.5 pixels; shapes are thus drawn at half the normal size. Similarly, a scaling factor of 2.0 increases the unit size so that one unit becomes two pixels; shapes are thus drawn at twice the normal size. Syntax void ctx.scale(x, y); Parameters x Scaling factor in the horizontal direction. A negative value flips pixels across the vertical axis. A value of 1 results in no horizontal scaling. y Scaling factor in the vertical direction. ...
... // Non-scaled rectangle ctx.fillStyle = 'gray'; ctx.fillRect(10, 10, 8, 20); Result The scaled rectangle is red, and the non-scaled rectangle is gray. Flipping things horizontally or vertically You can use scale(-1, 1) to flip the context horizontally and scale(1, -1) to flip it vertically. In this example, the words "Hello world!" are flipped horizontally. Note that the call to fillText
() specifies a negative x coordinate. This is to adjust for the negative scaling factor: -280 * -1 becomes 280, and text is drawn leftwards from that point. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.scale(-1, 1); ctx.font = '48px serif'; ctx.fillText('Hello world!', -280, 90); ctx.setTransform(1, 0, ...
ChannelMergerNode() - Web APIs
Syntax var myNode = new ChannelMergerNode(context, options); Parameters context A BaseAudioContext representing the audio context you want the node to be associated with. options Optional A ChannelMergerOptions dictionary object defining the properties you want the ChannelMergerNode to have (also inherits parameters from the AudioNodeOptions dictionary): numberOfInputs: A number defining the number of inputs the ChannelMergerNode should have. If not specified, the default value used is 6. Return value A new ChannelMergerNode object instance. Exceptions InvalidStateError An option such as channelCount or channelCountMode has been given an invalid value. ...
...ters from the AudioNodeOptions dictionary): numberOfInputs: A number defining the number of inputs the ChannelMergerNode should have. If not specified, the default value used is 6. Return value A new ChannelMergerNode object instance. Exceptions InvalidStateError An option such as channelCount or channelCountMode has been given an invalid value. Example var ac = new AudioContext
(); var options = { numberOfInputs : 2 } var myMerger = new ChannelMergerNode(ac, options); Specifications Specification Status Comment Web Audio APIThe definition of 'ChannelMergerNode' in that specification. Working Draft ...
ChannelSplitterNode.ChannelSplitterNode() - Web APIs
Syntax var splitter = new ChannelSpitterNode(context, options); Parameters Inherits parameters from the AudioNodeOptions dictionary. context A BaseAudioContext representing the audio context you want the node to be associated with. options Optional A ChannelSplitterOptions dictionary object defining the properties you want the ChannelSplitterNode to have (It also inherits the options defined in the AudioNodeOptions dictionary): numberOfOutputs: A number defining the number of inputs the ChannelSplitterNode should have. ...
...dictionary object defining the properties you want the ChannelSplitterNode to have (It also inherits the options defined in the AudioNodeOptions dictionary): numberOfOutputs: A number defining the number of inputs the ChannelSplitterNode should have. If not specified, the default value used is 6. Return value A new ChannelSplitterNode object instance. Example var ac = new AudioContext
(); var options = { numberOfOutputs : 2 } var mySplitter = new ChannelSplitterNode(ac, options); Specifications Specification Status Comment Web Audio APIThe definition of 'ChannelSplitterNode' in that specification. Working Draft ...
Clients.claim() - Web APIs
The claim
() method of the Clients interface allows an active service worker to set itself as the controller for all clients within its scope. 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. Return value A Promise that resolves to undefined. ...
...n'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. 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. ...
Clipboard.readText() - Web APIs
The Clipboard interface's readText
() method returns a Promise which resolves with a copy of the textual contents of the system clipboard.. The "clipboard-read" permission of the Permissions API must be granted before you can read data from the clipboard. Syntax var promise = navigator.clipboard.readText
() Parameters None. Return value A Promise that resolves with a DOMString containing the textual contents of the clipboard. Returns an empty string if the clipboard is empty, does not contain text, or does not include a textual representation among the DataTransfer objects representing the clipboard's contents. To read non-text contents from the clipboard, use the read
() method instead. You can write text to the clipboard using writeText
(). Example This example retrieves the textual ...
...s not include a textual representation among the DataTransfer objects representing the clipboard's contents. To read non-text contents from the clipboard, use the read
() method instead. You can write text to the clipboard using writeText
(). Example This example retrieves the textual contents of the clipboard and inserts the returned text into an element's contents. navigator.clipboard.readText
().then( clipText => document.getElementById("outbox").innerText = clipText); Specifications Specification Status Comment Clipboard API and eventsThe definition of 'readText
()' in that specification. Working Draft Initial definition. ...
Clipboard.writeText() - Web APIs
The "clipboard-write" permission of the Permissions API, is granted automatically to pages when they are in the active tab. Note: Browser support for the asynchronous clipboard APIs is still in the process of being implemented. Be sure to check the compatibility table as well as Clipboard availability in Clipboard for more information. Syntax var promise = navigator.clipboard.writeText(newClipText) Parameters newClipText The DOMString to be written to the clipboard. Return value A Promise which is resolved once the clipboard's contents have been updated. ...
... newClipText The DOMString to be written to the clipboard. Return value A Promise which is resolved once the clipboard's contents have been updated. The promise is rejected if the caller does not have permission to write to the clipboard. Example This example sets the clipboard's contents to the string "<empty clipboard>". navigator.clipboard.writeText("<empty clipboard>").then(function
() { /* clipboard successfully set */ }, function
() { /* clipboard write failed */ }); Specifications Specification Status Comment Clipboard API and eventsThe definition of 'writeText
()' in that specification. Working Draft Initial definition. ...
ClipboardEvent() - Web APIs
type Is a DOMString representing the name of the type of the ClipboardEvent. It is case-sensitive and can be: 'copy', 'cut', or 'paste'. options Optional Options are as follows: clipboardData: A DataTransfer containing the data concerned by the clipboard event. dataType : A DOMString containing the MIME-type of the data contained in the data argument. ...
... Working Draft Initial definition. ...
CloseEvent() - Web APIs
Syntax var event = new CloseEvent(typeArg, closeEventInit); Values typeArg Is a DOMString representing the name of the event. closeEventInit Optional Is a CloseEventInit dictionary, having the following fields: "wasClean", optional and defaulting to false, of type long, indicates if the connection has been closed cleanly or not. "code", optional and defaulting to 0, of type unsigned short, that is the connection close code sent by the server. "reason", optional and defaulting to '', of type DOMString, that is a human-readable reason why the server closed the connection. The CloseEventInit dictionary also accepts fields from the EventInit dictionary. ...
...hat is the connection close code sent by the server. "reason", optional and defaulting to '', of type DOMString, that is a human-readable reason why the server closed the connection. The CloseEventInit dictionary also accepts fields from the EventInit dictionary. Specifications Specification Status Comment HTML Living StandardThe definition of 'CloseEvent
()' in that specification. Living Standard Initial definition. ...
CompositionEvent.CompositionEvent() - Web APIs
The CompositionEvent
() constructor creates a new CompositionEvent object instance. Syntax const myEvent = new CompositionEvent(typeArg [, CompositionEventInit]) Values typeArg Is a DOMString representing the name of the event. CompositionEventInit Optional A CompositionEventInit dictionary object, which can contain the following members: data Initializes the data attribute of the CompositionEvent object to the characters generated by the IME composition. Note: The CompositionEventInit dictionary inherits from the UIEventInit dictionary, so can also accept members defined on there. ...
... Obsolete Initial definition. ...
CompositionEvent.initCompositionEvent() - Web APIs
Syntax compositionEventInstance.initCompositionEvent(typeArg, canBubbleArg, cancelableArg, viewArg, dataArg, localeArg) Parameters typeArg A DOMString representing the type of composition event; this will be one of compositionstart, compositionupdate, or compositionend. canBubbleArg A Boolean specifying whether or not the event can bubble. cancelableArg A Boolean shether or not the event can be canceled. viewArg The Window object from which the event was generated. dataArg A DOMString representing the value of the data attribute. localeArg A DOMString representing the value of the locale attribute. ...
...led. viewArg The Window object from which the event was generated. dataArg A DOMString representing the value of the data attribute. localeArg A DOMString representing the value of the locale attribute. Return value Void. Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'initCompositionEvent
()' in that specification. Obsolete Initial definition. ...
console.assert() - Web APIs
If the assertion is true, nothing happens. Note: This feature is available in Web Workers. Syntax console.assert(assertion, obj1 [, obj2, ..., objN]); console.assert(assertion, msg [, subst1, ..., substN]); // C-like message formatting Parameters assertion Any boolean expression. If the assertion is false, the message is written to the console. obj1 ... objN A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. msg A JavaScript string containing zero or more substitution strings. subst1 ... substN JavaScript objects with which to replace substitution strings within msg. ...
...e browsers // (e.g. Firefox v60.0.2): // Assertion failed: the word is foo // incorrect output in some browsers // (e.g. Chrome v67.0.3396.87): // Assertion failed: the word is %s foo See Outputting text to the console in the documentation of console for further details. Specifications Specification Status Comment Console APIThe definition of 'console.assert
()' in that specification. Living Standard Initial definition ...
console.debug() - Web APIs
The message is only displayed to the user if the console is configured to display debug output. Note: This feature is available in Web Workers. Syntax console.debug(obj1 [, obj2, ..., objN]); console.debug(msg [, subst1, ..., substN]); Parameters obj1 ... objN A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console. msg A JavaScript string containing zero or more substitution strings, which are replaced with subst1 through substN in consecutive order. subst1 ... substN JavaScript objects with which to replace substitution strings within msg. ...
...lace substitution strings within msg. This gives you additional control over the format of the output. See Using string substitutions in console for a description of how substitutions work. See Outputting text to the console in the documentation of the console object for details. Specifications Specification Status Comment Console APIThe definition of 'console.debug
()' in that specification. Living Standard Initial definition ...
Console.info() - Web APIs
In Firefox, a small "i" icon is displayed next to these items in the Web Console's log. Note: This feature is available in Web Workers. Syntax console.info(obj1 [, obj2, ..., objN]); console.info(msg [, subst1, ..., substN]); Parameters obj1 ... objN A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. msg A JavaScript string containing zero or more substitution strings. subst1 ... substN JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. ...
...taining zero or more substitution strings. subst1 ... substN JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. See Outputting text to the console in the documentation of console for details. Specifications Specification Status Comment Console APIThe definition of 'console.info
()' in that specification. Living Standard Initial definition ...
Console.table() - Web APIs
jane, emily]); Note that if the array contains objects, then the columns are labeled with the property name. // an object whose properties are objects var family = {}; family.mother = new Person("Jane", "Smith"); family.father = new Person("John", "Smith"); family.daughter = new Person("Emily", "Smith"); console.table(family); Restricting the columns displayed By default, console.table
() lists all elements in each row. You can use the optional columns parameter to select a subset of columns to display: // an array of objects, logging only firstName function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } var john = new Person("John", "Smith"); var jane = new Person("Jane", "Doe"); var emily = new Person("Emily", "Jones"); console.tabl...
...an sort the table by a particular column by clicking on that column's label. Syntax console.table(data [, columns]); Parameters data The data to display. This must be either an array or an object. columns An array containing the names of columns to include in the output. Specifications Specification Status Comment Console APIThe definition of 'console.table
()' in that specification. Living Standard Initial definition ...
DOMTokenList.item() - Web APIs
Syntax tokenList.item(index) Parameters index A DOMString representing the index of the item you want to return. Return value A DOMString representing the returned item. It returns null if the number is greater than or equal to the length of the list. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then retrieve the last item in the list using item(tokenList.length - 1), and write it into the <span>'s Node.textContent. ...
...gth - 1), and write it into the <span>'s Node.textContent. First, the HTML: <span class="a b c"></span> Now the JavaScript: let span = document.querySelector("span"); let classes = span.classList; let item = classes.item(classes.length-1); span.textContent = item; The output looks like this: Specifications Specification Status Comment DOMThe definition of 'item
()' in that specification. Living Standard Initial definition ...
DOMTokenList.keys() - Web APIs
The keys
() method of the DOMTokenList interface returns an iterator allowing to go through all keys contained in this object. The keys are of type unsigned integer. Syntax tokenList.keys
(); Parameters None. Return value Returns an iterator. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We when retrieve an iterator containing the keys using values
(), then iterate through those keys using a for ... of loop, writing each one to the <span>'s Node.textContent. ...
...<span> element as a DOMTokenList using Element.classList. We when retrieve an iterator containing the keys using values
(), then iterate through those keys using a for ... of loop, writing each one to the <span>'s Node.textContent. First, the HTML: <span class="a b c"></span> Now the JavaScript: var span = document.querySelector("span"); var classes = span.classList; var iterator = classes.keys
(); for(var value of iterator) { span.textContent += value + ' ++ '; } The output looks like this: Specifications Specification Status Comment DOMThe definition of 'keys
() (as iterable<Node>)' in that specification. Living Standard Initial definition ...
DOMTokenList.remove() - Web APIs
Syntax tokenList.remove(token1[, token2[, ...tokenN]]); Parameters tokenN A DOMString representing the token you want to remove from the list. If the string is not in the list, no error is thrown, and nothing happens. Return value undefined Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then remove a token from the list, and write the list into the <span>'s Node.textContent. ...
... remove multiple classes at once, you can supply multiple tokens. The order you supply the tokens doesn't have to match the order they appear in the list: let span2 = document.getElementsByTagName("span")[0] let classes2 = span.classList; classes2.remove("c", "b"); span2.textContent = classes; Specifications Specification Status Comment DOMThe definition of 'remove
()' in that specification. Living Standard Initial definition ...
DOMTokenList.toggle() - Web APIs
If token doesn't exist it's added and the function returns true. Syntax tokenList.toggle(token [, force]); Parameters token A DOMString representing the token you want to toggle. force Optional A Boolean that, if included, turns the toggle into a one way-only operation. If set to false, then token will only be removed, but not added. If set to true, then token will only be added, but not removed. Return value A Boolean indicating whether token is in the list after the call. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. ...
...ng example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then replace a token in the list, and write the list into the <span>'s Node.textContent. First, the HTML: <span class="a b">classList is 'a b'</span> Now the JavaScript: let span = document.querySelector("span"); let classes = span.classList; span.addEventListener('click', function
() { let result = classes.toggle("c"); if (result) { span.textContent = `'c' added; classList is now "${classes}".`; } else { span.textContent = `'c' removed; classList is now "${classes}".`; } }) The output looks like this: Specifications Specification Status Comment DOMThe definition of 'toggle
()' in that specification. Living Standard Initi...
DOMTokenList.values() - Web APIs
The values
() method of the DOMTokenList interface returns an iterator allowing developers to go through all values contained in the DOMTokenList. The individual values are DOMString objects. Syntax tokenList.values
(); Parameters None. Return value Returns an iterator. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We when retrieve an iterator containing the values using values
(), then iterate through those values using a for ... of loop, writing each one to the <span>'s Node.textContent. ...
... element as a DOMTokenList using Element.classList. We when retrieve an iterator containing the values using values
(), then iterate through those values using a for ... of loop, writing each one to the <span>'s Node.textContent. First, the HTML: <span class="a b c"></span> Now the JavaScript: var span = document.querySelector("span"); var classes = span.classList; var iterator = classes.values
(); for(var value of iterator) { span.textContent += value + ' ++ '; } The output looks like this: Specifications Specification Status Comment DOMThe definition of 'values
() (as iterable<Node>)' in that specification. Living Standard Initial definition ...
DataTransfer.mozClearDataAt() - Web APIs
The index must be in the range from zero to the number of items minus one. If the format argument is not provided, then the data associated with all formats is removed. If the format is not found, then this method has no effect. If the last format for the item is removed, the entire item is removed, reducing mozItemCount by one. Removing the last format for a particular index removes that item entirely, shifting the remaining items down and changing their indices. Note: This method is Gecko-specific. ...
...ning items down and changing their indices. Note: This method is Gecko-specific. Syntax void dataTransfer.mozClearDataAt([type], index); Arguments type A string representing the type of the drag data to remove from the drag data object. index A unsigned long representing the index of the data to remove. Return value void Example This example shows the use of the mozClearDataAt
() method in a dragend event handler. function dragend_handler(event) { var dt = event.dataTransfer; // Remove a text/html item dt.mozClearDataAt("text/html", 1); } Specifications This method is not defined in any Web standard. ...
DataTransfer.mozSetDataAt() - Web APIs
Data should be added in order of preference, with the most specific format added first and the least specific format added last. If data of the given format already exists, it is replaced in the same position as the old data. ...
...cko-specific. Syntax void dataTransfer.mozSetDataAt([type], data, index); Arguments type A string representing the type of the drag data to add to the drag data object. data A nsIVariant representing the data to add to the drag data object. index A unsigned long representing the index of the data to add. Return value void Example This example shows the use of the mozSetDataAt
() method in a dragstart handler. function dragstart_handler(event) { var dt = event.dataTransfer; var idx = dt.mozItemCount; // Add two new items to the drag transfer if (idx >= 0) { dt.mozSetDataAt("text/uri-list","http://www.example.com/", idx); dt.mozSetDataAt("text/html", "Hello World", idx+1); } } Specifications This method is not defined in any Web standard. ...
DedicatedWorkerGlobalScope.postMessage() - Web APIs
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 main scope that spawned the worker can send back information to the thread that spawned it using the Worker.postMessage method. 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. This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references. ...
... 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
()' in that specification. Living Standard ...
Document.clear() - Web APIs
The Document.clear
() method clears the whole specified document in early (pre-1.0) versions of Mozilla. In recent versions of Mozilla-based applications, as well as in Internet Explorer and Netscape 4, this method does nothing. ...
... The Document.clear
() method clears the whole specified document in early (pre-1.0) versions of Mozilla. In recent versions of Mozilla-based applications, as well as in Internet Explorer and Netscape 4, this method does nothing. ...
Document.createCDATASection() - Web APIs
createCDATASection
() creates a new CDATA section node, and returns it. Syntax var CDATASectionNode = document.createCDATASection(data); CDATASectionNode is a CDATA Section node. data is a string containing the data to be added to the CDATA Section. Example var docu = new DOMParser
().parseFromString('<xml></xml>', 'application/xml') var cdata = docu.createCDATASection('Some <CDATA> data & then some'); docu.getElementsByTagName('xml')[0].appendChild(cdata); alert(new XMLSerializer
().serializeToString(docu)); // Displays: <xml><![CDATA[Some <CDATA> data & then some]]></xml> Notes This will only work with XML, not HTML documents (as HTML documents do not support CDATA sections); attempting it on an HTML document will throw NOT_SUPPORTED_ERR. Will throw a NS_ERROR_DOM_INVALID_...
... with XML, not HTML documents (as HTML documents do not support CDATA sections); attempting it on an HTML document will throw NOT_SUPPORTED_ERR. Will throw a NS_ERROR_DOM_INVALID_CHARACTER_ERR exception if one tries to submit the closing CDATA sequence ("]]>") as part of the data, so unescaped user-provided data cannot be safely used without with this method getting this exception (createTextNode
() can often be used in its place). Specifications Specification Status Comment DOMThe definition of 'document.createCDATASection' in that specification. Living Standard ...
Document.createNodeIterator() - Web APIs
in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree. NodeFilter.SHOW_PROCESSING_INSTRUCTION 64 Shows ProcessingInstruction nodes. NodeFilter.SHOW_TEXT 4 Shows Text nodes. filter Optional An object implementing the NodeFilter interface. Its acceptNode
() method will be called for each node in the subtree based at root which is accepted as included by the whatToShow flag to determine whether or not to include it in the list of iterable nodes (a simple callback function may also be used instead). The method should return one of NodeFilter.FILTER_ACCEPT, NodeFilter.FILTER_REJECT, or NodeFilter.FILTER_SKIP. See the Example. Note: Prior to Gecko 12.
... and has therefore been removed. This parameter indicated whether or not the children of entity reference nodes were visible to the iterator. Since such nodes were never created in browsers, this paramater had no effect. Example const nodeIterator = document.createNodeIterator( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode(node) { return node.nodeName.toLowerCase
() === 'p' ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT; } } ); const pars = []; let currentNode; while (currentNode = nodeIterator.nextNode
()) { pars.push(currentNode); } Specifications Specification Status Comment DOMThe definition of 'document.createNodeIterator' in that specification. Living Standard ...
Document.createRange() - Web APIs
Specifications Specification Status Comment DOMThe definition of 'document.createRange' in that specification. ...
... Specifications Specification Status Comment DOMThe definition of 'document.createRange' in that specification. ...
Document.createTouchList() - Web APIs
Note: Before Gecko 25.0, this method was defined on the DocumentTouch mixin. The Document.createTouchList
() method creates and returns a new TouchList object. Syntax var list = DocumentTouch.createTouchList([touch1 [, touch2 [, ...]]]); Parameters touches Zero or more Touch objects. Note: Firefox also accepts an array of Touch objects. Return value list A TouchList object containing the Touch objects specified by the touches parameter. Example This example illustrates using the Document.createTouchList
() method to create TouchList objects. In following code snippet, some Touch objects are created for the target element and those touch points are then used to create some TouchList objects. var target = document.getElementById("target"); // Create some touch points va...
...s are created for the target element and those touch points are then used to create some TouchList objects. var target = document.getElementById("target"); // Create some touch points var touch1 = document.createTouch(window, target, 1, 15, 20, 35, 40); var touch2 = document.createTouch(window, target, 2, 25, 30, 45, 50); // Create an empty TouchList objects var list0 = document.createTouchList
(); // Create a TouchList with only one Touch object var list1 = document.createTouchList(touch1); // Create a list with two Touch objects var list2 = document.createTouchList(touch1, touch2); Specifications Specification Status Comment Touch EventsThe definition of 'Document.createTouchList
()' in that specification. Recommendation Initial definition. ...
Document.getAnimations() - Web APIs
The getAnimations
() method of the Document interface returns an array of all Animation objects currently in effect whose target elements are descendants of the document. This array includes CSS Animations, CSS Transitions, and Web Animations. Syntax var allAnimations = Document.getAnimations
(); Parameters None. Return value An Array of Animation objects, each representing one animation currently associated with elements which are descendants of the Document on which it's called. Examples The following code snippet will slow down all animations on a page by halving their Animation.playbackRate. ...
...imations. Syntax var allAnimations = Document.getAnimations
(); Parameters None. Return value An Array of Animation objects, each representing one animation currently associated with elements which are descendants of the Document on which it's called. Examples The following code snippet will slow down all animations on a page by halving their Animation.playbackRate. document.getAnimations
().forEach( function (animation) { animation.playbackRate *= .5; } ); Specifications Specification Status Comment Web AnimationsThe definition of 'document.getAnimations
()' in that specification. Working Draft ...
Document.hasStorageAccess() - Web APIs
The hasStorageAccess
() method of the Document interface returns a Promise that resolves with a boolean value indicating whether the document has access to its first-party storage. See Storage Access API for more information. Syntax var promise = document.hasStorageAccess
(); Parameters None. Return value A Promise that resolves with a boolean value indicating whether the document has access to its first-party storage. If the promise gets resolved and a user gesture event was being processed when the function was originally called, the resolve handler will run as if a user gesture was being processed, so it will be able to call APIs that require user activation. ...
... Promise that resolves with a boolean value indicating whether the document has access to its first-party storage. If the promise gets resolved and a user gesture event was being processed when the function was originally called, the resolve handler will run as if a user gesture was being processed, so it will be able to call APIs that require user activation. Examples document.hasStorageAccess
().then(hasAccess => { if (hasAccess) { // storage access has been granted already. } else { // storage access hasn't been granted already; // you may want to call requestStorageAccess
(). } }); Specifications The API is currently only at the proposal stage -- the standardization process has yet to begin. You can currently find specification details of the API at Apple's Introduci...
HTMLCanvasElement.getContext() - Web APIs
Later calls to this method on the same canvas element return the same drawing context instance as was returned the last time the method was invoked with the same contextType argument. To get a different drawing context object you need to pass a different contextType or call the method on a different canvas element. Syntax var ctx = canvas.getContext(contextType); var ctx = canvas.getContext(contextType, contextAttributes); Parameters contextType Is a DOMString containing the context identifier defining the drawing context associated to the canvas. ...
...ntent and images. desynchronized: Boolean that hints the user agent to reduce the latency by desynchronizing the canvas paint cycle from the event loop (Gecko only) willReadFrequently: Boolean that indicates whether or not a lot of read-back operations are planned. This will force the use of a software (instead of hardware accelerated) 2D canvas and can save memory when calling getImageData
() frequently. This option is only available, if the flag gfx.canvas.willReadFrequently.enable is set to true (which, by default, is only the case for B2G/Firefox OS). (Blink only) storage: String that indicates which storage is used ("persistent" by default). WebGL context attributes: alpha: Boolean that indicates if the canvas contains an alpha buffer. desynchronized: Boolean that hi...
HTMLElement.forceSpellCheck() - Web APIs
The forceSpellCheck
() method of the HTMLElement interface forces a spelling and grammar check on HTML elements, even if the user has not focused on the elements. This method overrides user agent behavior. The specific user interface of the check, for example whether red underlining appears, is determined by the user agent. ...
... The forceSpellCheck
() method of the HTMLElement interface forces a spelling and grammar check on HTML elements, even if the user has not focused on the elements. This method overrides user agent behavior. The specific user interface of the check, for example whether red underlining appears, is determined by the user agent. ...
HTMLFormControlsCollection.namedItem() - Web APIs
Like that one, in JavaScript, using the array bracket syntax with a String, like collection["value"] is equivalent to collection.namedItem("value"). Syntax var item = collection.namedItem(str); var item = collection[str]; Parameters str is a DOMString Return value item is a RadioNodeList , Element, or null. ...
...value item is a RadioNodeList , Element, or null. Example HTML <form> <input id="my-form-control" type="textarea"> </form> JavaScript // Returns the HTMLInputElement representing #my-form-control elem1 = document.forms[0]['my-form-control']; Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormControlsCollection.namedItem
()' in that specification. Living Standard HTML5The definition of 'HTMLFormControlsCollection' in that specification. Recommendation In this snapshot of HTML Living Standard, the HTMLFormControlsCollections is defined for the first time. ...
HTMLFormElement.submit() - Web APIs
The HTMLFormElement.submit
() method submits a given <form>. This method is similar, but not identical to, activating a form's submit <button>. When invoking this method directly, however: No submit event is raised. In particular, the form's onsubmit event handler is not run. Constraint validation is not triggered. The HTMLFormElement.requestSubmit
() method is identical to activating a form's submit <button> and does not have these differences. If a form control (such as a submit button) has a name or id of submit, this method will mask the form's submit method. <input> with attribute type="submit" will not be submitted with the form when using HTMLFormElement.submit
(), but it would be submitted when you do it with original HTML form submit. ...
...g a form's submit <button> and does not have these differences. If a form control (such as a submit button) has a name or id of submit, this method will mask the form's submit method. <input> with attribute type="submit" will not be submitted with the form when using HTMLFormElement.submit
(), but it would be submitted when you do it with original HTML form submit. Syntax HTMLFormElement.submit
() Example document.forms["myform"].submit
(); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement: submit' in that specification. Living Standard ...
Image() - Web APIs
Syntax var htmlImageElement = new Image(width, height); Parameters width The width of the image (i.e., the value for the width attribute). height The height of the image (i.e., the value for the height attribute). Usage note The entire bitmap is loaded regardless of the sizes specified in the constructor. The size specified in the constructor is reflected through the properties HTMLImageElement.width and HTMLImageElement.height of the resulting instance. ...
...irs of properties have the same values. Examples var myImage = new Image(100, 200); myImage.src = 'picture.jpg'; document.body.appendChild(myImage); This would be the equivalent of defining the following HTML tag inside the <body>: <img width="100" height="200" src="picture.jpg"> Specifications Specification Status Comment HTML Living StandardThe definition of 'Image
()' in that specification. Living Standard ...
HTMLInputElement.select() - Web APIs
The HTMLInputElement.select
() method selects all the text in a <textarea> element or in an <input> element that includes a text field. Syntax element.select
(); Example Click the button in this example to select all the text in the <input> element. HTML <input type="text" id="text-box" size="20" value="Hello world!"> <button onclick="selectText
()">Select text</button> JavaScript function selectText
() { const input = document.getElementById('text-box'); input.focus
(); input.select
(); } Result Notes Calling element.select
() will not necessarily focus the input, so it is often used with HTMLElement.focus
(). ...
...xt
()">Select text</button> JavaScript function selectText
() { const input = document.getElementById('text-box'); input.focus
(); input.select
(); } Result Notes Calling element.select
() will not necessarily focus the input, so it is often used with HTMLElement.focus
(). In browsers where it is not supported, it is possible to replace it with a call to HTMLInputElement.setSelectionRange
() with parameters 0 and the input's value length: <input onClick="this.select
();" value="Sample Text" /> <!-- equivalent to --> <input onClick="this.setSelectionRange(0, this.value.length);" value="Sample Text" /> Specifications Specification Status Comment HTML Living StandardThe definition of 'select' in that specification. Living Standard ...
HTMLMediaElement.captureStream() - Web APIs
Return value A MediaStream object which can be used as a source for audio and/or video data by other media processing code, or as a source for WebRTC. Example In this example, an event handler is established so that clicking a button starts capturing the contents of a media element with the ID "playback" into a MediaStream. ...
...xample, an event handler is established so that clicking a button starts capturing the contents of a media element with the ID "playback" into a MediaStream. The stream can then be used for other purposes--like a source for streaming over WebRTC, to allow sharing prerecorded videos with another person during a video call. document.querySelector('.playAndRecord').addEventListener('click', function
() { var playbackElement = document.getElementById("playback"); var captureStream = playbackElement.captureStream
(); playbackElement.play
(); }); See Recording a media element for a longer and more intricate example and explanation. Specifications Specification Status Comment Media Capture from DOM ElementsThe definition of 'captureStream
()' in that specification. ...
HTMLMediaElement.seekToNextFrame() - Web APIs
This non-standard method is part of an experimentation process around support for non-real-time access to media for tasks including filtering, editing, and so forth. You should not use this method in production code, because its implementation may change--or be removed outright--without notice. You are, however, invited to experiment with it. This method lets you access frames of video media without the media being performed in real time. This also lets you access media using frames as a seek unit rather than timecodes (albeit only by seeking one frame at a time until you get to the frame you want). ...
...tion is complete. In addition, a seeked event is sent to let interested parties know that a seek has taken place. If the seek fails because the media is already at the last frame, a seeked event occurs, followed immediately by an ended event. If there is no video on the media element, or the media isn't seekable, nothing happens. Syntax var seekCompletePromise = HTMLMediaElement.seekToNextFrame
(); HTMLMediaElement.seekToNextFrame
(); Return value A Promise which is fulfilled once the seek operation has completed. Firefox 49 returns undefined instead of a promise, and performs the seek operation synchronously. Specifications Not part of any specification. ...
HTMLMediaElement.setMediaKeys() - Web APIs
Recommendation Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
...tax var Promise = HTMLMediaElement.setMediaKeys(mediaKeys); Parameters mediaKeys A reference to a MediaKeys object that the HTMLMediaElement can use for decryption of media data during playback. Returns A Promise that resolves to the passed instance of MediaKeys. Specifications Specification Status Comment Encrypted Media ExtensionsThe definition of 'setMediaKeys
()' in that specification. Recommendation Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox fo...
HTMLMediaElement.setSinkId() - Web APIs
The HTMLMediaElement.setSinkId
() method sets the ID of the audio device to use for output and returns a Promise. This only works when the application is authorized to use the specified device. Syntax HTMLMediaElement.setSinkId(sinkId).then(function
() { ... }) Returns A Promise that resolves to undefined. Parameters sinkId The MediaDeviceInfo.deviceId of the audio output device. ...
...vice. Syntax HTMLMediaElement.setSinkId(sinkId).then(function
() { ... }) Returns A Promise that resolves to undefined. Parameters sinkId The MediaDeviceInfo.deviceId of the audio output device. Exceptions Exception Explanation DOMException No permission to use the requested device Examples const devices = await navigator.mediaDevices.enumerateDevices
(); const audioDevices = devices.filter(device => device.kind === 'audiooutput'); const audio = document.createElement('audio'); await audio.setSinkId(audioDevices[0].deviceId); console.log('Audio is being played on ' + audio.sinkId); Specifications Specification Status Comment Audio Output Devices APIThe definition of 'sinkId' in that specification. Candidate Recommend...
HTMLSelectElement.namedItem() - Web APIs
In JavaScript, using the array bracket syntax with a String, like selectElt["value"] is equivalent to selectElt.namedItem("value"). Syntax var item = collection.namedItem(str); var item = collection[str]; Parameters str is a DOMString. Return value item is a HTMLOptionElement. ...
...ent. Example HTML <form> <select id="myFormControl"> <option id="o1">Opt 1</option> <option id="o2">Opt 2</option> </select> </form> JavaScript elem1 = document.forms[0]['myFormControl']['o1']; // Returns the HTMLOptionElement representing #o1 Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLSelectElement.namedItem
()' in that specification. Living Standard No change since the latest snapshot, HTML5. HTML5The definition of 'HTMLSelectElement.namedItem
()' in that specification. Recommendation Initial definition, snapshot of HTML Living Standard ...
HTMLSlotElement.assignedElements() - Web APIs
If the flatten option is set to true, it also returns the assigned elements of any other slots that are descendants of this slot. If no assigned nodes are found, it returns the slot's fallback content. Syntax var assignedElements = HTMLSlotElement.assignedElements(options) Parameters options Optional An object that sets options for the nodes to be returned. The available options are: flatten: A Boolean indicating whether to return the assigned elements of any available child <slot> elements (true) or not (false). Defaults to false. Return value An array of elements. ...
...return the assigned elements of any available child <slot> elements (true) or not (false). Defaults to false. Return value An array of elements. Examples let slots = this.shadowRoot.querySelector('slot'); let elements = slots.assignedElements({flatten: true}); Specifications Specification Status Comment HTML Living StandardThe definition of 'assignedElements
()' in that specification. Living Standard 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 fo...
HTMLSlotElement.assignedNodes() - Web APIs
If no assigned nodes are found, it returns the slot's fallback content. Syntax var assignedNodes = HTMLSlotElement.assignedNodes(options) Parameters options Optional An object that sets options for the nodes to be returned. The available options are: flatten: A Boolean indicating whether to return the assigned nodes of any available child <slot> elements (true) or not (false). Defaults to false. Return value An array of nodes. Examples The following snippet is taken from our slotchange example (see it live also). ...
...icating whether to return the assigned nodes of any available child <slot> elements (true) or not (false). Defaults to false. Return value An array of nodes. Examples The following snippet is taken from our slotchange example (see it live also). let slots = this.shadowRoot.querySelectorAll('slot'); slots[1].addEventListener('slotchange', function(e) { let nodes = slots[1].assignedNodes
(); console.log('Element in Slot "' + slots[1].name + '" changed to "' + nodes[0].outerHTML + '".'); }); Here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template -- which is the one that keeps having its contents changed in the example. Every time the element inserted in the slot changes, we log a report to the console saying which slot has c...
HTMLTableElement.createCaption() - Web APIs
The HTMLTableElement.createCaption
() method returns the <caption> element associated with a given <table>. If no <caption> element exists on the table, this method creates it, and then returns it. Note: If no caption exists, createCaption
() inserts a new caption directly into the table. The caption does not need to be added separately as would be the case if Document.createElement
() had been used to create the new <caption> element. Syntax HTMLTableElement = table.createCaption
(); Return value HTMLTableCaptionElement Example This example uses JavaScript to add a caption to a table that initially lacks one. HTML <table> <tr><td>Cell 1.1</td><td>Cell 1.2</td><td>Cell 1.3</td></tr> <tr><td>Cell 2.1</td><td>Cell 2.2</td><td>Cell 2.3</td></tr> </table> JavaScript let table = doc...
...t = table.createCaption
(); Return value HTMLTableCaptionElement Example This example uses JavaScript to add a caption to a table that initially lacks one. HTML <table> <tr><td>Cell 1.1</td><td>Cell 1.2</td><td>Cell 1.3</td></tr> <tr><td>Cell 2.1</td><td>Cell 2.2</td><td>Cell 2.3</td></tr> </table> JavaScript let table = document.querySelector('table'); let caption = table.createCaption
(); caption.textContent = 'This caption was created by JavaScript!'; Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement: createCaption' in that specification. Living Standard ...
Headers() - Web APIs
The Headers
() constructor creates a new Headers object. Syntax var myHeaders = new Headers(init); Parameters init Optional An object containing any HTTP headers that you want to pre-populate your Headers object with. This can be a simple object literal with ByteString values; or an existing Headers object. In the last case, the new Headers object inherits its data from the existing Headers object. Example Creating an empty Headers object is simple: var myHeaders = new Headers
(); // Currently empty You could add a header to this using Headers.append: myHeaders.append('Content-Type', 'image/jpeg'); myHeaders.get('Content-Type'); // Returns 'image/jpeg' Or you can add the headers you want as the Headers object is created. In the following snippet we create a new Headers object, ...
... Living Standard ...
Headers.has() - Web APIs
The has
() method of the Headers interface returns a boolean stating whether a Headers object contains a certain header. For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names. Syntax myHeaders.has(name); Parameters name The name of the HTTP header you want to test for. If the given name is not a valid HTTP header name, this method throws a TypeError. Returns A Boolean. ...
...rolled by the user agent. These headers include the forbidden header names and forbidden response header names. Syntax myHeaders.has(name); Parameters name The name of the HTTP header you want to test for. If the given name is not a valid HTTP header name, this method throws a TypeError. Returns A Boolean. Example Creating an empty Headers object is simple: var myHeaders = new Headers
(); // Currently empty You could add a header to this using Headers.append, then test for the existence of it using has
(): myHeaders.append('Content-Type', 'image/jpeg'); myHeaders.has('Content-Type'); // Returns true myHeaders.has('Accept-Encoding'); // Returns false Specifications Specification Status Comment FetchThe definition of 'has
()' in that specification. Liv...
History.back() - Web APIs
The History.back
() method causes the browser to move back one page in the session history. It has the same effect as calling history.go(-1). If there is no previous page, this method call does nothing. This method is asynchronous. Add a listener for the popstate event in order to determine when the navigation has completed. Syntax history.back
() Examples The following short example causes a button on the page to navigate back one entry in the session history. HTML <button id="go-back">Go back!</button> JavaScript document.getElementById('go-back').addEventListener('click',
() => { history.back
(); }); Specifications Specification Status Comment HTML Living StandardThe definition of 'History.back
()' in that specification. Living Standard No change fr...
... Recommendation Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
IDBDatabase.close() - Web APIs
The close
() method of the IDBDatabase interface returns immediately and closes the connection in a separate thread. The connection is not actually closed until all transactions created using this connection are complete. No new transactions can be created for this connection once this method is called. Methods that create transactions throw an exception if a closing operation is pending. Note: This feature is available in Web Workers. Syntax IDBDatabase.close
(); Example // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); // opening a database. // Create event handlers for both success and failure of DBOpenRequest.onerror = function(event) { note.innerHTML += "<li>Error loading database.</li>"; }; DBOpenRequest.onsuccess = function(event) { no...
...eate event handlers for both success and failure of DBOpenRequest.onerror = function(event) { note.innerHTML += "<li>Error loading database.</li>"; }; DBOpenRequest.onsuccess = function(event) { note.innerHTML += "<li>Database initialised.</li>"; // store the result of opening the database in the db variable. db = DBOpenRequest.result; // now let"s close the database again! db.close
(); }; Specification Specification Status Comment Indexed Database API 2.0The definition of 'close
()' in that specification. Recommendation Indexed Database API DraftThe definition of 'close
()' in that specification. Recommendation Browser compatibility The compatibility table on this page is generated from structured data. If you'd like t...
IDBDatabase.deleteObjectStore() - Web APIs
As with IDBDatabase.createObjectStore, this method can be called only within a versionchange transaction. Note: This feature is available in Web Workers. Syntax dbInstance.deleteObjectStore(name); Parameters name The name of the object store you want to delete. Exceptions This method may raise a DOMException of one of the following types: Exception Description InvalidStateError Occurs if the method was not called from a versionchange transaction callback. For older WebKit browsers, you must call first. ...
...equest.onupgradeneeded = function(e) { var db = request.result; if (e.oldVersion < 1) { db.createObjectStore("store1"); } if (e.oldVersion < 2) { db.deleteObjectStore("store1"); db.createObjectStore("store2"); } // etc. for version < 3, 4... }; Specification Specification Status Comment Indexed Database API 2.0The definition of 'deleteObjectStore
()' in that specification. Recommendation Indexed Database API DraftThe definition of 'deleteObjectStore
()' in that specification. Recommendation Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
IDBFactory.cmp() - Web APIs
Note: This feature is available in Web Workers. Note: Do not use this method for comparing arbitrary JavaScript values, because many JavaScript values are either not valid IndexedDB keys (booleans and objects, for example) or are treated as equivalent IndexedDB keys (for example, since IndexedDB ignores arrays with non-numeric properties and treats them as empty arrays, so any non-numeric arrays are treated as equivalent). This throws an exception if either of the values is not a valid key. Syntax var result = indexedDB.cmp(first, second); Parameters first The first key to compare. ...
...d may raise a DOMException of the following types: Attribute Description DataError One of the supplied keys was not a valid key. Example var a = 1; var b = 2; var result = window.indexedDB.cmp(a, b); console.log( "Comparison results: " + result ); Specifications Specification Status Comment Indexed Database API 2.0The definition of 'cmp
()' in that specification. Recommendation Indexed Database API DraftThe definition of 'cmp
()' in that specification. Recommendation Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobil...
IDBIndex.getAll() - Web APIs
The getAll
() method of the IDBIndex interface retrieves all objects that are inside the index. There is a performance cost associated with looking at the value property of a cursor, because the object is created lazily. To use a feature like getAll
(), the browser has to create all the objects at once. If you are just interested in looking at each of the keys, for instance, it is more efficient to use a cursor. If you are trying to get an array of all the objects in an object store, though, you should use getAll
(). Syntax var getAllKeysRequest = IDBIndex.getAll
(); var getAllKeysRequest = IDBIndex.getAll(query); var getAllKeysRequest = IDBIndex.getAll(query, count); Parameters query Optional A key or an IDBKeyRange identifying the records to retrieve. If this value is null or missin...
...n of the following types: Exception Description TransactionInactiveError This IDBIndex's transaction is inactive. InvalidStateError The IDBIndex has been deleted or removed. A TypeError exception is thrown if the count parameter is not between 0 and 232-1 included. Example var myIndex = objectStore.index('index'); var getAllRequest = myIndex.getAll
(); getAllRequest.onsuccess = function
() { console.log(getAllRequest.result); } Specification Specification Status Comment Indexed Database API DraftThe definition of 'getAll
()' in that specification. Recommendation Initial definition. ...
IDBIndex.getAllKeys() - Web APIs
If this value is null or missing, the browser will use an unbound key range. count Optional The number records to return. If this value exceeds the number of records in the query, the browser will only retrieve the first item. If it is lower than 0 or greater than 232-1 a TypeError exception will be thrown. ...
...wing types: Exception Description TransactionInactiveError This IDBIndex's transaction is inactive. InvalidStateError The IDBIndex has been deleted or removed. A TypeError exception is thrown if the count parameter is not between 0 and 232-1 included. Example var myIndex = objectStore.index('index'); var getAllKeysRequest = myIndex.getAllKeys
(); getAllKeysRequest.onsuccess = function
() { console.log(getAllKeysRequest.result); } Specification Specification Status Comment Indexed Database API DraftThe definition of 'getAll
()' in that specification. Recommendation Initial definition. Indexed Database API DraftThe definition of 'getAll
()' in that specification. Recommendation ...
IdleDeadline.timeRemaining() - Web APIs
The timeRemaining
() method on the IdleDeadline interface returns the estimated number of milliseconds remaining in the current idle period. The callback can call this method at any time to determine how much time it can continue to work before it must return. For example, if the callback finishes a task and has another one to begin, it can call timeRemaining
() to see if there's enough time to complete the next task. If there isn't, the callback can just return immediately, or look for other work to do with the remaining time. By the time timeRemaining
() reaches 0, it is suggested that the callback should return control to the user agent's event loop. ...
...The value is ideally accurate to within about 5 microseconds. If the IdleDeadline object's didTimeout property is true, this method returns zero. ...
ImageCapture() constructor - Web APIs
The ImageCapture
() constructor creates a new ImageCapture object. Syntax const imageCapture = new ImageCapture(videoTrack) Parameters videoTrack A MediaStreamTrack from which the still images will be taken. This can be any source, such as an incoming stream of a video conference, a playing movie, or the stream from a webcam. Return value A new ImageCapture object which can be used to capture still frames from the specified video track. Example The following example shows how to use a call to MediaDevices.getUserMedia
() to retrieve the MediaStreamTrack needed by the ImageCapture
() constructor. ...
...to capture still frames from the specified video track. Example The following example shows how to use a call to MediaDevices.getUserMedia
() to retrieve the MediaStreamTrack needed by the ImageCapture
() constructor. navigator.mediaDevices.getUserMedia({video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream const track = mediaStream.getVideoTracks
()[0]; imageCapture = new ImageCapture(track); }) .catch(error => console.log(error)); Specifications Specification Status Comment MediaStream Image CaptureThe definition of 'ImageCapture' in that specification. Working Draft Initial definition. ...
ImageData() - Web APIs
This constructor is the preferred way of creating such an object in a Worker. Syntax new ImageData(array, width [, height]); new ImageData(width, height); Parameters array Optional A Uint8ClampedArray containing the underlying pixel representation of the image. If no such array is given, an image with a transparent black rectangle of the specified width and height will be created. width An unsigned long representing the width of the image. height An unsigned long representing the height of the image. This value is optional if an array is given: the height will be inferred from the array's size and the given width. ...
... Living Standard Initial definition. ...
InputEvent.getTargetRanges() - Web APIs
Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
IntersectionObserver.IntersectionObserver() - Web APIs
The rootMargin, if specified, is checked to ensure it's syntactically correct, the thresholds are checked to ensure that they're all in the range 0.0 and 1.0 inclusive, and the threshold list is sorted in ascending numeric order. if the threshold list is empty, it's set to the array [0.0]. Syntax var observer = new IntersectionObserver(callback[, options]); Parameters callback A function which is called when the percentage of the target element is visible crosses a threshold. ...
...s that the entire target element is visible. See Thresholds in Intersection Observer API for a more in-depth description of how thresholds are used. The default is a threshold of 0.0. Return value A new IntersectionObserver which can be used to watch for the visibility of a target element within the specified root crossing through any of the specified visibility thresholds. Call its observe
() method to begin watching for the visibility changes on a given target. Exceptions SyntaxError The specified rootMargin is invalid. RangeError One or more of the values in threshold is outside the range 0.0 to 1.0. Example This example creates a new intersection observer which calls the function myObserverCallback every time the visible area of the element being observed changes by at le...
IntersectionObserver.takeRecords() - Web APIs
The IntersectionObserver method takeRecords
() returns an array of IntersectionObserverEntry objects, one for each targeted element which has experienced an intersection change since the last time the intersections were checked, either explicitly through a call to this method or implicitly by an automatic call to the observer's callback. Note: If you use the callback to monitor these changes, you don't need to call this method. Calling this method clears the pending intersection list, so the callback will not be run. Syntax intersectionObserverEntries = intersectionObserver.takeRecords
(); Parameters None. Return value An array of IntersectionObserverEntry objects, one for each target element whose intersection with the root has changed since the last time the intersections were che...
...Observer.takeRecords
(); Parameters None. Return value An array of IntersectionObserverEntry objects, one for each target element whose intersection with the root has changed since the last time the intersections were checked. Examples <<<...>>> Specifications Specification Status Comment Intersection ObserverThe definition of 'IntersectionObserver.takeRecords
()' in that specification. Working Draft Initial definition. ...
IntersectionObserver.unobserve() - Web APIs
Syntax IntersectionObserver.unobserve(target); Parameters target The Element to cease observing. If the specified element isn't being observed, this method does nothing and no exception is thrown. Return value undefined. Example This snippet simply shows an observer being created, an element being observed, and then being unobserved. var observer = new IntersectionObserver(callback); observer.observe(document.getElementById("elementToObserve")); /* ... ...
...eing created, an element being observed, and then being unobserved. var observer = new IntersectionObserver(callback); observer.observe(document.getElementById("elementToObserve")); /* ... */ observer.unobserve(document.getElementById("elementToObserve")); Specifications Specification Status Comment Intersection ObserverThe definition of 'IntersectionObserver.unobserve
()' in that specification. Working Draft Initial definition. ...
Keyboard.getLayoutMap() - Web APIs
The getLayoutMap
() method of the Keyboard interface returns a Promise that resolves with an instance of KeyboardLayoutMap which is a map-like object with functions for retrieving the strings associated with specific physical keys. Syntax var promise = Keyboard.getLayoutMap
() Parameters None. Return value A Promise that resolves with an instance of KeyboardLayoutMap. Example The following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'W' key on an English QWERTY keyboard. ...
...physical keys. Syntax var promise = Keyboard.getLayoutMap
() Parameters None. Return value A Promise that resolves with an instance of KeyboardLayoutMap. Example The following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'W' key on an English QWERTY keyboard. var keyboard = navigator.keyboard; keyboard.getLayoutMap
() .then(keyboardLayoutMap => { var upKey = keyboardLayoutMap.get('KeyW'); window.alert('Press ' + upKey + ' to move up.'); }) Specifications Specification Status Comment Keyboard MapThe definition of 'getLayoutMap
()' in that specification. Editor's Draft Initial definition. ...
RTCPeerConnection.addTransceiver() - Web APIs
Each transceiver represents a bidirectional stream, with both an RTCRtpSender and an RTCRtpReceiver associated with it. Syntax rtpTransceiver = RTCPeerConnection.addTransceiver(trackOrKind, init); Parameters trackOrKind A MediaStreamTrack to associate with the transceiver, or a DOMString which is used as the kind of the receiver's track, and by extension of the RTCRtpReceiver itself. init Optional An object that conforms to the RTCRtpTransceiverInit dictionary which provides any options that you may wish to specify when creating the new transceiver. ...
... Candidate Recommendation ...
RTCPeerConnection.createDataChannel() - Web APIs
This can be useful for back-channel content such as images, file transfer, text chat, game update packets, and so forth. If the new data channel is the first one added to the connection, renegotiation is started by delivering a negotiationneeded event. Syntax dataChannel = RTCPeerConnection.createDataChannel(label[, options]); Parameters label A human-readable name for the channel. This string may not be longer than 65,535 bytes. ...
... Candidate Recommendation Initial definition. ...
RTCPeerConnection.getIdentityAssertion() - Web APIs
The RTCPeerConnection.getIdentityAssertion
() method initiates the gathering of an identity assertion. This has an effect only if the signalingState is not "closed". The method returns immediately. If the assertion cannot be generated, an idpassertionerror will be sent to the object. It is not expected for the application dealing with the RTCPeerConnection: this is automatically done; an explicit call only allows to anticipate the need. Syntax pc.getIdentityAssertion
(); There is neither parameter nor return value for this method. Example var pc = new PeerConnection
(); pc.getIdentityAssertion
(); // Not mandatory, but we know that we will need it in the future. Specifications Specification Status Comment Identity for WebRTCThe definition of 'RTCPeer...
...e the need. Syntax pc.getIdentityAssertion
(); There is neither parameter nor return value for this method. Example var pc = new PeerConnection
(); pc.getIdentityAssertion
(); // Not mandatory, but we know that we will need it in the future. Specifications Specification Status Comment Identity for WebRTCThe definition of 'RTCPeerConnection.getIdentityAssertion
()' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection.getReceivers() - Web APIs
The RTCPeerConnection.getReceivers
() method returns an array of RTCRtpReceiver objects, each of which represents one RTP receiver. Each RTP receiver manages the reception and decoding of data for a MediaStreamTrack on an RTCPeerConnection Syntax var receivers = rtcPeerConnection.getReceivers
(); Return value An array of RTCRtpReceiver objects, one for each track on the connection. The array is empty if there are no RTP receivers on the connection. The order of the returned RTCRtpReceiver instances is not defined by the specification, and may change from one call to getReceivers
() to the next. Example tbd Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.getReceiv...
...ray is empty if there are no RTP receivers on the connection. The order of the returned RTCRtpReceiver instances is not defined by the specification, and may change from one call to getReceivers
() to the next. Example tbd Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.getReceivers
()' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection.getTransceivers() - Web APIs
The RTCPeerConnection interface's getTransceivers
() method returns a list of the RTCRtpTransceiver objects being used to send and receive data on the connection. Syntax transceiverList = rtcPeerConnection.getTransceivers
(); Parameters None. Return value An array of the RTCRtpTransceiver objects representing the transceivers handling sending and receiving all media on the RTCPeerConnection. The list is in the order in which the transceivers were added to the connection. Example The following snippet of code stops all transceivers associated with an RTCPeerConnection. ...
...ection.getTransceivers
(); Parameters None. Return value An array of the RTCRtpTransceiver objects representing the transceivers handling sending and receiving all media on the RTCPeerConnection. The list is in the order in which the transceivers were added to the connection. Example The following snippet of code stops all transceivers associated with an RTCPeerConnection. pc.getTransceivers
().forEach(transceiver => { transceiver.stop
(); }); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.getTransceivers
()' in that specification. Candidate Recommendation ...
RTCPeerConnection.setIdentityProvider() - Web APIs
The IdP will be used only when an assertion is needed. If the signalingState is set to "closed", an InvalidStateError is raised. Syntax pc.setIdentityProvider(domainname [, protocol] [, username]); There is no return value for this method. Parameters domainname Is a DOMString is the domain name where the IdP is. protocol Optional Is a DOMString representing the protocol used to communicate with the IdP. It defaults to "default" and is used to determine the URL where the IdP is listening. ...
...or this method. Parameters domainname Is a DOMString is the domain name where the IdP is. protocol Optional Is a DOMString representing the protocol used to communicate with the IdP. It defaults to "default" and is used to determine the URL where the IdP is listening. username Optional Is a DOMString representing the username associated with the IdP. Example var pc = new PeerConnection
(); pc.setIdentityAssertion("developer.mozilla.org"); Specifications Specification Status Comment Identity for WebRTCThe definition of 'RTCPeerConnection.setIdentityProvider
()' in that specification. Candidate Recommendation ...
RTCRtpReceiver.getParameters() - Web APIs
The getParameters
() method of the RTCRtpReceiver interface returns an RTCRtpReceiveParameters object describing the current configuration for the encoding and transmission of media on the receiver's track. Syntax let rtpReceiveParameters = rtpReceiver.getParameters
(); Parameters None. Return value An RTCRtpReceiveParameters object indicating the current configuration of the receiver. Examples This example obtains the canonical name (CNAME) being used for RTCP on an RTCRtpReceiver. ...
... of media on the receiver's track. Syntax let rtpReceiveParameters = rtpReceiver.getParameters
(); Parameters None. Return value An RTCRtpReceiveParameters object indicating the current configuration of the receiver. Examples This example obtains the canonical name (CNAME) being used for RTCP on an RTCRtpReceiver. function getRtcpCNAME(receiver) { let parameters = receiver.getParameters
(); return parameters.rtcp.cname; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpReceiver.getParameters
()' in that specification. Candidate Recommendation Initial definition. ...
RTCRtpReceiver.getSynchronizationSources() - Web APIs
Return value An array of RTCRtpSynchronizationSource instances. Each instance describes one of the synchronization sources that provided data to the incoming stream in the past ten seconds. As you'll see in the documentarion for RTCRtpSynchronizationSource, it inherits the properties of RTCRtpContributingSource, including timestamp, source, and audioLevel. ...
... Candidate Recommendation Initial definition. ...
RTCRtpSender.getParameters() - Web APIs
The getParameters
() method of the RTCRtpSender interface returns an RTCRtpSendParameters object describing the current configuration for the encoding and transmission of media on the sender's track. Syntax var rtpSendParameters = rtpSender.getParameters
() Parameters None. Return value An RTCRtpSendParameters object indicating the current configuration of the sender. Examples This example gets the sender's current transaction ID; the transaction ID uniquely identifies the current set of parameters, to ensure that calls to setParameters
() are always handled in the correct order, avoiding inadvertently overwriting parameters with older parameters. ...
...nt configuration of the sender. Examples This example gets the sender's current transaction ID; the transaction ID uniquely identifies the current set of parameters, to ensure that calls to setParameters
() are always handled in the correct order, avoiding inadvertently overwriting parameters with older parameters. function getSenderTransactionID(sender) { let parameters = sender.getParameters
(); return parameters.transactionId; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'getParameters
()' in that specification. Candidate Recommendation Initial definition. ...
RTCRtpSender.getStats() - Web APIs
The promise's fulfillment handler receives as a parameter a RTCStatsReport object containing the collected statistics. The returned RTCStatsReport accumulates the statistics for all of the streams being sent using the RTCRtpSender, as well as the statistics for any dependencies those streams have. ...
...g the collected statistics. The returned RTCStatsReport accumulates the statistics for all of the streams being sent using the RTCRtpSender, as well as the statistics for any dependencies those streams have. Example This simple example obtains the statistics for an RTCRtpSender and updates an element's innerText to display the current round trip time for requests on the sender. sender.getStats
().then(function(stats) { document.getElementById("currentRTT").innerText = stats.roundTripTime; }); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpSender.getStats
()' in that specification. Candidate Recommendation Initial specification. ...
RTCSessionDescription.toJSON() - Web APIs
The RTCSessionDescription.toJSON
() method generates a JSON description of the object. Both properties, type and sdp, are contained in the generated JSON. Syntax var jsonValue = sd.toJSON
(); The result value is a JSON object containing the following values: "type", containing the value of the RTCSessionDescription.type property and can be one of the following values: "offer", "answer", "pranswer" or null. "sdp", containing a DOMString, or null, with the SDP message corresponding to RTCSessionDescription.sdp property. Example // sd is a RTCSessionDescriptor alert(JSON.stringify(sd)); // This call the toJSON
() method behind the scene. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'R...
...aining a DOMString, or null, with the SDP message corresponding to RTCSessionDescription.sdp property. Example // sd is a RTCSessionDescriptor alert(JSON.stringify(sd)); // This call the toJSON
() method behind the scene. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCSessionDescription: toJSON
()' in that specification. Candidate Recommendation Initial specification. ...
RTCTrackEvent() - Web APIs
In general, you won't need to use this constructor, as RTCTrackEvent objects are created by WebRTC and delivered to your RTCPeerConnector's ontrack event handler as appropriate. Syntax trackEvent = new RTCTrackEvent(eventInfo); Parameters eventInfo An object based on the RTCTrackEventInit dictionary, providing information about the track which has been added to the RTCPeerConnection. This object has the following properties: receiver The RTCRtpReceiver which is being used to receive the track's media. ...
...esponding track. track The MediaStreamTrack the event is associated with. transceiver The RTCRtpTransceiver associated with the event. Return value A new RTCTrackEvent describing a track which has been added to the RTCPeerConnection. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCTrackEvent
()' in that specification. Candidate Recommendation Initial specification. ...
Range.collapse() - Web APIs
The Range.collapse
() method collapses the Range to one of its boundary points. A collapsed Range is empty, containing no content, specifying a single-point in a DOM tree. To determine if a Range is already collapsed, see the Range.collapsed property. Syntax range.collapse(toStart); Parameters toStart Optional A Boolean value: true collapses the Range to its start, false to its end. If omitted, it defaults to false . Example var range = document.createRange
(); referenceNode = document.getElementsByTagName("div").item(0); range.selectNode(referenceNode); range.collapse(true); Specifications Specification Status Comment DOMThe definition of 'Range.collapse
()' in that specification. Living Standard The parameter is now optional and default to false...
...ByTagName("div").item(0); range.selectNode(referenceNode); range.collapse(true); Specifications Specification Status Comment DOMThe definition of 'Range.collapse
()' in that specification. Living Standard The parameter is now optional and default to false. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.collapse
()' in that specification. Obsolete Initial specification. ...
Range.comparePoint() - Web APIs
The Range.comparePoint
() method returns -1, 0, or 1 depending on whether the referenceNode is before, the same as, or after the Range. If the reference node is a Node of type Text, Comment, or CDATASection, then offset is the number of characters from the start of reference node. For other Node types, offset is the number of child nodes between the start of the reference node. Syntax returnValue = range.comparePoint(referenceNode, offset) Parameters referenceNode The Node to compare with the Range. offset An integer greater than or equal to zero representing the offset inside the referenceNode. ...
... the start of reference node. For other Node types, offset is the number of child nodes between the start of the reference node. Syntax returnValue = range.comparePoint(referenceNode, offset) Parameters referenceNode The Node to compare with the Range. offset An integer greater than or equal to zero representing the offset inside the referenceNode. Example range = document.createRange
(); range.selectNode(document.getElementsByTagName('div').item(0)); returnValue = range.comparePoint(document.getElementsByTagName('p').item(0), 1); Specification Specification Status Comment DOMThe definition of 'Range.comparePoint
()' in that specification. Living Standard Initial specification. ...
Range.toString() - Web APIs
The Range.toString
() method is a stringifier returning the text of the Range. Alerting the contents of a Range makes an implicit toString
() call, so comparing range and text through an alert dialog is ineffective. Syntax text = range.toString
(); Example HTML <p>This example logs <b>everything</b> between the bold <b>words</b>. Look at the output below.</p> <p id="log"></p> JavaScript const range = document.createRange
(); range.setStartBefore(document.getElementsByTagName('b').item(0), 0); range.setEndAfter(document.getElementsByTagName('b').item(1), 0); document.getElementById('log').textContent = range.toString
(); Result Specifications Specification Status Comment DOMThe definition of 'Range.toString
()' in that specification. Living Standard No c...
...r(document.getElementsByTagName('b').item(1), 0); document.getElementById('log').textContent = range.toString
(); Result Specifications Specification Status Comment DOMThe definition of 'Range.toString
()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.toString
()' in that specification. Obsolete Initial specification. ...
ReadableStream.pipeTo() - Web APIs
Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. Syntax var promise = readableStream.pipeTo(destination[, options]); Parameters destination A WritableStream that acts as the final destination for the ReadableStream. options Optional The options that should be used when piping to the writable stream. ...
...that resolves when the piping process has completed. Exceptions TypeError The writableStream and/or readableStream objects are not a writable stream/readable stream, or one or both of the streams are locked. Examples // Fetch the original image fetch('png-logo.png') // Retrieve its body as ReadableStream .then(response => response.body) .then(body => body.pipeThrough(new PNGTransformStream
())) .then(rs => rs.pipeTo(new FinalDestinationStream
())) Specifications Specification Status Comment StreamsThe definition of 'pipeTo
()' in that specification. Living Standard Initial definition. ...
ReadableStreamBYOBReader.read() - Web APIs
Syntax var promise = readableStreamBYOBReader.read(view); Parameters view The view to be read into. Return value A Promise, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: If a chunk is available, the promise will be fulfilled with an object of the form { value: theChunk, done: false }. If the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. If the stream becomes errored, the promise will be rejected with the relevant error. ...
... done: true }. If the stream becomes errored, the promise will be rejected with the relevant error. Exceptions TypeError The source object is not a ReadableStreamBYOBReader, the stream has no owner, the view is not an object or has become detached, or the view's length is 0. Examples TBD. Specifications Specification Status Comment StreamsThe definition of 'read
()' in that specification. Living Standard Initial definition. ...
ReadableStreamBYOBReader.releaseLock() - Web APIs
Return value undefined. Exceptions TypeError The source object is not a ReadableStreamBYOBReader, or a read request is pending. ...
...lock on the stream. After the lock is released, the reader is no longer active. If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by the reader's ReadableStreamBYOBReader.read
() method has not finished. This will result in a TypeError being thrown. Syntax readableStreamBYOBReader.releaseLock
(); Parameters None. Return value undefined. Exceptions TypeError The source object is not a ReadableStreamBYOBReader, or a read request is pending. Examples TBD. Specifications Specification Status Comment StreamsThe definition of 'releaseLock(...
ReadableStreamDefaultController.error() - Web APIs
Syntax readableStreamDefaultController.error(e); Parameters e The error you want future interactions to fail with. Return value undefined. Exceptions TypeError The source object is not a ReadableStreamDefaultController, or the stream is not readable for some other reason. ...
...ypeError The source object is not a ReadableStreamDefaultController, or the stream is not readable for some other reason. Examples The A readable stream with an underlying push source and backpressure support example in the spec provides a good example of using ReadableStreamDefaultController.desiredSize to manually detect when the stream is full and apply backpressure, and also of using error
() to manually trigger a stream error if another part of the system it relies on fails. Specifications Specification Status Comment StreamsThe definition of 'error
()' in that specification. Living Standard Initial definition. ...
ReadableStreamDefaultReader.releaseLock() - Web APIs
The releaseLock
() method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by the reader's ReadableStreamDefaultReader.read
() method has not finished. This will result in a TypeError being thrown. Syntax readableStreamDefaultReader.releaseLock
(); Parameters None. Return value undefined. Exceptions TypeError The source object is not a ReadableStreamDefaultReader, or a read request is pending. Examples function fetchStream
() { const reader = stream.getReader
(); ... ...
...aultReader.read
() method has not finished. This will result in a TypeError being thrown. Syntax readableStreamDefaultReader.releaseLock
(); Parameters None. Return value undefined. Exceptions TypeError The source object is not a ReadableStreamDefaultReader, or a read request is pending. Examples function fetchStream
() { const reader = stream.getReader
(); ... reader.releaseLock
() ... } Specifications Specification Status Comment StreamsThe definition of 'releaseLock
()' in that specification. Living Standard Initial definition. ...
ReportingObserver.disconnect() - Web APIs
The disconnect
() method of the ReportingObserver interface stops a reporting observer that had previously started observing from collecting reports. After calling disconnect
(), neither ReportingObserver.takeRecords
() nor the records parameter of the ReportingObserver
() callback will return any reports. The associated observer will no longer be active. Syntax reportingObserverInstance.disconnect
() Examples let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { reportBtn.onclick =
() => displayReports(reports); }, options); observer.observe
() ... ...
...rtingObserver
() callback will return any reports. The associated observer will no longer be active. Syntax reportingObserverInstance.disconnect
() Examples let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { reportBtn.onclick =
() => displayReports(reports); }, options); observer.observe
() ... observer.disconnect
() Specifications Specification Status Comment Reporting APIThe definition of 'ReportingObserver.disconnect
()' in that specification. Editor's Draft ...
Request.clone() - Web APIs
The clone
() method of the Request interface creates a copy of the current Request object. clone
() throws a TypeError if the response Body has already been used. In fact, the main reason clone
() exists is to allow multiple uses of Body objects (when they are one-use only.) If intend to modify the request, you may prefer the Request constructor. Syntax var newRequest = request.clone
(); Parameters None. Return value A Request object, which is an exact copy of the Request that clone
() was called on. Example In the following snippet, we create a new request using the Request.Request
() constructor (for an image file in the same directory as the script), then clone the request. ...
...uest = request.clone
(); Parameters None. Return value A Request object, which is an exact copy of the Request that clone
() was called on. Example In the following snippet, we create a new request using the Request.Request
() constructor (for an image file in the same directory as the script), then clone the request. var myRequest = new Request('flowers.jpg'); var newRequest = myRequest.clone
(); // a copy of the request is now stored in newRequest Specifications Specification Status Comment FetchThe definition of 'clone' in that specification. Living Standard Initial definition ...
Response() - Web APIs
Syntax var myResponse = new Response(body, init); Parameters body Optional An object defining a body for the response. This can be null (which is the default value), or one of: Blob BufferSource FormData ReadableStream URLSearchParams USVString init Optional An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: status: The status code for the reponse, e.g., 200. statusText: The status message associated with the status code, e.g., OK. ...
...ers you want to add to your response, contained within a Headers object or object literal of ByteString key/value pairs (see HTTP headers for a reference). Examples In our Fetch Response example (see Fetch Response live) we create a new Response object using the constructor, passing it a new Blob as a body, and an init object containing a custom status and statusText: var myBlob = new Blob
(); var init = { "status" : 200 , "statusText" : "SuperSmashingGreat!" }; var myResponse = new Response(myBlob,init); Specifications Specification Status Comment FetchThe definition of 'Response
()' in that specification. Living Standard Initial definition ...
Response.clone() - Web APIs
The clone
() method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. clone
() throws a TypeError if the response Body has already been used. In fact, the main reason clone
() exists is to allow multiple uses of Body objects (when they are one-use only.) Syntax var response2 = response1.clone
(); Parameters None. Value A Response object. Example In our Fetch Response clone example (see Fetch Response clone live) we create a new Request object using the Request
() constructor, passing it a JPG path. We then fetch this request using fetch
(). When the fetch resolves successfully, we clone it, extract a blob from both responses using two Body.blob calls, create object URLs out of the blobs using URL.createObjectURL, a...
...e clone it, extract a blob from both responses using two Body.blob calls, create object URLs out of the blobs using URL.createObjectURL, and display them in two separate <img> elements. var image1 = document.querySelector('.img1'); var image2 = document.querySelector('.img2'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { var response2 = response.clone
(); response.blob
().then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); image1.src = objectURL; }); response2.blob
().then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); image2.src = objectURL; }); }); Specifications Specification Status Comment FetchThe definition of 'clone
()' in that specification. Living Stand...
Response.redirect() - Web APIs
Note: This is mainly relevant to the ServiceWorker API. A controlling service worker could intercept a page's request and redirect it as desired. This will actually lead to a real redirect if a service worker sends it upstream. Syntax var response = Response.redirect(url, status); Parameters url The URL that the new response is to originate from. status Optional An optional status code for the response (e.g., 302.) Return value A Response object. Exceptions Exception Explanation RangeError The specified status is not a redirect status. TypeError The specified URL is invalid. ...
...sponse (e.g., 302.) Return value A Response object. Exceptions Exception Explanation RangeError The specified status is not a redirect status. TypeError The specified URL is invalid. Example responseObj.redirect('https://www.example.com', 302); Specifications Specification Status Comment FetchThe definition of 'redirect
()' in that specification. Living Standard ...
SVGGeometryElement.isPointInFill() - Web APIs
Normal hit testing rules apply; the value of the pointer-events property on the element determines whether a point is considered to be within the fill. The point argument is interpreted as a point in the local coordiante system of the element. Syntax boolean someElement.isPointInFill(DOMPointInit point); Parameters point A DOMPointInit interpreted as a point in the local coordiante system of the element. Return value A boolean indicating whether the given point is within the fill or not. ...
... Candidate Recommendation Initial definition ...
SVGGeometryElement.isPointInStroke() - Web APIs
Normal hit testing rules apply; the value of the pointer-events property on the element determines whether a point is considered to be within the stroke. The point argument is interpreted as a point in the local coordiante system of the element. Syntax boolean someElement.isPointInStroke(DOMPointInit point); Parameters point A DOMPointInit interpreted as a point in the local coordinate system of the element. Return value A boolean indicating whether the given point is within the stroke or not. ...
... Candidate Recommendation Initial definition ...
getBBox() - Web APIs
The SVGGraphicsElement.getBBox
() allows us to determine the coordinates of the smallest rectangle in which the object fits. The coordinates returned are with respect to the current SVG space (after the application of all geometry attributes on all the elements contained in the target element). Note: getBBox
() must return the actual bounding box at the time the method was called--even in case the element has not yet been rendered. It also does not account for any transformation applied to the element or its parents. getBBox returns different values than getBoundingClientRect
(), as the latter returns value relative to the viewport Syntax let bboxRect = object.getBBox
(); Return value The returned value is a SVGRect object, which defines the bounding box. This value is irrespective of...
...#00ff00" stroke-width="3" fill="none"> </rect> <!-- Shows BoundingClientRect in red --> <rect id="rect_2" stroke="#ff0000" stroke-width="3" fill="none"></rect> </svg> JavaScript var rectBBox = document.querySelector('#rect_1'); var rectBoundingClientRect = document.querySelector('#rect_2'); var groupElement = document.querySelector('#group_text_1'); var bboxGroup = groupElement.getBBox
(); rectBBox.setAttribute('x', bboxGroup.x); rectBBox.setAttribute('y', bboxGroup.y); rectBBox.setAttribute('width', bboxGroup.width); rectBBox.setAttribute('height', bboxGroup.height); var boundingClientRectGroup = groupElement.getBoundingClientRect
(); rectBoundingClientRect.setAttribute('x', boundingClientRectGroup.x); rectBoundingClientRect.setAttribute('y', boundingClientRectGroup.y); rectBound...
Screen.lockOrientation() - Web APIs
Note: This method only works for installed Web apps or for Web pages in full-screen mode. Syntax lockAllowed = window.screen.lockOrientation(orientation); Parameters orientation The orientation into which to lock the screen. This is either a string or an array of strings. Passing several strings lets the screen rotate only in the selected orientations. The following strings represent the possible orientation requirements you may specify: portrait-primary It represents the orientation of the screen when it is in its primary portrait mode. ...
... Working Draft Initial definition (Not present in the draft anymore) ...
Screen.unlockOrientation() - Web APIs
The Screen.unlockOrientation
() method removes all the previous screen locks set by the page/app. The ScreenOrientation.unlock
() method should be used instead. Note: This method only works for installed Web apps or for Web pages in full-screen mode. Syntax var unlocked = window.screen.unlockOrientation
(); Return value Returns true if the orientation was successfully unlocked or false if the orientation couldn't be unlocked. ...
...n full-screen mode. Syntax var unlocked = window.screen.unlockOrientation
(); Return value Returns true if the orientation was successfully unlocked or false if the orientation couldn't be unlocked. Example var unlockOrientation = screen.unlockOrientation || screen.mozUnlockOrientation || screen.msUnlockOrientation || (screen.orientation && screen.orientation.unlock); if (unlockOrientation
()) { // orientation was unlocked } else { // orientation unlock failed } Specifications Specification Status Comment Screen Orientation APIThe definition of 'lockOrientation
()' in that specification. Working Draft Initial definition (Not present in the draft anymore) ...
Window.find() - Web APIs
Syntax window.find(aString, aCaseSensitive, aBackwards, aWrapAround, aWholeWord, aSearchInFrames, aShowDialog); aString The text string for which to search. aCaseSensitive Boolean. If true, specifies a case-sensitive search. aBackwards Boolean. If true, specifies a backward search. aWrapAround Boolean. If true, specifies a wrap around search. aWholeWord Unimplemented Boolean. If true, specifies a whole word search. This is not implemented; see bug 481513. aSearchInFrames Boolean. If true, specifies a search in frames. ...
... Specification This is not part of any specification. ...
Window.getDefaultComputedStyle() - Web APIs
The getDefaultComputedStyle
() method gives the default computed values of all the CSS properties of an element, ignoring author styling. That is, only user-agent and user styles are taken into account. Syntax var style = window.getDefaultComputedStyle(element [, pseudoElt]); Parameters element The Element for which to get the computed style. pseudoElt Optional A string specifying the pseudo-element to match. Must be null (or not specified) for regular elements. Return value The returned style is a CSSStyleDeclaration object. The object is of the same type as the object returned by Window.getComputedStyle
(), but only takes into account user-agent and user rules. Example Simple example var elem1 = document.getElementById("elemId"); var style = window.getDefaultCo...
... <style> h3:after { content: ' rocks!'; } </style> <h3>generated content</h3> <script> var h3 = document.querySelector('h3'), result = getDefaultComputedStyle(h3, ':after').content; console.log('the generated content is: ', result); // returns 'none' </script> Notes The returned value is, in ...
Window.moveBy() - Web APIs
The moveBy
() method of the Window interface moves the current window by a specified amount. Note: This function moves the window relative to its current location. In contrast, window.moveTo
() moves the window to an absolute location. Syntax window.moveBy(deltaX, deltaY) Parameters deltaX is the amount of pixels to move the window horizontally. Positive values are to the right, while negative values are to the left. deltaY is the amount of pixels to move the window vertically. Positive values are down, while negative values are up. Example This example moves the window 10 pixels to the right and 10 pixels up. ...
... window.moveBy(deltaX, deltaY) Parameters deltaX is the amount of pixels to move the window horizontally. Positive values are to the right, while negative values are to the left. deltaY is the amount of pixels to move the window vertically. Positive values are down, while negative values are up. Example This example moves the window 10 pixels to the right and 10 pixels up. function budge
() { moveBy(10, -10); } Specification Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'window.moveBy
()' in that specification. Working Draft ...
Window.print() - Web APIs
Living Standard Browser Compatibility The compatibility table in this page is generated from structured data. ...
... Living Standard Browser Compatibility The compatibility table in this page is generated from structured data. ...
Window.requestFileSystem() - Web APIs
It has even been removed from the proposed specification. Do not use this method! Syntax This method is prefixed with webkit in all browsers that implement it (that is, Google Chrome). ...
...It has even been removed from the proposed specification. Do not use this method! Syntax This method is prefixed with webkit in all browsers that implement it (that is, Google Chrome). ...
window.requestIdleCallback() - Web APIs
The window.requestIdleCallback
() method queues a function to be called during a browser's idle periods. This enables developers to perform background and low priority work on the main event loop, without impacting latency-critical events such as animation and input response. Functions are generally called in first-in-first-out order; however, callbacks which have a timeout specified may be called out-of-order if necessary in order to run them before the timeout elapses. You can call requestIdleCallback
() within an idle callback function to schedule another callback to take place no sooner than the next pass through the event loop. A timeout option is strongly recommended for required work, as otherwise it's possible multiple seconds will elapse before the callback is fired. Syn...
...lback to take place no sooner than the next pass through the event loop. A timeout option is strongly recommended for required work, as otherwise it's possible multiple seconds will elapse before the callback is fired. Syntax var handle = window.requestIdleCallback(callback[, options]) Return value An ID which can be used to cancel the callback by passing it into the window.cancelIdleCallback
() method. Parameters callback A reference to a function that should be called in the near future, when the event loop is idle. The callback function is passed an IdleDeadline object describing the amount of time available and whether or not the callback has been run because the timeout period expired. options Optional Contains optional configuration parameters. Currently only one property is...
Window.scroll() - Web APIs
The Window.scroll
() method scrolls the window to a particular place in the document. Syntax window.scroll(x-coord, y-coord) window.scroll(options) Parameters x-coord is the pixel along the horizontal axis of the document that you want displayed in the upper left. y-coord is the pixel along the vertical axis of the document that you want displayed in the upper left. - or - options is a ScrollToOptions dictionary. Examples <!-- put the 100th vertical pixel at the top of the window --> <button onclick="scroll(0, 100);">click to scroll down 100 pixels</button> Using options: window.scroll({ top: 100, left: 100, behavior: 'smooth' }); Notes Window.scrollTo
() is effectively the same as this method. ...
...t. - or - options is a ScrollToOptions dictionary. Examples <!-- put the 100th vertical pixel at the top of the window --> <button onclick="scroll(0, 100);">click to scroll down 100 pixels</button> Using options: window.scroll({ top: 100, left: 100, behavior: 'smooth' }); Notes Window.scrollTo
() is effectively the same as this method. For relative scrolling, see Window.scrollBy
(), Window.scrollByLines
(), and Window.scrollByPages
(). For scrolling elements, see Element.scrollTop and Element.scrollLeft. Specification Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'window.scroll
()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table in this page ...
Window.scrollBy() - Web APIs
The Window.scrollBy
() method scrolls the document in the window by the given amount. Syntax window.scrollBy(x-coord, y-coord); window.scrollBy(options) Parameters x-coord is the horizontal pixel value that you want to scroll by. y-coord is the vertical pixel value that you want to scroll by. - or - options is a ScrollToOptions dictionary. Examples To scroll down one page: window.scrollBy(0, window.innerHeight); To scroll up: window.scrollBy(0, -window.innerHeight); Using options: window.scrollBy({ top: 100, left: 100, behavior: 'smooth' }); Notes window.scrollBy
() scrolls by a particular amount, whereas window.scroll
() scrolls to an absolute position in the document. See also window.scrollByLines
() and window.scrollByPages
(). Specification Specificat...
... Working Draft Initial definition. Browser Compatibility The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
Window.scrollTo() - Web APIs
For scrolling elements, see Element.scrollTop and Element.scrollLeft. ...
...s the pixel along the horizontal axis of the document that you want displayed in the upper left. y-coord is the pixel along the vertical axis of the document that you want displayed in the upper left. - or - options is a ScrollToOptions dictionary. Examples window.scrollTo(0, 1000); Using options: window.scrollTo({ top: 100, left: 100, behavior: 'smooth' }); Notes Window.scroll
() is effectively the same as this method. For relative scrolling, see Window.scrollBy
(), Window.scrollByLines
(), and Window.scrollByPages
(). For scrolling elements, see Element.scrollTop and Element.scrollLeft. Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'window.scroll
()' in that specification. Working Draft ...
Window.showModalDialog() - Web APIs
Syntax returnVal = window.showModalDialog(uri[, arguments][, options]); returnVal holds the returnValue property as set by the document specified by uri. uri is the URL of the document to display in the dialog. arguments is an optional variant containing values passed to the dialog; these are made available in the window object's window.dialogArguments property. ...
...value is on, yes, or 1, the dialog window can be resized by the user; otherwise its size is fixed. The default value is no. scroll: {on | off | yes | no | 1 | 0 } If on, yes, or 1, the dialog window has scroll bars; otherwise its size is fixed. Default is no. Note: Firefox does not implement the dialogHide, edge, status, or unadorned arguments. Examples Try out showModalDialog
(). Notes showModalDialog
() was briefly standardized as part of HTML5. The third argument for additional options was not present in the HTML5 version. Specification MSDN page for showModalDialog Browser compatibility The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and...
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. Specifications Specification Status Comment HTML Living StandardThe definition of 'WindowOrWorkerGlobalScope.clearI...
...d 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 ...
WorkerGlobalScope.importScripts() - Web APIs
The importScripts
() method of the WorkerGlobalScope interface synchronously imports one or more scripts into the worker's scope. Syntax self.importScripts('foo.js'); self.importScripts('foo.js', 'bar.js', ...); Parameters A comma-separated list of DOMString objects representing the scripts to be imported. These paths are relative to html document base URL. Return value None. Exceptions NetworkError Imported scripts were not served with a valid JavaScript MIME type (i.e. text/javascript). ...
...e paths are relative to html document base URL. Return value None. Exceptions NetworkError Imported scripts were not served with a valid JavaScript MIME type (i.e. text/javascript). Example If you had some functionality written in a separate script called foo.js that you wanted to use inside worker.js, you could import it using the following line: importScripts('foo.js'); importScripts
() and self.importScripts
() are effectively equivalent -- both represent importScripts
() being called from inside the worker's inner scope. Specifications Specification Status Comment HTML Living StandardThe definition of 'importScripts
()' in that specification. Living Standard ...
WritableStream.abort() - Web APIs
The abort
() method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. Syntax var promise = writableStream.abort(reason); Parameters reason A DOMString providing a human-readable reason for the abort. Return value A Promise, which fulfills with the value given in the reason parameter. Exceptions TypeError The stream you are trying to abort is not a WritableStream, or it is locked. Examples const writableStream = new WritableStream({ write(chunk) { ... }, close
() { ... }, abort(err) { ... } }, queuingStrategy); ... ...
...omise, which fulfills with the value given in the reason parameter. Exceptions TypeError The stream you are trying to abort is not a WritableStream, or it is locked. Examples const writableStream = new WritableStream({ write(chunk) { ... }, close
() { ... }, abort(err) { ... } }, queuingStrategy); ... // abort the stream later on, when required writableStream.abort
(); Specifications Specification Status Comment StreamsThe definition of 'abort
()' in that specification. Living Standard Initial definition. ...
WritableStreamDefaultController.error() - Web APIs
This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. Syntax writableStreamDefaultController.error(e); Parameters e A DOMString representing the error you want future interactions to fail with. Return value undefined. Exceptions TypeError The stream you are trying to error is not a WritableStream. ...
... Living Standard Initial definition. ...
WritableStreamDefaultWriter.abort() - Web APIs
If not, it returns a rejected promise. Syntax var promise = writableStreamDefaultWriter.abort(reason); Parameters reason Optional A DOMString representing a human-readable reason for the abort. Return value A Promise, which fulfills with the value given in the reason parameter. Exceptions TypeError The stream you are trying to abort is not a WritableStream, or it is locked. ...
...iter.abort(reason); Parameters reason Optional A DOMString representing a human-readable reason for the abort. Return value A Promise, which fulfills with the value given in the reason parameter. Exceptions TypeError The stream you are trying to abort is not a WritableStream, or it is locked. Examples const writableStream = new WritableStream({ write(chunk) { ... }, close
() { ... }, abort(err) { ... } }, queuingStrategy); ... const writer = writableStream.getWriter
(); ... // abort the stream when desired writer.abort.then((reason) => { console.log(reason); }) Specifications Specification Status Comment StreamsThe definition of 'abort
()' in that specification. Living Standard Initial definition. ...
regexp:match() - EXSLT
Syntax regexp:match(targetString, regExpString[, flagsString]) Parameters targetString The string to perform regular expression matching upon. regExpString The JavaScript style regular expression to evaluate. flagsStringOptional An optional string containing character flags. The character flags are: g Global match The submatches from every match in the string are returned. If this flag isn't specified, only the submatches from the first match are returned. ...
...red by the regular expression. If the match isn't a global one, the first match element has the value of the portion of the string matched by the entire regular expression. ...
AggregateError() constructor - JavaScript
The AggregateError
() constructor creates an error for several errors that need to be wrapped in a single error. Syntax new AggregateError(errors[, message]) Parameters errors An iterable of errors, may not actually be Error instances. messageOptional An optional human-readable description of the aggregate error. ...
... ...
Array.prototype.entries() - JavaScript
The entries
() method returns a new Array Iterator object that contains the key/value pairs for each index in the array. 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 array.entries
() Return value A new Array iterator object. ...
...urce 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 array.entries
() Return value A new Array iterator object. Examples Iterating with index and element const a = ['a', 'b', 'c']; for (const [index, element] of a.entries
()) console.log(index, element); // 0 'a' // 1 'b' // 2 'c' Using a for...of loop var a = ['a', 'b', 'c']; var iterator = a.entries
(); for (let e of iterator) { console.log(e); } // [0, 'a'] // [1, 'b'] // [2, 'c'] Specifications Specification ECMAScript (ECMA-262)The definition of 'Array.prototype.entries' in that specification. ...
Array.prototype.find() - JavaScript
The find
() method returns the value of the first element in the provided array that satisfies the provided testing function. 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. If you need the index of the found element in the array, use findIndex
(). If you need to find the index of a value, use Array.prototype.indexOf
(). (It's similar to findIndex
(), but checks each element for equality with the value instead of using a testing function.) If you need to find if a value exists in an array, use Array.prototype.includes
(). Again, it checks each element for equality with the value instead of using a testing function.
... Syntax arr.find(callback(element[, index[, array]])[, thisArg]) Parameters callback Function to execute on each value in the array, taking 3 arguments: element The current element in the array. index Optional The index (position) of the current element in the array. array Optional The array that find was called on. ...
Array.prototype.join() - JavaScript
If the array has only one item, then that item will be returned without using the separator. 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 arr.join([separator]) Parameters separator Optional Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). ...
...s are joined into one string. If an element is undefined, null or an empty array [], it is converted to an empty string. Examples Joining an array four different ways The following example creates an array, a, with three elements, then joins the array four times: using the default separator, then a comma and a space, then a plus and an empty string. var a = ['Wind', 'Water', 'Fire']; a.join
(); // 'Wind,Water,Fire' a.join(', '); // 'Wind, Water, Fire' a.join(' + '); // 'Wind + Water + Fire' a.join(''); // 'WindWaterFire' Joining an array-like object The following example joins array-like object (arguments), by calling Function.prototype.call on Array.prototype.join. function f(a, b, c) { var s = Array.prototype.join.call(arguments); console.log(s); // '1,a,true' } f(1, ...
Array.prototype.lastIndexOf() - JavaScript
The array is searched backwards, starting at fromIndex. 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 arr.lastIndexOf(searchElement[, fromIndex]) Parameters searchElement Element to locate in the array. fromIndex Optional The index at which to start searching backwards. Defaults to the array's length minus one (arr.length - 1), i.e. the whole array will be searched. ...
... assuming Object, TypeError, Number, Math.floor, Math.abs, and Math.min have their original values. ...
Array.prototype.push() - JavaScript
The push
() method adds one or more elements to the end of an array and returns the new length of the array. 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 arr.push([element1[, ...[, elementN]]]) Parameters elementN The element(s) to add to the end of the array. Return value The new length property of the object upon which the method was called. Description The push method appends values to an array. push is intentionally generic. This method can be used with call
() or apply
() on objects resembling arrays. The push method relies on a length property to determine where to start inserting the give...
...to an array The following code creates the sports array containing two elements, then appends two elements to it. The total variable contains the new length of the array. let sports = ['soccer', 'baseball'] let total = sports.push('football', 'swimming') console.log(sports) // ['soccer', 'baseball', 'football', 'swimming'] console.log(total) // 4 Merging two arrays This example uses apply
() to push all elements from a second array. Do not use this method if the second array (moreVegs in the example) is very large because the maximum number of parameters that one function can take is limited in practice. See apply
() for more details. let vegetables = ['parsnip', 'potato'] let moreVegs = ['celery', 'beetroot'] // Merge the second array into the first one // Equivalent to vegetables...
Array.prototype.splice() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax let arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]]) Parameters start The index at which to start changing the array. If greater than the length of the array, start will be set to the length of the array. In this case, no element will be deleted but the method will behave as an adding function, adding as many element as item[n*] provided. ...
...n all the elements from start to the end of the array will be deleted. Note: In IE8, it won't delete all when deleteCount is omitted. If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element (see below). item1, item2, ... Optional The elements to add to the array, beginning from start. If you do not specify any elements, splice
() will only remove elements from the array. Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. Description If the specified number of elements to insert differs from the number of elements being removed, the array's length will be changed. Examples Remove 0 (zero...
Array.prototype.toSource() - JavaScript
The toSource
() method returns a string representing the source code of the array. Syntax arr.toSource
() Return value A string representing the source code of the array. Description The toSource method returns the following values: For the built-in Array object, toSource returns the following string indicating that the source code is not available: function Array
() { [native code] } For instances of Array, toSource returns a string representing the source code. This method is usually called internally by JavaScript and not explicitly in code. You can call toSource while debugging to examine the contents of an array. ...
...ive code] } For instances of Array, toSource returns a string representing the source code. This method is usually called internally by JavaScript and not explicitly in code. You can call toSource while debugging to examine the contents of an array. Examples Examining the source code of an array To examine the source code of an array: var alpha = new Array('a', 'b', 'c'); alpha.toSource
(); //returns ['a', 'b', 'c'] Specifications Not part of any standard. Implemented in JavaScript 1.3. ...
Array.prototype.toString() - JavaScript
The toString
() method returns a string representing the specified array and its elements. Syntax arr.toString
() Return value A string representing the elements of the array. Description The Array object overrides the toString method of Object. For Array objects, the toString method joins the array and returns one string containing each array element separated by commas. JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ECMAScript 5 semantics Starting in JavaScript 1.8.5 (Firefox 4), and consistent with ECMAScript 5th edition semantics, the toString
() method is generic and can be used with any object. ...
...ment separated by commas. JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ECMAScript 5 semantics Starting in JavaScript 1.8.5 (Firefox 4), and consistent with ECMAScript 5th edition semantics, the toString
() method is generic and can be used with any object. Object.prototype.toString
() will be called, and the resulting value will be returned. Examples Using toString const array1 = [1, 2, 'a', '1a']; console.log(array1.toString
()); // expected output: "1,2,a,1a" Specifications Specification ECMAScript (ECMA-262)The definition of 'Array.prototype.toString' in that specification. ...
Atomics.add() - JavaScript
This atomic operation guarantees that no other write happens until the modified value is written back. 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 Atomics.add(typedArray, index, value) Parameters typedArray An integer typed array. One of Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array. index The position in the typedArray to add a value to. value The number to add. ...
...ray, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array. index The position in the typedArray to add a value to. value The number to add. Return value The old value at the given position (typedArray[index]). Exceptions Throws a TypeError, if typedArray is not one of the allowed integer types. Throws a RangeError, if index is out of bounds in the typedArray. Examples Using add
() const sab = new SharedArrayBuffer(1024); const ta = new Uint8Array(sab); Atomics.add(ta, 0, 12); // returns 0, the old value Atomics.load(ta, 0); // 12 Specifications Specification ECMAScript (ECMA-262)The definition of 'Atomics.add' in that specification. ...
Atomics.and() - JavaScript
This atomic operation guarantees that no other write happens until the modified value is written back. 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 Atomics.and(typedArray, index, value) Parameters typedArray An integer typed array. One of Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array. index The position in the typedArray to compute the bitwise AND. ...
... of bounds in the typedArray. Description The bitwise AND operation only yields 1, if both a and b are 1. The truth table for the AND operation is: a b a & b 0 0 0 0 1 0 1 0 0 1 1 1 For example, a bitwise AND of 5 & 1 results in 0001 which is 1 in decimal. 5 0101 1 0001 ---- 1 0001 Examples Using and
() const sab = new SharedArrayBuffer(1024); const ta = new Uint8Array(sab); ta[0] = 5; Atomics.and(ta, 0, 1); // returns 0, the old value Atomics.load(ta, 0); // 1 Specifications Specification ECMAScript (ECMA-262)The definition of 'Atomics.and' in that specification. ...
Atomics.compareExchange() - JavaScript
It returns the old value at that position whether it was equal to the expected value or not. This atomic operation guarantees that no other write happens until the modified value is written back. 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 Atomics.compareExchange(typedArray, index, expectedValue, replacementValue) Parameters typedArray An integer typed array. ...
...ition in the typedArray to exchange a value. expectedValue The value to check for equality. replacementValue The number to exchange. Return value The old value at the given position (typedArray[index]). Exceptions Throws a TypeError, if typedArray is not one of the allowed integer types. Throws a RangeError, if index is out of bounds in the typedArray. Examples Using compareExchange
() const sab = new SharedArrayBuffer(1024); const ta = new Uint8Array(sab); ta[0] = 7; Atomics.compareExchange(ta, 0, 7, 12); // returns 7, the old value Atomics.load(ta, 0); // 12 Specifications Specification ECMAScript (ECMA-262)The definition of 'Atomics.compareExchange' in that specification. ...
Atomics.exchange() - JavaScript
This atomic operation guarantees that no other write happens between the read of the old value and the write of the new value. 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 Atomics.exchange(typedArray, index, value) Parameters typedArray An integer typed array. One of Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array. index The position in the typedArray to exchange a value. ...
...ray, Uint32Array, BigInt64Array, or BigUint64Array. index The position in the typedArray to exchange a value. value The number to exchange. Return value The old value at the given position (typedArray[index]). Exceptions Throws a TypeError, if typedArray is not one of the allowed integer types. Throws a RangeError, if index is out of bounds in the typedArray. Examples Using exchange
() const sab = new SharedArrayBuffer(1024); const ta = new Uint8Array(sab); Atomics.exchange(ta, 0, 12); // returns 0, the old value Atomics.load(ta, 0); // 12 Specifications Specification ECMAScript (ECMA-262)The definition of 'Atomics.exchange' in that specification. ...
Atomics.store() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Atomics.store(typedArray, index, value) Parameters typedArray An integer typed array. One of Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array. index The position in the typedArray to store a value in. value The number to store. Return value The value that has been stored. ...
...nt16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array. index The position in the typedArray to store a value in. value The number to store. Return value The value that has been stored. Exceptions Throws a TypeError, if typedArray is not one of the allowed integer types. Throws a RangeError, if index is out of bounds in the typedArray. Examples Using store
() var sab = new SharedArrayBuffer(1024); var ta = new Uint8Array(sab); Atomics.store(ta, 0, 12); // 12 Specifications Specification ECMAScript (ECMA-262)The definition of 'Atomics.store' in that specification. ...
Atomics.wait() - JavaScript
It returns a string which is either "ok", "not-equal", or "timed-out". Note: This operation only works with a shared Int32Array and may not be allowed on the main thread. Syntax Atomics.wait(typedArray, index, value[, timeout]) Parameters typedArray A shared Int32Array. index The position in the typedArray to wait on. value The expected value to test. timeout Optional Time to wait in milliseconds. Infinity, if no time is provided. Return value A String which is either "ok", "not-equal", or "timed-out". Exceptions Throws a TypeError, if typedArray is not a shared Int32Array. ...
...position in the typedArray to wait on. value The expected value to test. timeout Optional Time to wait in milliseconds. Infinity, if no time is provided. Return value A String which is either "ok", "not-equal", or "timed-out". Exceptions Throws a TypeError, if typedArray is not a shared Int32Array. Throws a RangeError, if index is out of bounds in the typedArray. Examples Using wait
() Given a shared Int32Array: const sab = new SharedArrayBuffer(1024); const int32 = new Int32Array(sab); A reading thread is sleeping and waiting on location 0 which is expected to be 0. As long as that is true, it will not go on. However, once the writing thread has stored a new value, it will be notified by the writing thread and return the new value (123). Atomics.wait(int32, 0, 0); console...
Boolean() constructor - JavaScript
The Boolean
() constructor is used to create Boolean objects. 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 new Boolean([value]) Parameters value Optional The initial value of the Boolean object. ...
...nteractive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax new Boolean([value]) Parameters value Optional The initial value of the Boolean object. ...
Boolean.prototype.toString() - JavaScript
The toString
() method returns a string representing the specified Boolean object. 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 bool.toString
() Return value A string representing the specified Boolean object. Description The Boolean object overrides the toString method of the Object object; it does not inherit Object.prototype.toString
(). For Boolean objects, the toString method returns a string representation of the object. JavaScript calls the toString
() method automatically when a Boolean is to be represented as a text value or when a Boolean is referred to in a string concatenation. For Boolean...
... the toString method of the Object object; it does not inherit Object.prototype.toString
(). For Boolean objects, the toString method returns a string representation of the object. JavaScript calls the toString
() method automatically when a Boolean is to be represented as a text value or when a Boolean is referred to in a string concatenation. For Boolean objects and values, the built-in toString
() method returns the string "true" or "false" depending on the value of the boolean object. Examples Using toString
() In the following code, flag.toString
() returns "true": var flag = new Boolean(true); var myVar = flag.toString
(); Specifications Specification ECMAScript (ECMA-262)The definition of 'Boolean.prototype.toString' in that specification. ...
Boolean.prototype.valueOf() - JavaScript
The valueOf
() method returns the primitive value of a Boolean object. 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 bool.valueOf
() Return value The primitive value of the given Boolean object Description The valueOf
() method of Boolean returns the primitive value of a Boolean object or literal Boolean as a Boolean data type. This method is usually called internally by JavaScript and not explicitly in code. ...
...s://github.com/mdn/interactive-examples and send us a pull request. Syntax bool.valueOf
() Return value The primitive value of the given Boolean object Description The valueOf
() method of Boolean returns the primitive value of a Boolean object or literal Boolean as a Boolean data type. This method is usually called internally by JavaScript and not explicitly in code. Examples Using valueOf
() x = new Boolean
(); myVar = x.valueOf
(); // assigns false to myVar Specifications Specification ECMAScript (ECMA-262)The definition of 'Boolean.prototype.valueOf' in that specification. ...
DataView.prototype.getBigInt64() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.getBigInt64(byteOffset [, littleEndian]) Parameters byteOffset The offset, in bytes, from the start of the view to read the data from. littleEndian Optional Indicates whether the 64-bit int is stored in little- or big-endian format. If false or undefined, a big-endian value is read. Return value A BigInt. ...
... ...
DataView.prototype.getBigUint64() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.getBigUint64(byteOffset [, littleEndian]) Parameters byteOffset The offset, in bytes, from the start of the view to read the data from. littleEndian Optional Indicates whether the 64-bit int is stored in little- or big-endian format. If false or undefined, a big-endian value is read. Return value A BigInt. ...
...ld read beyond the end of the view. Description There is no alignment constraint; multi-byte values may be fetched from any offset. Examples Using the getBigUint64 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.getBigUint64(0); // 0n Specifications Specification ECMAScript (ECMA-262)The definition of 'DataView.prototype.getBigUint64
()' in that specification. ...
DataView.prototype.setBigInt64() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.setBigInt64(byteOffset, value [, littleEndian]) Parameters byteOffset The offset, in bytes, from the start of the view to store the data from. value The value to set as a BigInt. The highest possible value that fits in a signed 64-bit integer is 2n ** (64n -1n) - 1n (9223372036854775807n). Upon overflow, it will be negative (-9223372036854775808n). ...
... ...
DataView.prototype.setBigUint64() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.setBigUint64(byteOffset, value [, littleEndian]) Parameters byteOffset The offset, in bytes, from the start of the view to store the data from. value The value to set as a BigInt. The highest possible value that fits in an unsigned 64-bit integer is 2n ** 64n - 1n (18446744073709551615n). Upon overflow, it will be zero (0n). ...
... ...
Date.prototype.getDate() - JavaScript
The getDate
() method returns the day of the month for the specified date according to local time. 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 dateObj.getDate
() Return value An integer number, between 1 and 31, representing the day of the month for the given date according to local time. Examples Using getDate
() The second statement below assigns the value 25 to the variable day, based on the value of the Date object Xmas95. ...
...nd us a pull request. Syntax dateObj.getDate
() Return value An integer number, between 1 and 31, representing the day of the month for the given date according to local time. Examples Using getDate
() The second statement below assigns the value 25 to the variable day, based on the value of the Date object Xmas95. var Xmas95 = new Date('December 25, 1995 23:15:30'); var day = Xmas95.getDate
(); console.log(day); // 25 Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.getDate' in that specification. ...
Date.prototype.getFullYear() - JavaScript
The getFullYear
() method returns the year of the specified date according to local time. Use this method instead of the getYear
() method. 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 dateObj.getFullYear
() Return value A number corresponding to the year of the given date, according to local time. Description The value returned by getFullYear
() is an absolute number. For dates between the years 1000 and 9999, getFullYear
() returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000. ...
...ax dateObj.getFullYear
() Return value A number corresponding to the year of the given date, according to local time. Description The value returned by getFullYear
() is an absolute number. For dates between the years 1000 and 9999, getFullYear
() returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000. Examples Using getFullYear
() The following example assigns the four-digit value of the current year to the variable year. var today = new Date
(); var year = today.getFullYear
(); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.getFullYear' in that specification. ...
Date.prototype.getHours() - JavaScript
The getHours
() method returns the hour for the specified date, according to local time. 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 dateObj.getHours
() Return value An integer number, between 0 and 23, representing the hour for the given date according to local time. Examples Using getHours
() The second statement below assigns the value 23 to the variable hours, based on the value of the Date object Xmas95. ...
...nd send us a pull request. Syntax dateObj.getHours
() Return value An integer number, between 0 and 23, representing the hour for the given date according to local time. Examples Using getHours
() The second statement below assigns the value 23 to the variable hours, based on the value of the Date object Xmas95. let Xmas95 = new Date('December 25, 1995 23:15:30'); let hours = Xmas95.getHours
(); console.log(hours); // 23 Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.getHours' in that specification. ...
Date.prototype.getMilliseconds() - JavaScript
The getMilliseconds
() method returns the milliseconds in the specified date according to local time. 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 dateObj.getMilliseconds
() Return value A number, between 0 and 999, representing the milliseconds for the given date according to local time. ...
...e for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dateObj.getMilliseconds
() Return value A number, between 0 and 999, representing the milliseconds for the given date according to local time. Examples Using getMilliseconds
() The following example assigns the milliseconds portion of the current time to the variable milliseconds: var today = new Date
(); var milliseconds = today.getMilliseconds
(); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.getMilliseconds' in that specification. ...
Date.prototype.getMonth() - JavaScript
The getMonth
() method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year). 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 dateObj.getMonth
() Return value An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. Examples Using getMonth
() The second statement below assigns the value 11 to the variable month, based on the value of the Date object Xmas95. var Xmas95 = new Date('December 25, 1995 23:15:30'); var month = Xma...
...
() Return value An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. Examples Using getMonth
() The second statement below assigns the value 11 to the variable month, based on the value of the Date object Xmas95. var Xmas95 = new Date('December 25, 1995 23:15:30'); var month = Xmas95.getMonth
(); console.log(month); // 11 Note: If needed, the full name of a month ("January" for example) can be obtained by using Intl.DateTimeFormat
() with an options parameter. Using this method, internationalization is made easier: var options = { month: 'long'}; console.log(new Intl.DateTimeFormat('en-US', options).format(Xmas95)); // December console.log(new Intl.DateTimeFormat('de-DE', options).fo...
Date.prototype.getSeconds() - JavaScript
The getSeconds
() method returns the seconds in the specified date according to local time. 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 dateObj.getSeconds
() Return value An integer number, between 0 and 59, representing the seconds in the given date according to local time. Examples Using getSeconds
() The second statement below assigns the value 30 to the variable seconds, based on the value of the Date object Xmas95. ...
... pull request. Syntax dateObj.getSeconds
() Return value An integer number, between 0 and 59, representing the seconds in the given date according to local time. Examples Using getSeconds
() The second statement below assigns the value 30 to the variable seconds, based on the value of the Date object Xmas95. var Xmas95 = new Date('December 25, 1995 23:15:30'); var seconds = Xmas95.getSeconds
(); console.log(seconds); // 30 Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.getSeconds' in that specification. ...
Date.prototype.getUTCDay() - JavaScript
The getUTCDay
() method returns the day of the week in the specified date according to universal time, where 0 represents Sunday. 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 dateObj.getUTCDay
() Return value An integer number corresponding to the day of the week for the given date, according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Examples Using getUTCDay
() The following example assigns the weekday portion of the current date to the variable weekday. ...
...dn/interactive-examples and send us a pull request. Syntax dateObj.getUTCDay
() Return value An integer number corresponding to the day of the week for the given date, according to universal time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Examples Using getUTCDay
() The following example assigns the weekday portion of the current date to the variable weekday. var today = new Date
(); var weekday = today.getUTCDay
(); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.getUTCDay' in that specification. ...
Date.prototype.getUTCFullYear() - JavaScript
The getUTCFullYear
() method returns the year in the specified date according to universal time. 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 dateObj.getUTCFullYear
() Return value A number representing the year in the given date according to universal time. Description The value returned by getUTCFullYear
() is an absolute number that is compliant with year-2000, for example, 1995. Examples Using getUTCFullYear
() The following example assigns the four-digit value of the current year to the variable year. ...
...tax dateObj.getUTCFullYear
() Return value A number representing the year in the given date according to universal time. Description The value returned by getUTCFullYear
() is an absolute number that is compliant with year-2000, for example, 1995. Examples Using getUTCFullYear
() The following example assigns the four-digit value of the current year to the variable year. var today = new Date
(); var year = today.getUTCFullYear
(); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.getUTCFullYear' in that specification. ...
Date.prototype.getUTCMilliseconds() - JavaScript
The getUTCMilliseconds
() method returns the milliseconds portion of the time object's value. Syntax dateObj.getUTCMilliseconds
() Return value An integer number, between 0 and 999, representing the milliseconds portion of the given date object. This method is a companion to the other UTC based methods that give hour portion, minute portion, etc.; this method gives milliseconds portion. Not to be confused with Unix epoch time. To get total milliseconds since 1970/01/01, use the method ".getTime
()". Examples Using getUTCMilliseconds
() The following example assigns the milliseconds portion of the current time to the variable milliseconds. ...
...to the other UTC based methods that give hour portion, minute portion, etc.; this method gives milliseconds portion. Not to be confused with Unix epoch time. To get total milliseconds since 1970/01/01, use the method ".getTime
()". Examples Using getUTCMilliseconds
() The following example assigns the milliseconds portion of the current time to the variable milliseconds. var today = new Date
(); var milliseconds = today.getUTCMilliseconds
(); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.getUTCMilliseconds' in that specification. ...
Date.prototype.getUTCMonth() - JavaScript
The getUTCMonth
() returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year). 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 dateObj.getUTCMonth
() Return value An integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for January, 1 for February, 2 for March, and so on. Examples Using getUTCMonth
() The following example assigns the month portion of the current date to the variable month. ...
...active-examples and send us a pull request. Syntax dateObj.getUTCMonth
() Return value An integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for January, 1 for February, 2 for March, and so on. Examples Using getUTCMonth
() The following example assigns the month portion of the current date to the variable month. var today = new Date
(); var month = today.getUTCMonth
(); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.getUTCMonth' in that specification. ...
Date.now() - JavaScript
The static Date.now
() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC. Syntax var timeInMs = Date.now
(); Return value A Number representing the milliseconds elapsed since the UNIX epoch. Polyfill This method was standardized in ECMA-262 5th edition. Engines which have not been updated to support this method can work around the absence of this method using the following shim: if (!Date.now) { Date.now = function now
() { return new Date
().getTime
(); }; } Examples Reduced time precision To offer protection against timing attacks and fingerprinting, the precision of Date.now
() might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecision preference is enabled by default and defaults to 20us in Firefox 5...
...n new Date
().getTime
(); }; } Examples Reduced time precision To offer protection against timing attacks and fingerprinting, the precision of Date.now
() might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecision preference is enabled by default and defaults to 20us in Firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in Firefox 60 Date.now
() // 1519211809934 // 1519211810362 // 1519211811670 // ... // reduced time precision with `privacy.resistFingerprinting` enabled Date.now
(); // 1519129853500 // 1519129858900 // 1519129864400 // ... In Firefox, you can also enable privacy.resistFingerprinting, the precision will be 100ms or the value of privacy.resistFingerprinting.reduceTimerPrecision.microseconds, whichever is larger. Spec...
Date.prototype.setDate() - JavaScript
The setDate
() method sets the day of the Date object relative to the beginning of the currently set month. 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 dateObj.setDate(dayValue) Parameters dayValue An integer representing the day of the month. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the Date object is also changed in place). Description If the dayValue is outside of the range of date values for the month, setDate
() will update the Date object accordingly. For example, if 0 is provided for dayValue, the date will be set to the last day of...
... setDate
() will update the Date object accordingly. For example, if 0 is provided for dayValue, the date will be set to the last day of the previous month. If a negative number is provided for dayValue, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ...
Date.prototype.setMilliseconds() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dateObj.setMilliseconds(millisecondsValue) Parameters millisecondsValue A number between 0 and 999, representing the milliseconds. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If you specify a number outside the expected range, the date information in the Date object is updated accordingly. ...
...nting the milliseconds. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If you specify a number outside the expected range, the date information in the Date object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds. Examples Using setMilliseconds
() var theBigDay = new Date
(); theBigDay.setMilliseconds(100); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.setMilliseconds' in that specification. ...
Date.prototype.setTime() - JavaScript
The setTime
() method sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. 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 dateObj.setTime(timeValue) Parameters timeValue An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument). Description Use the setTime
() method to help assign a date and time to another Date object. ...
...dateObj.setTime(timeValue) Parameters timeValue An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument). Description Use the setTime
() method to help assign a date and time to another Date object. Examples Using setTime
() var theBigDay = new Date('July 1, 1999'); var sameAsBigDay = new Date
(); sameAsBigDay.setTime(theBigDay.getTime
()); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.setTime' in that specification. ...
Date.prototype.setUTCDate() - JavaScript
The setUTCDate
() method sets the day of the month for a specified date according to universal time. 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 dateObj.setUTCDate(dayValue) Parameters dayValue An integer from 1 to 31, representing the day of the month. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If a parameter you specify is outside of the expected range, setUTCDate
() attempts to update the date information in the Date object accordingly. For example, if you use 40 for dayValue, and the month stored in the Date object is June, ...
...1 January 1970 00:00:00 UTC and the updated date. Description If a parameter you specify is outside of the expected range, setUTCDate
() attempts to update the date information in the Date object accordingly. For example, if you use 40 for dayValue, and the month stored in the Date object is June, the day will be changed to 10 and the month will be incremented to July. Examples Using setUTCDate
() var theBigDay = new Date
(); theBigDay.setUTCDate(20); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.setUTCDate' in that specification. ...
Date.prototype.setUTCMilliseconds() - JavaScript
The setUTCMilliseconds
() method sets the milliseconds for a specified date according to universal time. 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 dateObj.setUTCMilliseconds(millisecondsValue) Parameters millisecondsValue A number between 0 and 999, representing the milliseconds. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If a parameter you specify is outside of the expected range, setUTCMilliseconds
() attempts to update the date information in the Date object accordingly. For example, if you use 1100 for millisecondsValue, t...
...y 1970 00:00:00 UTC and the updated date. Description If a parameter you specify is outside of the expected range, setUTCMilliseconds
() attempts to update the date information in the Date object accordingly. For example, if you use 1100 for millisecondsValue, the seconds stored in the Date object will be incremented by 1, and 100 will be used for milliseconds. Examples Using setUTCMilliseconds
() var theBigDay = new Date
(); theBigDay.setUTCMilliseconds(500); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.setUTCMilliseconds' in that specification. ...
Date.prototype.setYear() - JavaScript
The setYear
() method sets the year for a specified date according to local time. Because setYear
() does not set full years ("year 2000 problem"), it is no longer used and has been replaced by the setFullYear
() method. Syntax dateObj.setYear(yearValue) Parameters yearValue An integer. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If yearValue is a number between 0 and 99 (inclusive), then the year for dateObj is set to 1900 + yearValue. Otherwise, the year for dateObj is set to yearValue. Examples Using setYear
() The first two lines set the year to 1996. The third sets the year to 2000. ...
...urn value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If yearValue is a number between 0 and 99 (inclusive), then the year for dateObj is set to 1900 + yearValue. Otherwise, the year for dateObj is set to yearValue. Examples Using setYear
() The first two lines set the year to 1996. The third sets the year to 2000. var theBigDay = new Date
(); theBigDay.setYear(96); theBigDay.setYear(1996); theBigDay.setYear(2000); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.setYear' in that specification. ...
Date.prototype.toGMTString() - JavaScript
The toGMTString
() method converts a date to a string, using Internet Greenwich Mean Time (GMT) conventions. The exact format of the value returned by toGMTString
() varies according to the platform and browser, in general it should represent a human readable date string. Note: toGMTString
() is deprecated and should no longer be used. It remains implemented only for backward compatibility; please use toUTCString
() instead. Syntax dateObj.toGMTString
() Return value A string representing the given date following the Internet Greenwich Mean Time (GMT) convention. Examples Simple example In this example, the toGMTString
() method converts the date to GMT (UTC) using the operating system's time-zone offset and returns a string value that is similar to the following form. The exact forma...
...GMTString
() Return value A string representing the given date following the Internet Greenwich Mean Time (GMT) convention. Examples Simple example In this example, the toGMTString
() method converts the date to GMT (UTC) using the operating system's time-zone offset and returns a string value that is similar to the following form. The exact format depends on the platform. var today = new Date
(); var str = today.toGMTString
(); // deprecated! use toUTCString
() console.log(str); // Mon, 18 Dec 1995 17:28:35 GMT Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.toGMTString' in that specification. ...
Date.prototype.toJSON() - JavaScript
The toJSON
() method returns a string representation of the Date object. 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 dateObj.toJSON
() Return value A string representation of the given date. Description Date instances refer to a specific point in time. Calling toJSON
() returns a string (using toISOString
()) representing the Date object's value. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization. ...
...d send us a pull request. Syntax dateObj.toJSON
() Return value A string representation of the given date. Description Date instances refer to a specific point in time. Calling toJSON
() returns a string (using toISOString
()) representing the Date object's value. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization. Examples Using toJSON
() var jsonDate = (new Date
()).toJSON
(); var backToDate = new Date(jsonDate); console.log(jsonDate); //2015-10-26T07:46:36.611Z Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.toJSON' in that specification. ...
Date.prototype.toUTCString() - JavaScript
The toUTCString
() method converts a date to a string, using the UTC time zone. Based on rfc7231 and modified according to ecma-262 toUTCString, it can have negative values in the 2021 version 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 dateObj.toUTCString
() Return value A string representing the given date using the UTC time zone. Description The value returned by toUTCString
() is a string in the form Www, dd Mmm yyyy hh:mm:ss GMT, Where: Format Sring Description Www Day of week, as three letters (e.g. Sun, Mon, ...) dd Day of month, as two digits with lead...
...if required mm Minute, as two digits with leading zero if required ss Seconds, as two digits with leading zero if required Prior to ECMAScript 2018, the format of the return value varied according to the platform. The most common return value was an RFC-1123 formatted date stamp, which is a slightly updated version of RFC-822 date stamps. Examples Using toUTCString
() let today = new Date('Wed, 14 Jun 2017 00:00:00 PDT'); let UTCstring = today.toUTCString
(); // Wed, 14 Jun 2017 07:00:00 GMT Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.toUTCString' in that specification. ...
FinalizationRegistry.prototype.unregister() - JavaScript
se` when you're done with it. * * @param label A label for the `Thingy`. */ constructor(label) { // vvvvv----- held value this.#registry.register(this, label, this); // target -----^^^^ ^^^^----- unregister token } /** * Releases resources held by this `Thingy` instance. ...
...filename The name of the file. */ constructor(filename) { this.#file = File.open(filename); // vvvvv----- held value this.#registry.register(this, label, this.#file); // target -----^^^^ ^^^^^^^^^^----- unregister token } /** * Releases resources held by this `Thingy` instance. */ release
() { if (this.#file) { this.#registry.unregister(this.#file); // ^^^^^^^^^^----- unregister token File.close(this.#file); this.#file = null; } } } Specifications Specification WeakRefsThe definition of 'FinalizationRegistry.prototype.unregister' in that specification. ...
Function.prototype.toSource() - JavaScript
The toSource
() method returns a string representing the source code of the object. This method is usually called internally by JavaScript and not explicitly in code. You can call toSource
() while debugging to examine the contents of an object. Syntax function.toSource
(); Return value A string representing the source code of the object. Examples Native functions For the built-in Function object, toSource
() returns the following string indicating that the source code is not available: function Function
() { [native code] } Custom functions For custom functions, toSource
() returns the JavaScript source that defines the object as a string. ...
... A string representing the source code of the object. Examples Native functions For the built-in Function object, toSource
() returns the following string indicating that the source code is not available: function Function
() { [native code] } Custom functions For custom functions, toSource
() returns the JavaScript source that defines the object as a string. // For example: function hello
() { console.log("Hello, World!"); } hello.toSource
(); // Results in: "function hello
() { console.log(\"Hello, World!\"); }" Specifications Not part of any standard. ...
Intl.RelativeTimeFormat() constructor - JavaScript
Syntax new Intl.RelativeTimeFormat([locales[, options]]) Parameters locales Optional. A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the Intl page. options Optional. An object with some or all of the following properties: localeMatcher The locale matching algorithm to use. Possible values are "lookup" and "best fit"; the default is "best fit". For information about this option, see Intl. numeric The format of output message. Possible values are: "always" (default, e.g., 1 day ago), or "auto" (e.g., yesterday). ...
... Stage 4 ...
Intl.RelativeTimeFormat.prototype.format() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax relativeTimeFormat.format(value, unit) Parameters value Numeric value to use in the internationalized relative time message. unit Unit to use in the relative time internationalized message. Possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". Plural forms are also permitted. ...
... Stage 4 ...
Intl.RelativeTimeFormat.prototype.formatToParts() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax RelativeTimeFormat.formatToParts(value, unit) Parameters value Numeric value to use in the internationalized relative time message. unit Unit to use in the relative time internationalized message. Possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". ...
... Stage 4 ...
Intl.RelativeTimeFormat.prototype.resolvedOptions() - JavaScript
The Intl.RelativeTimeFormat.prototype.resolvedOptions
() method returns a new object with properties reflecting the locale and relative time formatting options computed during initialization of this RelativeTimeFormat object. 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 relativeTimeFormat.resolvedOptions
() Return value A new object with properties reflecting the locale and number formatting options computed during the initialization of the given RelativeTimeFormat object. Description The resulting object has the following properties: locale The BCP 47 language tag for the locale actually used. If...
... values are: "always" (default, e.g., 1 day ago), or "auto" (e.g., yesterday). The "auto" value allows to not always have to use numeric values in the output. numberingSystem The value requested using the Unicode extension key "nu" or filled in as a default. Examples Using the resolvedOptions method var de = new Intl.RelativeTimeFormat('de-DE'); var usedOptions = de.resolvedOptions
(); usedOptions.locale; // "de-DE" usedOptions.style; // "long" usedOptions.numeric; // "always" usedOptions.numberingSystem; // "latn" Specifications Specification Status Comment ECMAScript Internationalization API (ECMA-402)The definition of 'RelativeTimeFormat.resolvedOptions
()' in that specification. Stage 4 ...
Intl.RelativeTimeFormat.supportedLocalesOf() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Intl.RelativeTimeFormat.supportedLocalesOf(locales[, options]) Parameters locales A string with a BCP 47 language tag, or an array of such strings. For the general form of the locales argument, see the Intl page. options Optional. ...
...tag as well. const locales = ['ban', 'id-u-co-pinyin', 'de-ID']; const options = { localeMatcher: 'lookup' }; console.log(Intl.RelativeTimeFormat.supportedLocalesOf(locales, options).join(', ')); // -> "id-u-co-pinyin, de-ID" Specifications Specification Status Comment ECMAScript Internationalization API (ECMA-402)The definition of 'RelativeTimeFormat.supportedLocalesOf
()' in that specification. Stage 4 ...
Map.prototype.delete() - JavaScript
Successfully removed. myMap.has('bar'); // Returns false. The "bar" element is no longer present. ...
.... 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 myMap.delete(key); Parameters key The key of the element to remove from the Map object. Return value true if an element in the Map object existed and has been removed, or false if the element does not exist. Examples Using delete
() var myMap = new Map
(); myMap.set('bar', 'foo'); myMap.delete('bar'); // Returns true. Successfully removed. myMap.has('bar'); // Returns false. The "bar" element is no longer present. Specifications Specification ECMAScript (ECMA-262)The definition of 'Map.prototype.delete' in that specification. ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Map.
Map.prototype.get() - JavaScript
The get
() method returns a specified element from a Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map object. 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 myMap.get(key) Parameters key The key of the element to return from the Map object. Return value The element associated with the specified key, or undefined if the key can't be found in the Map object. ...
...epository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax myMap.get(key) Parameters key The key of the element to return from the Map object. Return value The element associated with the specified key, or undefined if the key can't be found in the Map object. Examples Using get
() let myMap = new Map
(); myMap.set('bar', 'foo'); myMap.get('bar'); // Returns "foo" myMap.get('baz'); // Returns undefined Specifications Specification ECMAScript (ECMA-262)The definition of 'Map.prototype.get' in that specification. ...
Map.prototype.has() - JavaScript
The has
() method returns a boolean indicating whether an element with the specified key exists or not. 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 myMap.has(key) Parameters key The key of the element to test for presence in the Map object. Return value true if an element with the specified key exists in the Map object; otherwise false. ...
... 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 myMap.has(key) Parameters key The key of the element to test for presence in the Map object. Return value true if an element with the specified key exists in the Map object; otherwise false. Examples Using has
() let myMap = new Map
() myMap.set('bar', "foo") myMap.has('bar') // returns true myMap.has('baz') // returns false Specifications Specification ECMAScript (ECMA-262)The definition of 'Map.prototype.has' in that specification. ...
Map.prototype.keys() - JavaScript
The keys
() method returns a new Iterator object that contains the keys for each element in the Map object in insertion order. 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 myMap.keys
() Return value A new Map iterator object. ...
...or object that contains the keys for each element in the Map object in insertion order. 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 myMap.keys
() Return value A new Map iterator object. Examples Using keys
() var myMap = new Map
(); myMap.set('0', 'foo'); myMap.set(1, 'bar'); myMap.set({}, 'baz'); var mapIter = myMap.keys
(); console.log(mapIter.next
().value); // "0" console.log(mapIter.next
().value); // 1 console.log(mapIter.next
().value); // Object Specifications Specification ECMAScript (ECMA-262)The definition of 'Map.prototype.keys' in that specification. ...
Map.prototype.set() - JavaScript
The set
() method adds or updates an element with a specified key and a value to a Map object. 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 myMap.set(key, value) Parameters key The key of the element to add to the Map object. value The value of the element to add to the Map object. Return value The Map object. ...
...mple 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 myMap.set(key, value) Parameters key The key of the element to add to the Map object. value The value of the element to add to the Map object. Return value The Map object. Examples Using set
() let myMap = new Map
() // Add new elements to the map myMap.set('bar', 'foo') myMap.set(1, 'foobar') // Update an element in the map myMap.set('bar', 'baz') Using the set
() with chaining Since the set
() method returns back the same Map object, you can chain the method call like below: // Add new elements to the map with chaining. myMap.set('bar', 'foo') .set(1, 'foobar') .set(2, '...
Map.prototype.values() - JavaScript
The values
() method returns a new Iterator object that contains the values for each element in the Map object in insertion order. 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 myMap.values
() Return value A new Map iterator object. ...
...ect that contains the values for each element in the Map object in insertion order. 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 myMap.values
() Return value A new Map iterator object. Examples Using values
() var myMap = new Map
(); myMap.set('0', 'foo'); myMap.set(1, 'bar'); myMap.set({}, 'baz'); var mapIter = myMap.values
(); console.log(mapIter.next
().value); // "foo" console.log(mapIter.next
().value); // "bar" console.log(mapIter.next
().value); // "baz" Specifications Specification ECMAScript (ECMA-262)The definition of 'Map.prototype.values' in that specification. ...
Math.asinh() - JavaScript
The Math.asinh
() function returns the hyperbolic arcsine of a number, that is Math.asinh(x)=arsinh(x)= the unique ysuch thatsinh(y)=x\mathtt{\operatorname{Math.asinh}(x)} = \operatorname{arsinh}(x) = \text{ the unique } \; y \; \text{such that} \; \sinh(y) = x The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.asinh(x) Parameters x A number. Return value The hyperbolic arcsine of the given number. Description Because asinh
() is a static method of Math, you always use it as Math.asinh
(), rather than as a method of a Math object you created (Math is not a constructor). Polyfill Math.asinh can ...
... ...
Math.cbrt() - JavaScript
The Math.cbrt
() function returns the cube root of a number, that is Math.cbrt(x)=x3=the uniqueysuch thaty3=x\mathtt{Math.cbrt(x)} = \sqrt[3]{x} = \text{the unique} \; y \; \text{such that} \; y^3 = x The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.cbrt(x) Parameters x A number. Return value The cube root of the given number. Description Because cbrt
() is a static method of Math, you always use it as Math.cbrt
(), rather than as a method of a Math object you created (Math is not a constructor). Polyfill For all x>=0x \geq 0, have x3=x1/3\sqrt[3]{x} = x^{1/3} so this can be emulated by the f...
...ctor). Polyfill For all x>=0x \geq 0, have x3=x1/3\sqrt[3]{x} = x^{1/3} so this can be emulated by the following function: if (!Math.cbrt) { Math.cbrt = (function(pow) { return function cbrt(x){ // ensure negative numbers remain negative: return x < 0 ? -pow(-x, 1/3) : pow(x, 1/3); }; })(Math.pow); // localize Math.pow to increase efficiency } Examples Using Math.cbrt
() Math.cbrt(NaN); // NaN Math.cbrt(-1); // -1 Math.cbrt(-0); // -0 Math.cbrt(-Infinity); // -Infinity Math.cbrt(0); // 0 Math.cbrt(1); // 1 Math.cbrt(Infinity); // Infinity Math.cbrt(null); // 0 Math.cbrt(2); // 1.2599210498948732 Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.cbrt' in that specification. ...
Math.exp() - JavaScript
The Math.exp
() function returns ex, where x is the argument, and e is Euler's number (also known as Napier's constant), the base of the natural logarithms. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.exp(x) Parameters x A number. Return value A number representing ex, where e is Euler's number and x is the argument. Description Because exp
() is a static method of Math, you always use it as Math.exp
(), rather than as a method of a Math object you created (Math is not a constructor). ...
...github.com/mdn/interactive-examples and send us a pull request. Syntax Math.exp(x) Parameters x A number. Return value A number representing ex, where e is Euler's number and x is the argument. Description Because exp
() is a static method of Math, you always use it as Math.exp
(), rather than as a method of a Math object you created (Math is not a constructor). Examples Using Math.exp
() Math.exp(-1); // 0.36787944117144233 Math.exp(0); // 1 Math.exp(1); // 2.718281828459045 Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.exp' in that specification. ...
Math.expm1() - JavaScript
The Math.expm1
() function returns ex - 1, where x is the argument, and e the base of the natural logarithms. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.expm1(x) Parameters x A number. Return value A number representing ex - 1, where e is Euler's number and x is the argument. Description Because expm1
() is a static method of Math, you always use it as Math.expm1
(), rather than as a method of a Math object you created (Math is not a constructor). ...
... a pull request. Syntax Math.expm1(x) Parameters x A number. Return value A number representing ex - 1, where e is Euler's number and x is the argument. Description Because expm1
() is a static method of Math, you always use it as Math.expm1
(), rather than as a method of a Math object you created (Math is not a constructor). Polyfill This can be emulated with the help of the Math.exp
() function: Math.expm1 = Math.expm1 || function(x) { return Math.exp(x) - 1; }; Examples Using Math.expm1
() Math.expm1(-1); // -0.6321205588285577 Math.expm1(0); // 0 Math.expm1(1); // 1.718281828459045 Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.expm1' in that specification. ...
Math.round() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.round(x) Parameters x A number. Return value The value of the given number rounded to the nearest integer. Description If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. ...
...tion If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +?. Note that this differs from many languages' round
() functions, which often round this case to the next integer away from zero, instead giving a different result in the case of negative numbers with a fractional part of exactly 0.5. Because round
() is a static method of Math, you always use it as Math.round
(), rather than as a method of a Math object you created (Math has no constructor). Examples Using round Math.round( 20.49); // 20 Math.rou...
Math.sin() - JavaScript
The Math.sin
() function returns the sine of a number. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.sin(x) Parameters x A number (given in radians). Return value The sine of the given number. Description The Math.sin
() method returns a numeric value between -1 and 1, which represents the sine of the angle given in radians. Because sin
() is a static method of Math, you always use it as Math.sin
(), rather than as a method of a Math object you created (Math is not a constructor). ...
... x A number (given in radians). Return value The sine of the given number. Description The Math.sin
() method returns a numeric value between -1 and 1, which represents the sine of the angle given in radians. Because sin
() is a static method of Math, you always use it as Math.sin
(), rather than as a method of a Math object you created (Math is not a constructor). Examples Using Math.sin
() Math.sin(0); // 0 Math.sin(1); // 0.8414709848078965 Math.sin(Math.PI / 2); // 1 Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.sin' in that specification. ...
Math.tan() - JavaScript
The Math.tan
() function returns the tangent of a number. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.tan(x) Parameters x A number representing an angle in radians. Return value The tangent of the given number. Description The Math.tan
() method returns a numeric value that represents the tangent of the angle. Because tan
() is a static method of Math, you always use it as Math.tan
(), rather than as a method of a Math object you created (Math is not a constructor). ...
...n(x) Parameters x A number representing an angle in radians. Return value The tangent of the given number. Description The Math.tan
() method returns a numeric value that represents the tangent of the angle. Because tan
() is a static method of Math, you always use it as Math.tan
(), rather than as a method of a Math object you created (Math is not a constructor). Examples Using Math.tan
() Math.tan(1); // 1.5574077246549023 Because the Math.tan
() function accepts radians, but it is often easier to work with degrees, the following function accepts a value in degrees, converts it to radians and returns the tangent. function getTanDeg(deg) { var rad = deg * Math.PI/180; return Math.tan(rad); } Specifications Specification ECMAScript (ECMA-262)The definitio...
Number.isFinite() - JavaScript
This means only values of the type number, that are also finite, return true. ...
...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 Number.isFinite(value) Parameters value The value to be tested for finiteness. Return value A Boolean indicating whether or not the given value is a finite number. Description In comparison to the global isFinite
() function, this method doesn't forcibly convert the parameter to a number. This means only values of the type number, that are also finite, return true. Polyfill if (Number.isFinite === undefined) Number.isFinite = function(value) { return typeof value === 'number' && isFinite(value); } Examples Using isFinite Number.isFinite(Infinity); // false Number.isFinite(NaN); // false Num...
Number.parseFloat() - JavaScript
If a number cannot be parsed from the argument, it returns NaN. 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 Number.parseFloat(string) Parameters string The value to parse. If this argument is not a string, then it is converted to one using the ToString abstract operation. Leading whitespace in this argument is ignored. Return value A floating point number parsed from the given string. Or NaN when the first non-whitespace character cannot be converted to a number. ...
...ation. Leading whitespace in this argument is ignored. Return value A floating point number parsed from the given string. Or NaN when the first non-whitespace character cannot be converted to a number. Polyfill if (Number.parseFloat === undefined) { Number.parseFloat = parseFloat; } Examples Number.parseFloat vs parseFloat This method has the same functionality as the global parseFloat
() function: Number.parseFloat === parseFloat; // true This method is also part of ECMAScript 2015. (Its purpose is modularization of globals.) See parseFloat
() for more detail and examples. Specifications Specification ECMAScript (ECMA-262)The definition of 'Number.parseFloat' in that specification. ...
Number.parseInt() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Number.parseInt(string,[ radix]) Parameters string The value to parse. If this argument is not a string, then it is converted to one using the ToString abstract operation. Leading whitespace in this argument is ignored. radix Optional An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. ...
...ault to 10! Return value An integer parsed from the given string. If the radix is smaller than 2 or bigger than 36, and the first non-whitespace character cannot be converted to a number, NaN is returned. Polyfill if (Number.parseInt === undefined) { Number.parseInt = window.parseInt } Examples Number.parseInt vs parseInt This method has the same functionality as the global parseInt
() function: Number.parseInt === parseInt // true and is part of ECMAScript 2015 (its purpose is modularization of globals). Please see parseInt
() for more detail and examples. Specifications Specification ECMAScript (ECMA-262)The definition of 'Number.parseInt' in that specification. ...
Number.prototype.valueOf() - JavaScript
The valueOf
() method returns the wrapped primitive value of a Number object. 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 numObj.valueOf
() Return value A number representing the primitive value of the specified Number object. Description This method is usually called internally by JavaScript and not explicitly in web code. ...
...://github.com/mdn/interactive-examples and send us a pull request. Syntax numObj.valueOf
() Return value A number representing the primitive value of the specified Number object. Description This method is usually called internally by JavaScript and not explicitly in web code. Examples Using valueOf let numObj = new Number(10) console.log(typeof numObj) // object let num = numObj.valueOf
() console.log(num) // 10 console.log(typeof num) // number Specifications Specification ECMAScript (ECMA-262)The definition of 'Number.prototype.valueOf' in that specification. ...
Object.prototype.__defineSetter__() - JavaScript
However, as it is widely implemented and used on the Web, it is very unlikely that browsers will stop implementing it. The __defineSetter__ method binds an object's property to a function to be called when an attempt is made to set that property. Syntax obj.__defineSetter__(prop, fun) Parameters prop A string containing the name of the property to be bound to the given function. fun A function to be called when there is an attempt to set the specified property. This function takes the form function(val) { . . . ...
... ...
Object.prototype.__lookupSetter__() - JavaScript
he specified property. Description If a setter has been defined for an object's property, it was not possible to reference the setter function through that property, because that property refers to the return value of that function. __lookupSetter__ can be used to obtain a reference to the setter function. It is now possible to do this in a standardized way using Object.getOwnPropertyDescriptor
(). Examples Standard-compliant and non-standard ways to get a property setter var obj = { set foo(value) { this.bar = value; } }; // Non-standard and deprecated way obj.__lookupSetter__('foo') // (function(value) { this.bar = value; }) // Standard-compliant way Object.getOwnPropertyDescriptor(obj, 'foo').set; // (function(value) { this.bar = value; }) Specifications Speci...
... ...
Object.getOwnPropertySymbols() - JavaScript
The Object.getOwnPropertySymbols
() method returns an array of all symbol properties found directly upon a given object. 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 Object.getOwnPropertySymbols(obj) Parameters obj The object whose symbol properties are to be returned. Return value An array of all symbol properties found directly upon the given object. Description Similar to Object.getOwnPropertyNames
(), you can get all symbol properties of a given object as an array of symbols. ...
...nd send us a pull request. Syntax Object.getOwnPropertySymbols(obj) Parameters obj The object whose symbol properties are to be returned. Return value An array of all symbol properties found directly upon the given object. Description Similar to Object.getOwnPropertyNames
(), you can get all symbol properties of a given object as an array of symbols. Note that Object.getOwnPropertyNames
() itself does not contain the symbol properties of an object and only the string properties. As all objects have no own symbol properties initially, Object.getOwnPropertySymbols
() returns an empty array unless you have set symbol properties on your object. Examples Using getOwnPropertySymbols var obj = {}; var a = Symbol('a'); var b = Symbol.for('b'); obj[a] = 'localSymbol'; obj[b] = 'globalSy...
Object.isExtensible() - JavaScript
The Object.isExtensible
() method determines if an object is extensible (whether it can have new properties added to it). 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 Object.isExtensible(obj) Parameters obj The object which should be checked. Return value A Boolean indicating whether or not the given object is extensible. Description Objects are extensible by default: they can have new properties added to them, and (in engines that support __proto__) their __proto__ property can be modified. ...
...ensible(obj) Parameters obj The object which should be checked. Return value A Boolean indicating whether or not the given object is extensible. Description Objects are extensible by default: they can have new properties added to them, and (in engines that support __proto__) their __proto__ property can be modified. An object can be marked as non-extensible using Object.preventExtensions
(), Object.seal
(), or Object.freeze
(). Examples Using Object.isExtensible // New objects are extensible. var empty = {}; Object.isExtensible(empty); // === true // ...but that can be changed. Object.preventExtensions(empty); Object.isExtensible(empty); // === false // Sealed objects are by definition non-extensible. var sealed = Object.seal({}); Object.isExtensible(sealed); // === false // Fro...
Object.isFrozen() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Object.isFrozen(obj) Parameters obj The object which should be checked. Return value A Boolean indicating whether or not the given object is frozen. Description An object is frozen if and only if it is not extensible, all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. Examples Using Object.isFrozen // A new object is extensible, so it is not frozen. ...
...igurable, 'release', { configurable: false }); Object.isFrozen(nonConfigurable); // === false // Changing that property to non-writable // then makes the object frozen. Object.defineProperty(nonConfigurable, 'release', { writable: false }); Object.isFrozen(nonConfigurable); // === true // A non-extensible object with a configurable // accessor property isn't frozen. var accessor = { get food
() { return 'yum'; } }; Object.preventExtensions(accessor); Object.isFrozen(accessor); // === false // ...but make that property non-configurable // and it becomes frozen. Object.defineProperty(accessor, 'food', { configurable: false }); Object.isFrozen(accessor); // === true // But the easiest way for an object to be frozen // is if Object.freeze has been called on it. var frozen = { 1: 81 }; O...
Object.isSealed() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Object.isSealed(obj) Parameters obj The object which should be checked. Return value A Boolean indicating whether or not the given object is sealed. Description Returns true if the object is sealed, otherwise false. An object is sealed if it is not extensible and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). Examples Using Object.isSealed // Objects aren't sealed by default. ...
... Object.isSealed(sealed); // === true // A sealed object is, by definition, non-extensible. Object.isExtensible(sealed); // === false // A sealed object might be frozen, // but it doesn't have to be. Object.isFrozen(sealed); // === true // (all properties also non-writable) var s2 = Object.seal({ p: 3 }); Object.isFrozen(s2); // === false // ('p' is still writable) var s3 = Object.seal({ get p
() { return 0; } }); Object.isFrozen(s3); // === true // (only configurability matters for accessor properties) Non-object coercion In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. In ES2015, a non-object argument will be treated as if it was a sealed ordinary object, simply return true. Object.isSealed(1); // TypeError: 1 is not an object (E...
Object.values() - JavaScript
The Object.values
() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop. (The only difference is that a for...in loop enumerates properties in the prototype chain as well.) 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 Object.values(obj) Parameters obj The object whose enumerable own property values are to be returned. Return value An array containing the given object's own enumerable property values. Description Object.values
() returns an array whose elements are the enumerable property values found on the object. Th...
... ...
Promise.reject() - JavaScript
The Promise.reject
() method returns a Promise object that is rejected with a given reason. 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 Promise.reject(reason); Parameters reason Reason why this Promise rejected. Return value A Promise that is rejected with the given reason. Description The static Promise.reject function returns a Promise that is rejected. For debugging purposes and selective error catching, it is useful to make reason an instanceof Error. ...
... pull request. Syntax Promise.reject(reason); Parameters reason Reason why this Promise rejected. Return value A Promise that is rejected with the given reason. Description The static Promise.reject function returns a Promise that is rejected. For debugging purposes and selective error catching, it is useful to make reason an instanceof Error. Examples Using the static Promise.reject
() method Promise.reject(new Error('fail')).then(function
() { // not called }, function(error) { console.error(error); // Stacktrace }); Specifications Specification ECMAScript (ECMA-262)The definition of 'Promise.reject' in that specification. ...
handler.deleteProperty() - JavaScript
The handler.deleteProperty
() method is a trap for the delete operator. 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 p = new Proxy(target, { deleteProperty: function(target, property) { } }); Parameters The following parameters are passed to the deleteProperty
() method. this is bound to the handler. target The target object. property The name or Symbol of the property to delete. Return value The deleteProperty
() method must return a Boolean indicating whether or not the property has been successfully deleted. ...
...get, property) { } }); Parameters The following parameters are passed to the deleteProperty
() method. this is bound to the handler. target The target object. property The name or Symbol of the property to delete. Return value The deleteProperty
() method must return a Boolean indicating whether or not the property has been successfully deleted. Description The handler.deleteProperty
() method is a trap for the delete operator. Interceptions This trap can intercept these operations: Property deletion: delete proxy[foo] and delete proxy.foo Reflect.deleteProperty
() Invariants If the following invariants are violated, the proxy will throw a TypeError: A property cannot be deleted, if it exists as a non-configurable own property of the target object. Examples Trappin...
handler.get() - JavaScript
The handler.get
() method is a trap for getting a property 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 const p = new Proxy(target, { get: function(target, property, receiver) { } }); Parameters The following parameters are passed to the get
() method. this is bound to the handler. target The target object. property The name or Symbol of the property to get. receiver Either the proxy or an object that inherits from the proxy. Return value The get
() method can return any value. Description The handler.get
() method is a trap for getting a property value. Interceptions This tra...
... of the property to get. receiver Either the proxy or an object that inherits from the proxy. Return value The get
() method can return any value. Description The handler.get
() method is a trap for getting a property value. Interceptions This trap can intercept these operations: Property access: proxy[foo]and proxy.bar Inherited property access: Object.create(proxy)[foo] Reflect.get
() Invariants If the following invariants are violated, the proxy will throw a TypeError: The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. The value reported for a property must be undefined if the corresponding target object property is a non-configu...
handler.getPrototypeOf() - JavaScript
The handler.getPrototypeOf
() method is a trap for the [[GetPrototypeOf]] internal method. 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 p = new Proxy(obj, { getPrototypeOf(target) { ... } }); Parameters The following parameter is passed to the getPrototypeOf
() method. this is bound to the handler. target The target object. Return value The getPrototypeOf
() method must return an object or null. ...
...ull request. Syntax const p = new Proxy(obj, { getPrototypeOf(target) { ... } }); Parameters The following parameter is passed to the getPrototypeOf
() method. this is bound to the handler. target The target object. Return value The getPrototypeOf
() method must return an object or null. Description Interceptions This trap can intercept these operations: Object.getPrototypeOf
() Reflect.getPrototypeOf
() __proto__ Object.prototype.isPrototypeOf
() instanceof Invariants If the following invariants are violated, the proxy will throw a TypeError: getPrototypeOf
() method must return an object or null. If target is not extensible, Object.getPrototypeOf(proxy) method must return the same value as Object.getPrototypeOf(target). Examples Basic usage const obj = {}; ...
handler.has() - JavaScript
The handler.has
() method is a trap for the in operator. 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 p = new Proxy(target, { has: function(target, prop) { } }); Parameters The following parameters are passed to has
() method. this is bound to the handler. target The target object. prop The name or Symbol of the property to check for existence. Return value The has
() method must return a boolean value. Description The handler.has
() method is a trap for the in operator. Interceptions This trap can intercept these operations: Property query: foo in proxy Inherited property quer...
... object. prop The name or Symbol of the property to check for existence. Return value The has
() method must return a boolean value. Description The handler.has
() method is a trap for the in operator. Interceptions This trap can intercept these operations: Property query: foo in proxy Inherited property query: foo in Object.create(proxy) with check: with(proxy) { (foo); } Reflect.has
() Invariants If the following invariants are violated, the proxy will throw a TypeError: A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. Examples Trapping the in operator The follo...
handler.isExtensible() - JavaScript
The handler.isExtensible
() method is a trap for Object.isExtensible
(). 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 p = new Proxy(target, { isExtensible: function(target) { } }); Parameters The following parameter is passed to the isExtensible
() method. this is bound to the handler. target The target object. Return value The isExtensible
() method must return a boolean value. Description The handler.isExtensible
() method is a trap for Object.isExtensible
(). ...
...unction(target) { } }); Parameters The following parameter is passed to the isExtensible
() method. this is bound to the handler. target The target object. Return value The isExtensible
() method must return a boolean value. Description The handler.isExtensible
() method is a trap for Object.isExtensible
(). Interceptions This trap can intercept these operations: Object.isExtensible
() Reflect.isExtensible
() Invariants If the following invariants are violated, the proxy will throw a TypeError: Object.isExtensible(proxy) must return the same value as Object.isExtensible(target). Examples Trapping of isExtensible The following code traps Object.isExtensible
(). const p = new Proxy({}, { isExtensible: function(target) { console.log('called'); return true; } ...
handler.preventExtensions() - JavaScript
The handler.preventExtensions
() method is a trap for Object.preventExtensions
(). 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 p = new Proxy(target, { preventExtensions: function(target) { } }); Parameters The following parameter is passed to the preventExtensions
() method. this is bound to the handler. target The target object. Return value The preventExtensions
() method must return a boolean value. Description The handler.preventExtensions
() method is a trap for Object.preventExtensions
(). ...
... Parameters The following parameter is passed to the preventExtensions
() method. this is bound to the handler. target The target object. Return value The preventExtensions
() method must return a boolean value. Description The handler.preventExtensions
() method is a trap for Object.preventExtensions
(). Interceptions This trap can intercept these operations: Object.preventExtensions
() Reflect.preventExtensions
() Invariants If the following invariants are violated, the proxy will throw a TypeError: Object.preventExtensions(proxy) only returns true if Object.isExtensible(proxy) is false. Examples Trapping of preventExtensions The following code traps Object.preventExtensions
(). const p = new Proxy({}, { preventExtensions: function(target) { console.log('called'...
Reflect.defineProperty() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.defineProperty(target, propertyKey, attributes) Parameters target The target object on which to define the property. propertyKey The name of the property to be defined or modified. attributes The attributes for the property being defined or modified. Return value A Boolean indicating whether or not the property was successfully defined. Exceptions A TypeError, if target is not an Object. ...
...cation of a property on an object. For more details, see the Object.defineProperty which is similar. One key difference: Object.defineProperty returns the object or throws a TypeError if the property has not been successfully defined. Reflect.defineProperty, however, simply returns a Boolean indicating whether or not the property was successfully defined. Examples Using Reflect.defineProperty
() let obj = {} Reflect.defineProperty(obj, 'x', {value: 7}) // true obj.x // 7 Checking if property definition has been successful With Object.defineProperty, which returns an object if successful, or throws a TypeError otherwise, you would use a try...catch block to catch any error that occurred while defining a property. ] Because Reflect.defineProper...
Reflect.deleteProperty() - JavaScript
It is like the delete operator as a function. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.deleteProperty(target, propertyKey) Parameters target The target object on which to delete the property. propertyKey The name of the property to be deleted. Return value A Boolean indicating whether or not the property was successfully deleted. Exceptions A TypeError, if target is not an Object. Description The Reflect.deleteProperty method allows you to delete a property on an object. ...
...ean indicating whether or not the property was successfully deleted. Exceptions A TypeError, if target is not an Object. Description The Reflect.deleteProperty method allows you to delete a property on an object. It returns a Boolean indicating whether or not the property was successfully deleted. It is almost identical to the non-strict delete operator. ...
Reflect.get() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.get(target, propertyKey[, receiver]) Parameters target The target object on which to get the property. propertyKey The name of the property to get. receiver Optional The value of this provided for the call to target if a getter is encountered. When used with Proxy, it can be an object that inherits from target. Return value The value of the property. Exceptions A TypeError, if target is not an Object. ...
...ue of this provided for the call to target if a getter is encountered. When used with Proxy, it can be an object that inherits from target. Return value The value of the property. Exceptions A TypeError, if target is not an Object. Description The Reflect.get method allows you to get a property on an object. It is like the property accessor syntax as a function. ...
Reflect.ownKeys() - JavaScript
The static Reflect.ownKeys
() method returns an array of the target object's own property keys. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.ownKeys(target) Parameters target The target object from which to get the own keys. Return value An Array of the target object's own property keys. Exceptions A TypeError, if target is not an Object. Description The Reflect.ownKeys method returns an array of the target object's own property keys. Its return value is equivalent to Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)). ...
...from which to get the own keys. Return value An Array of the target object's own property keys. Exceptions A TypeError, if target is not an Object. Description The Reflect.ownKeys method returns an array of the target object's own property keys. Its return value is equivalent to Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)). ...
Reflect.set() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.set(target, propertyKey, value[, receiver]) Parameters target The target object on which to set the property. propertyKey The name of the property to set. value The value to set. receiver Optional The value of this provided for the call to target if a setter is encountered. Return value A Boolean indicating whether or not setting the property was successful. Exceptions A TypeError, if target is not an Object. ...
...this provided for the call to target if a setter is encountered. Return value A Boolean indicating whether or not setting the property was successful. Exceptions A TypeError, if target is not an Object. Description The Reflect.set method allows you to set a property on an object. It does property assignment and is like the property accessor syntax as a function. Examples Using Reflect.set
() // Object let obj = {} Reflect.set(obj, 'prop', 'value') // true obj.prop // "value" // Array let arr = ['duck', 'duck', 'duck'] Reflect.set(arr, 2, 'goose') // true arr[2] // "goose" // It can truncate an array. Reflect.set(arr, 'length', 1) // true arr // ["duck"] // With just one argument, propertyKey and value are "undefined". let obj = {} Reflect.set(obj) // true Reflect.getOwnPro...
Reflect.setPrototypeOf() - JavaScript
It sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or to null, and returns true if the operation was successful, or false otherwise. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.setPrototypeOf(target, prototype) Parameters target The target object of which to set the prototype. prototype The object's new prototype (an object or null). ...
... (an object or null). Return value A Boolean indicating whether or not the prototype was successfully set. Exceptions A TypeError, if target is not an Object or if prototype is neither an object nor null. Description The Reflect.setPrototypeOf method changes the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object. Examples Using Reflect.setPrototypeOf
() Reflect.setPrototypeOf({}, Object.prototype) // true // It can change an object's [[Prototype]] to null. Reflect.setPrototypeOf({}, null) // true // Returns false if target is not extensible. Reflect.setPrototypeOf(Object.freeze({}), null) // false // Returns false if it cause a prototype chain cycle. let target = {} let proto = Object.create(target) Reflect.setPrototypeOf(target, proto) ...
RegExp.prototype[@@matchAll]() - JavaScript
ctive 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 regexp[Symbol.matchAll](str) Parameters str A String that is a target of the match. Return value An iterator. Description This method is called internally in String.prototype.matchAll
(). For example, the following two examples return same result. 'abc'.matchAll(/a/); /a/[Symbol.matchAll]('abc'); This method exists for customizing the behavior of matchAll
() in RegExp subclasses. Examples Direct call This method can be used in almost the same way as String.prototype.matchAll
(), except for the different value of this and the different order of arguments. let re = /[0-9]+/g; ...
... call This method can be used in almost the same way as String.prototype.matchAll
(), except for the different value of this and the different order of arguments. let re = /[0-9]+/g; let str = '2016-01-02'; let result = re[Symbol.matchAll](str); console.log(Array.from(result, x => x[0])); // ["2016", "01", "02"] Using @@matchAll in subclasses Subclasses of RegExp can override the [@@matchAll]
() method to modify the default behavior. For example, to return an Array instead of an iterator: class MyRegExp extends RegExp { [Symbol.matchAll](str) { const result = RegExp.prototype[Symbol.matchAll].call(this, str); if (!result) { return null; } else { return Array.from(result); } } } const re = new MyRegExp('([0-9]+)-([0-9]+)-([0-9]+)', 'g'); const str = '201...
RegExp.prototype.compile() - JavaScript
It is basically the same as the RegExp constructor. Syntax regexObj.compile(pattern, flags) Parameters pattern The text of the regular expression. ...
...n or \r), not only the very beginning or end of the whole input string) y sticky; matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes). Description The compile method is deprecated. You can just use the RegExp constructor to achieve the same effect. Examples Using compile
() The following example shows how to recompile a regular expression with a new pattern and a new flag. var regexObj = new RegExp('foo', 'gi'); regexObj.compile('new foo', 'g'); Specifications Specification ECMAScript (ECMA-262)The definition of 'RegExp.prototype.compile' in that specification. ...
Set.prototype.delete() - JavaScript
No "bar" element found to be deleted. mySet.delete('foo'); // Returns true. Successfully removed. mySet.has('foo'); // Returns false. The "foo" element is no longer present. ...
...tive 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 mySet.delete(value); Parameters value The value to remove from mySet. Return value Returns true if value was successfully removed from mySet; otherwise false. Examples Using the delete
() method const mySet = new Set
(); mySet.add('foo'); mySet.delete('bar'); // Returns false. No "bar" element found to be deleted. mySet.delete('foo'); // Returns true. Successfully removed. mySet.has('foo'); // Returns false. The "foo" element is no longer present. Let's checkout below how to delete an Object from a Set. const setObj = new Set
(); // Create a New Set. setObj.add({x: 10, ...
Set.prototype.values() - JavaScript
The values
() method returns a new Iterator object that contains the values for each element in the Set object in insertion order. The keys
() method is an alias for this method (for similarity with Map objects); it behaves exactly the same and returns values of Set elements. 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 mySet.values
(); Return value A new Iterator object containing the values for each element in the given Set, in insertion order. ...
...elements. 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 mySet.values
(); Return value A new Iterator object containing the values for each element in the given Set, in insertion order. Examples Using values
() var mySet = new Set
(); mySet.add('foo'); mySet.add('bar'); mySet.add('baz'); var setIter = mySet.values
(); console.log(setIter.next
().value); // "foo" console.log(setIter.next
().value); // "bar" console.log(setIter.next
().value); // "baz" Specifications Specification ECMAScript (ECMA-262)The definition of 'Set.prototype.values' in that specification. ...
SharedArrayBuffer.prototype.slice() - JavaScript
The SharedArrayBuffer.prototype.slice
() method returns a new SharedArrayBuffer whose contents are a copy of this SharedArrayBuffer's bytes from begin, inclusive, up to end, exclusive. If either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning. This method has the same algorithm as Array.prototype.slice
(). 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 sab.slice
() sab.slice(begin) sab.slice(begin, end) Parameters begin Optional Zero-based index at which to begin extraction. A negative index can be used, indicating an offset from the end of th...
...gative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. If end is omitted, slice extracts through the end of the sequence (sab.byteLength). Return value A new SharedArrayBuffer containing the extracted elements. Examples Using slice var sab = new SharedArrayBuffer(1024); sab.slice
(); // SharedArrayBuffer { byteLength: 1024 } sab.slice(2); // SharedArrayBuffer { byteLength: 1022 } sab.slice(-2); // SharedArrayBuffer { byteLength: 2 } sab.slice(0, 1); // SharedArrayBuffer { byteLength: 1 } Specifications Specification ECMAScript (ECMA-262)The definition of 'SharedArrayBuffer.prototype.slice' in that specification. ...
String.prototype.anchor() - JavaScript
The anchor
() method creates a string beginning with an <a name="..."> start tag, then some text, and then an </a> end tag. Don't use this method. Use DOM APIs instead. Also, the HTML specification no longer allows the <a> element to have a name attribute, so this method doesn't even create valid markup. Syntax str.anchor(name) Parameters name A string representing a name value to put into the generated <a name="..."> start tag. Return value A string beginning with an <a name="name"> start tag, then the text str, and then an </a> end tag Description Don't use this method. Use DOM APIs instead. Also, the HTML specification no longer allows the <a> element to have a name attribute, so this method doesn't even create valid markup. ...
...g a name value to put into the generated <a name="..."> start tag. Return value A string beginning with an <a name="name"> start tag, then the text str, and then an </a> end tag Description Don't use this method. Use DOM APIs instead. Also, the HTML specification no longer allows the <a> element to have a name attribute, so this method doesn't even create valid markup. Examples Using anchor
() var myString = 'Table of Contents'; document.body.innerHTML = myString.anchor('contents_anchor'); will output the following HTML: <a name="contents_anchor">Table of Contents</a> Specifications Specification ECMAScript (ECMA-262)The definition of 'String.prototype.anchor' in that specification. ...
String.prototype.fontcolor() - JavaScript
The fontcolor
() method creates a <font> HTML element that causes a string to be displayed in the specified font color. Usage note: The <font> element has been removed in HTML5 and shouldn't be used anymore. Instead web developers should use CSS properties. Syntax str.fontcolor(color) Parameters color A string expressing the color as a hexadecimal RGB triplet or as a string literal. String literals for color names are listed in the CSS color reference. Return value A string containing a <font> HTML element. Description If you express color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072". ...
...a string literal. String literals for color names are listed in the CSS color reference. Return value A string containing a <font> HTML element. Description If you express color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072". Examples Using fontcolor
() The following example uses the fontcolor
() method to change the color of a string by producing a string with the HTML <font> tag. var worldString = 'Hello, world'; console.log(worldString.fontcolor('red') + ' is red in this line'); // '<font color="red">Hello, world</font> is red in this line' console.log(worldString.fontcolor('FF00') + ' is red in hexadecimal in this line'); // '<font color...
String.prototype.lastIndexOf() - JavaScript
Returns -1 if the value is not found. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.lastIndexOf(searchValue[, fromIndex]) Parameters searchValue A string representing the value to search for. If searchValue is an empty string, then fromIndex is returned. fromIndex Optional The index of the last character in the string to be considered as the beginning of a match. The default value is +Infinity. ...
...stIndexOf('a', 0); // returns -1 'canal'.lastIndexOf('x'); // returns -1 'canal'.lastIndexOf('c', -5); // returns 0 'canal'.lastIndexOf('c', 0); // returns 0 'canal'.lastIndexOf(''); // returns 5 'canal'.lastIndexOf('', 2); // returns 2 Note: 'abab'.lastIndexOf('ab', 2) will return 2 and not 0, as fromIndex limits only the beginning of the match. Case-sensitivity The lastIndexOf
() method is case sensitive. For example, the following expression returns -1: 'Blue Whale, Killer Whale'.lastIndexOf('blue'); // returns -1 Examples Using indexOf
() and lastIndexOf
() The following example uses indexOf
() and lastIndexOf
() to locate values in the string "Brave new world". let anyString = 'Brave new world'; console.log('The index of the first w from the beginning is ' + anyStri...
String.prototype.link() - JavaScript
The link
() method creates a string representing the code for an <a> HTML element to be used as a hypertext link to another URL. Syntax str.link(url) Parameters url Any string that specifies the href attribute of the <a> tag; it should be a valid URL (relative or absolute), with any & characters escaped as &, and any " characters escaped as ". Return value A string containing an <a> HTML element. Description Use the link
() method to create an HTML snippet for a hypertext link. The returned string can then be added to the document via document.write
() or element.innerHTML. Links created with the link
() method become elements in the links array of the document object. See document.links. ...
...ters escaped as ". Return value A string containing an <a> HTML element. Description Use the link
() method to create an HTML snippet for a hypertext link. The returned string can then be added to the document via document.write
() or element.innerHTML. Links created with the link
() method become elements in the links array of the document object. See document.links. Examples Using link
() The following example displays the word "MDN" as a hypertext link that returns the user to the Mozilla Developer Network. var hotText = 'MDN'; var URL = 'https://developer.mozilla.org/'; console.log('Click to return to ' + hotText.link(URL)); // Click to return to <a href="https://developer.mozilla.org/">MDN</a> Specifications Specification ECMAScript (ECMA-262)The definit...
String.prototype.padStart() - JavaScript
The padding is applied from the start of the current string. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.padStart(targetLength [, padString]) Parameters targetLength The length of the resulting string once the current str has been padded. If the value is less than str.length, then str is returned as-is. padString Optional The string to pad the current str with. ...
... ...
String.prototype.replaceAll() - JavaScript
The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. The original string is left unchanged. 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. ...
... be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. The arguments to the function are as follows: Possible name Supplied value match The matched substring. (Corresponds to $& above.) p1, p2, ... The nth string found by a parenthesized capture group, provided the first argument to replace
() was a RegExp object. (Corresponds to $1, $2, etc. above.) For example, if /(\a+)(\b+)/, was given, p1 is the match for \a+, and p2 for \b+. offset The offset of the matched substring within the whole string being examined. (For example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.) string The whole string being examined.
String.prototype.search() - JavaScript
The search
() method executes a search for a match between a regular expression and this String object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.search(regexp) Parameters regexp A regular expression object. If a non-RegExp object regexp is passed, it is implicitly converted to a RegExp with new RegExp(regexp). Return value The index of the first match between the regular expression and the given string, or -1 if no match was found. Description When you want to know whether a pattern is found, and also know its index within a string, use search
(). (If you only want to know if it exists,...
...gExp object regexp is passed, it is implicitly converted to a RegExp with new RegExp(regexp). Return value The index of the first match between the regular expression and the given string, or -1 if no match was found. Description When you want to know whether a pattern is found, and also know its index within a string, use search
(). (If you only want to know if it exists, use the similar test
() method on the RegExp prototype, which returns a boolean.) For more information (but slower execution) use match
() (similar to the regular expression exec
() method). Examples Using search
() The following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1) let str = "hey JudE" let re = /[A-Z]/g let reDot = /[.
String.prototype.toLowerCase() - JavaScript
The toLowerCase
() method returns the calling string value converted to lower case. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.toLowerCase
() Return value A new string representing the calling string converted to lower case. Description The toLowerCase
() method returns the value of the string converted to lower case. toLowerCase
() does not affect the value of the string str itself. ...
...les project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.toLowerCase
() Return value A new string representing the calling string converted to lower case. Description The toLowerCase
() method returns the value of the string converted to lower case. toLowerCase
() does not affect the value of the string str itself. Examples Using toLowerCase
() console.log('ALPHABET'.toLowerCase
()); // 'alphabet' Specifications Specification ECMAScript (ECMA-262)The definition of 'String.prototype.toLowerCase' in that specification. ...
String.prototype.toUpperCase() - JavaScript
The toUpperCase
() method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.toUpperCase
() Return value A new string representing the calling string converted to upper case. Exceptions TypeError When called on null or undefined, for example, String.prototype.toUpperCase.call(undefined). Description The toUpperCase
() method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. Example...
...ng converted to upper case. Exceptions TypeError When called on null or undefined, for example, String.prototype.toUpperCase.call(undefined). Description The toUpperCase
() method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. Examples Basic usage console.log('alphabet'.toUpperCase
()); // 'ALPHABET' Conversion of non-string this values to strings This method will convert any non-string value to a string, when you set its this to a value that is not a string: const a = String.prototype.toUpperCase.call({ toString: function toString
() { return 'abcdef'; } }); const b = String.prototype.toUpperCase.call(true); // prints out 'ABCDEF TRUE'. console.log(a, b); Speci...
Symbol.for() - JavaScript
nteractive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Symbol.for(key); Parameters key String, required. The key for the symbol (and also used for the description of the symbol). Return value An existing symbol with the given key if found; otherwise, a new symbol is created and returned. Description In contrast to Symbol
(), the Symbol.for
() function creates a symbol available in a global symbol registry list. Symbol.for
() does also not necessarily create a new symbol on every call, but checks first if a symbol with the given key is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, Symbol.for
() will create a new global symbol. Global symbol registry T...
...]] A symbol that is stored globally. Examples Using Symbol.for Symbol.for('foo'); // create a new global symbol Symbol.for('foo'); // retrieve the already created symbol // Same global symbol, but not locally Symbol.for('bar') === Symbol.for('bar'); // true Symbol('bar') === Symbol('bar'); // false // The key is also used as the description var sym = Symbol.for('mario'); sym.toString
(); // "Symbol(mario)" To avoid name clashes with your global symbol keys and other (library code) global symbols, it might be a good idea to prefix your symbols: Symbol.for('mdn.foo'); Symbol.for('mdn.bar'); Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.for' in that specification. ...
TypeError() constructor - JavaScript
The TypeError
() constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. Syntax new TypeError([message[, fileName[, lineNumber]]]) Parameters message Optional Optional. Human-readable description of the error fileName Optional Optional. The name of the file containing the code that caused the exception lineNumber Optional Optional. ...
...not of the expected type. Syntax new TypeError([message[, fileName[, lineNumber]]]) Parameters message Optional Optional. Human-readable description of the error fileName Optional Optional. The name of the file containing the code that caused the exception lineNumber Optional Optional. ...
TypedArray.prototype[@@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. ...
...rn value The array iterator function, which is the values
() function by default. Examples Iteration using for...of loop var arr = new Uint8Array([10, 20, 30, 40, 50]); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of arr) { console.log(n); } Alternative iteration var arr = new Uint8Array([10, 20, 30, 40, 50]); var eArr = arr[Symbol.iterator]
(); console.log(eArr.next
().value); // 10 console.log(eArr.next
().value); // 20 console.log(eArr.next
().value); // 30 console.log(eArr.next
().value); // 40 console.log(eArr.next
().value); // 50 Specifications Specification ECMAScript (ECMA-262)The definition of '%TypedArray%.prototype[@@iterator]
()' in that specification. ...
TypedArray.prototype.fill() - JavaScript
TypedArray is one of the typed array types here. 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 typedarray.fill(value[, start = 0[, end = this.length]]) Parameters value Value to fill the typed array with. start Optional. Start index. Defaults to 0. end Optional. End index (not included). Defaults to this.length. Return value The modified array. Description The elements interval to fill is [start, end). ...
...are optional with default values of 0 and the length of the this object. If start is negative, it is treated as length+start where length is the length of the array. If end is negative, it is treated as length+end. Polyfill Since there is no global object with the name TypedArray, polyfilling must be done on an "as needed" basis. Use the following "polyfill" along with the Array.prototype.fill
() polyfill. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill if (!Uint8Array.prototype.fill) { Uint8Array.prototype.fill = Array.prototype.fill; } Examples Using fill new Uint8Array([1, 2, 3]).fill(4); // Uint8Array [4, 4, 4] new Uint8Array([1, 2, 3]).fill(4, 1); // Uint8Array [1, 4, 4] new Uint8Array([1, 2, 3]).fill(4, 1, 2); // Uint8Array [1, 4, 3] new Uint...
Index - Web APIs
ble to use while developing your Web app or site. 2 ANGLE_instanced_arrays API, Reference, WebGL, WebGL extension The ANGLE_instanced_arrays extension is part of the WebGL API and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type. ...
...The ANGLE_instanced_arrays extension is part of the WebGL API and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type. 3 ANGLE_instanced_arrays.drawArraysInstancedANGLE
() ANGLE_instanced_arrays, API, Method, Reference, WebGL, WebGL extension The ANGLE_instanced_arrays.drawArraysInstancedANGLE
() method of the WebGL API renders primitives from array data like the gl.drawArrays
() method. ...
...ced_arrays.drawArraysInstancedANGLE
() ANGLE_instanced_arrays, API, Method, Reference, WebGL, WebGL extension The ANGLE_instanced_arrays.drawArraysInstancedANGLE
() method of the WebGL API renders primitives from array data like the gl.drawArrays
() method. In addition, it can execute multiple instances of the range of elements. 4 ANGLE_instanced_arrays.drawElementsInstancedANGLE
() ANGLE_instanced_arrays, API, Method, Reference, WebGL, WebGL extension The ANGLE_instanced_arrays.drawElementsInstancedANGLE
() method of the WebGL API renders primitives from array data like the gl.drawElements
() method. In addition, it can execute multiple instances of a set of elements. ...
...And 1820 more matches
jspage - Archive of obsolete content
var MooTools={version:"1.2.4",build:"0d9113241a90b9cd5643b926795852a2026710d4"};var Native=function(k){k=k||{};var a=k.name;var i=k.legacy;var b=k.protect; var c=k.implement;var h=k.generics;var f=k.initialize;var g=k.afterImplement||function
(){};var d=f||i;h=h!==false;d.constructor=Native;d.$family={name:"native"}; if(i&&f){d.prototype=i.prototype;}d.prototype.constructor=d;if(a){var e=a.toLowerCase
();d.prototype.$family={name:e};Native.typize(d,e);}var j=function(n,l,o,m){if(!b||m||!n.prototype[l]){n.prototype[l]=o; }if(h){Native.genericize(n,l,b);}g.call(n,l,o);return n;};d.alias=function(n,l,p){if(typeof n=="string"){var o=this.prototype[n];if((n=o)){return j(this,l,n,p); }}for(var m in n){this.alias(m,n[m],l);}return this;};d.implement=function(m,l,o){if(typeof m=="string"){retu...
...nction(n,l,p){if(typeof n=="string"){var o=this.prototype[n];if((n=o)){return j(this,l,n,p); }}for(var m in n){this.alias(m,n[m],l);}return this;};d.implement=function(m,l,o){if(typeof m=="string"){return j(this,m,l,o);}for(var n in m){j(this,n,m[n],l); }return this;};if(c){d.implement(c);}return d;};Native.genericize=function(b,c,a){if((!a||!b[c])&&typeof b.prototype[c]=="function"){b[c]=function
(){var d=Array.prototype.slice.call(arguments); return b.prototype[c].apply(d.shift
(),d);};}};Native.implement=function(d,c){for(var b=0,a=d.length;b<a;b++){d[b].implement(c);}};Native.typize=function(a,b){if(!a.type){a.type=function(c){return($type(c)===b); };}};(function
(){var a={Array:Array,Date:Date,Function:Function,Number:Number,RegExp:RegExp,String:String};for(var h in a){new Native({name:h,i...
...],c);}var f={Array:["concat","indexOf","join","lastIndexOf","pop","push","reverse","shift","slice","sort","splice","toString","unshift","valueOf"],String:["charAt","charCodeAt","concat","indexOf","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","valueOf"]}; for(var e in f){for(var b=f[e].length;b--;){Native.genericize(a[e],f[e][b],true);}}})
();var Hash=new Native({name:"Hash",initialize:function(a){if($type(a)=="hash"){a=$unlink(a.getClean
()); }for(var b in a){this[b]=a[b];}return this;}});Hash.implement({forEach:function(b,c){for(var a in this){if(this.hasOwnProperty(a)){b.call(c,this[a],a,this); }}},getClean:function
(){var b={};for(var a in this){if(this.hasOwnProperty(a)){b[a]=this[a];}}return b;},getLength:function
(){var b=0;for(va...
...And 93 more matches
Index
d themes--that were created prior to Firefox 1.5. Add-ons can (and should) be identified with IDs of the form extensionname@organization.tld since Firefox 1.5. 9 Generic factory XPCOM Most XPCOM factories can be very simple. Rick Potts wrote a templated-based generic factory (nsFactory<t>) that simplifies the factory creation process that just requires writing a CreateInstance
() method. The new nsIGenericFactory interface takes this a step further, by providing a single interface that can be reused anytime a simple implementation of nsIFactory is needed. Here is the interface, and a description of its use.</t> 10 How To Pass an XPCOM Object to a New Window NeedsExample, NeedsHelp If you want to be able to call functions within an XPCOM object from a ...
...s.utils XPCOM:Language Bindings, XPConnect Components.utils is a collection of various useful XPConnect features. Its interface is defined at js/xpconnect/idl/xpccomponents.idl. 31 Components.utils.Sandbox NeedsMarkupWork, Reference, Reference(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, Reference(2), XPCOM:Language Bindings, XPConnect ...
... Add-ons, Developing Mozilla, Extensions, JavaScript, Reference, Reference(2), XPCOM:Language Bindings, XPConnect Components.utils.createObjectIn creates a new JavaScript object in the scope of the specified object's compartment. 34 Components.utils.evalInSandbox Add-ons, Developing Mozilla, Extensions, JavaScript, XPCOM:Language Bindings, XPConnect The evalInSandbox
() function enables you to evaluate JavaScript code inside a sandbox you've previously created using the Components.utils.Sandbox constructor. 35 Components.utils.evalInWindow This function enables code running in a more-privileged JavaScript context to evaluate a string in a less-privileged JavaScript context. The result is structured cloned back to the original context, unles...
...And 90 more matches
JavaScript Daemons Management - Archive of obsolete content
e are some code snippets that simplify and abstract the management of daemons. The following daemons management framework is the major version of setInterval - A little framework. Introduction Sometimes a page uses dozens and dozens of animations. In such a condition it is difficult and unnatural to keep track of all events started and then to stop them when appropriate through the clearTimeout
() function. A possible approach to solve this problem is to nest all the information needed by each animation to start, stop, etc. in different objects (daemons) and then to create a constructor for such a class of objects (Daemon) in order to standardize and simplify the instantiation of them. Note: A minimalistic version of it (MiniDaemon) is published here. This more complex version of it is no...
...ire daemon.js to work. For a fast overview on the code proposed here you can git clone https://github.com/madmurphy/daemon.js.git. or, at your choice, directly download this .zip file. About the "callback arguments" polyfill In order to make this framework compatible with Internet Explorer (which doesn't support sending additional parameters to timers' callback function, neither with setTimeout
() or setInterval
()) we included the IE-specific compatibility code (commented code), which enables the HTML5 standard parameters' passage functionality in that browser for both timers (polyfill), at the end of the daemon.js module. daemon.js What follows is the module that declares the Daemon constructor (the core of this framework). The Daemon constructor itself is nothing but a clone of the lit...
...*/ Daemon.prototype; Daemon.context.constructor = Object; /* These properties can be manually reconfigured after the creation of the daemon */ Daemon.prototype.owner = Daemon.context; D...
...And 87 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
er-select: text; } #output .css-property { width: 90%; margin: 5px 5%; color: #777; position: relative; float: left; } #output .property { height: 100%; width: 12%; position: absolute; left: 0; } #output .value { width: 88%; position: absolute; white-space: pre; word-wrap: break-word; display: block; right: 0; } JavaScript Content var UIColorPicker = (function UIColorPicker
() { 'use strict'; function getElemById(id) { return document.getElementById(id); } var subscribers = []; var pickers = []; /** * RGBA Color class * * HSV/HSB and HSL (hue, saturation, value / brightness, lightness) * @param hue 0-360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ function Color(color) { if(color instanceof Color === t...
...param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ function Color(color) { if(color instanceof Color === true) { this.copy(color); return; } this.r = 0; this.g = 0; this.b = 0; this.a = 1; this.hue = 0; this.saturation = 0; this.value = 0; this.lightness = 0; this.format = 'HSV'; } function RGBColor(r, g, b) { var color = new Color
(); color.setRGBA(r, g, b, 1); return color; } function RGBAColor(r, g, b, a) { var color = new Color
(); color.setRGBA(r, g, b, a); return color; } function HSVColor(h, s, v) { var color = new Color
(); color.setHSV(h, s, v); return color; } function HSVAColor(h, s, v, a) { var color = new Color
(); color.setHSV(h, s, v); color.a = a; return color; } function HSLCol...
...rn color; } function RGBAColor(r, g, b, a) { var color = new Color
(); color.setRGBA(r, g, b, a); return color; } function HSVColor(h, s, v) { var color = new Color
(); color.setHSV(h, s, v); return color; } function HSVAColor(h, s, v, a) { var color = new Color
(); color.setHSV(h, s, v); color.a = a; return color; } function HSLColor(h, s, l) { var color = new Color
(); color.setHSL(h, s, l); return color; } function HSLAColor(h, s, l, a) { var color = new Color
(); color.setHSL(h, s, l); color.a = a; return color; } Color.prototype.copy = function copy(obj) { if(obj instanceof Color !== true) { console.log('Typeof parameter not Color'); return; } this.r = obj.r; this.g = obj.g; this.b = obj.b; this.a = obj.a; this.hue = ob...
...And 84 more matches
nsIDOMWindowUtils
hods and attributes. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 49.0 (Firefox 49.0 / Thunderbird 49.0 / SeaMonkey 2.46) Implemented by: Window. ...
...String); void clearMozAfterPaintEvents
(); PRUint32 compareCanvases(in nsIDOMHTMLCanvasElement aCanvas1, in nsIDOMHTMLCanvasElement aCanvas2, out unsigned long aMaxDifference); double computeAnimationDistance(in nsIDOMElement element, in AString property, in AString value1, in AString value2); nsICompositionStringSynthesizer createCompositionStringSynthesizer
(); Obsolete since Gecko 38.0 void disableNonTestMouseEvents(in boolean aDisable); boolean dispatchDOMEventViaPresShell(in nsIDOMNode aTarget, in nsIDOMEvent aEvent, in boolean aTrusted); nsIDOMElement elementFromPoint(in float aX, in float aY, in boolean aIgnoreRootScrollFrame, in boolean aFlushLayout); void enterModalState
(); nsIDOMElement findElem...
...aX, in float aY, in boolean aIgnoreRootScrollFrame, in boolean aFlushLayout); void enterModalState
(); nsIDOMElement findElementWithViewId(in nsViewID aId); void focus(in nsIDOMElement aElement); void forceUpdateNativeMenuAt(in AString indexString); void garbageCollect([optional] in nsICycleCollectorListener aListener); short getCursorType
(); AString getDocumentMetadata(in AString aName); nsIDOMWindow getOuterWindowWithId(in unsigned long long aOuterWindowID); long getPCCountScriptCount
(); AString getPCCountScriptSummary(in long aScript); AString getPCCountScriptContents(in long aScript); void getScrollXY(in boolean aFlushLayout, out long aScrollX, out long aScrollY); ...
...And 77 more matches
Color picker tool - CSS: Cascading Style Sheets
5px; font-size: 16px; position: absolute; opacity: 0; top: -10000px; left: 0; color: #777; float: left; transition: opacity 1s; } #zindex input { border: 1px solid #DDD; font-size: 16px; color: #777; } #zindex .ui-input-slider-info { width: 60px; } #zindex[data-active='true'] { top: 0; opacity: 1; } JavaScript Content 'use strict'; var UIColorPicker = (function UIColorPicker
() { function getElemById(id) { return document.getElementById(id); } var subscribers = []; var pickers = []; /** * RGBA Color class * * HSV/HSB and HSL (hue, saturation, value / brightness, lightness) * @param hue 0-360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ function Color(color) { if(color instanceof Color === true) { this.
...param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ function Color(color) { if(color instanceof Color === true) { this.copy(color); return; } this.r = 0; this.g = 0; this.b = 0; this.a = 1; this.hue = 0; this.saturation = 0; this.value = 0; this.lightness = 0; this.format = 'HSV'; } function RGBColor(r, g, b) { var color = new Color
(); color.setRGBA(r, g, b, 1); return color; } function RGBAColor(r, g, b, a) { var color = new Color
(); color.setRGBA(r, g, b, a); return color; } function HSVColor(h, s, v) { var color = new Color
(); color.setHSV(h, s, v); return color; } function HSVAColor(h, s, v, a) { var color = new Color
(); color.setHSV(h, s, v); color.a = a; return color; } function HSLCol...
...rn color; } function RGBAColor(r, g, b, a) { var color = new Color
(); color.setRGBA(r, g, b, a); return color; } function HSVColor(h, s, v) { var color = new Color
(); color.setHSV(h, s, v); return color; } function HSVAColor(h, s, v, a) { var color = new Color
(); color.setHSV(h, s, v); color.a = a; return color; } function HSLColor(h, s, l) { var color = new Color
(); color.setHSL(h, s, l); return color; } function HSLAColor(h, s, l, a) { var color = new Color
(); color.setHSL(h, s, l); color.a = a; return color; } Color.prototype.copy = function copy(obj) { if(obj instanceof Color !== true) { console.log('Typeof parameter not Color'); return; } this.r = obj.r; this.g = obj.g; this.b = obj.b; this.a = obj.a; this.hue = ob...
...And 73 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
node + npm installed to compile and build your app. Objective: Learn some advanced Svelte techniques involving solving reactivity issues, keyboard accessibility problems to do with component lifecycle, and more. We'll focus on some accessibility issues involving focus management. To do so, we'll utilize some techniques for accessing DOM nodes and executing methods like focus
() and select
(). We will also see how to declare and clean-up event listeners on DOM elements. We also need to learn a bit about component lifecycle, to understand when these DOM nodes get mounted and and unmounted from the DOM and how we can access them. We will also learn about the action directive, which will allow us to extend the functionality of HTML elements in a reusable and declarative way...
...t button is clicked, we'll emit a checkAll event to signal that all the todos should be checked/unchecked. When the second button is clicked, we'll emit a removeCompleted event to signal that all of the completed todos should be removed. ...
...t to signal that all the todos should be checked/unchecked. When the second button is clicked, we'll emit a removeCompleted event to signal that all of the completed todos should be removed. ...
...And 70 more matches
Graceful asynchronous programming with Promises - Learn web development
it's nice that it doesn't block the rest of the code execution. One of the most common engagements you'll have with promises is with web APIs that return a promise. Let's consider a hypothetical video chat application. The application has a window with a list of the user's friends, and clicking on a button next to a user starts a video call to that user. That button's handler calls getUserMedia
() in order to get access to the user's camera and microphone. Since getUserMedia
() has to ensure that the user has permission to use those devices and ask the user which microphone to use and which camera to use (or whether to be a voice-only call, among other possible options), it can block until not only all of those decisions are made, but also the camera and microphone have been engaged. Also, ...
... devices and ask the user which microphone to use and which camera to use (or whether to be a voice-only call, among other possible options), it can block until not only all of those decisions are made, but also the camera and microphone have been engaged. Also, the user may not respond immediately to these permission requests. This can potentially take a long time. Since the call to getUserMedia
() is made from the browser's main thread, the entire browser is blocked until getUserMedia
() returns! Obviously, that's not an acceptable option; without promises, everything in the browser becomes unusable until the user decides what to do about the camera and microphone. So instead of waiting for the user, getting the chosen devices enabled, and directly returning the MediaStream for the stream c...
...ntire browser is blocked until getUserMedia
() returns! ...
...And 66 more matches
Using IndexedDB - Web APIs
dexedDB. Such and such feature will not be available."); } Opening a database We start the whole process like this: // Let us open our database var request = window.indexedDB.open("MyTestDatabase", 3); See that? Opening a database is just like any other operation -- you have to "request" it. The open request doesn't open the database or start the transaction right away. The call to the open
() function returns an IDBOpenDBRequest object with a result (success) or error value that you handle as an event. Most other asynchronous functions in IndexedDB do the same thing - return an IDBRequest object with the result or error. The result for the open function is an instance of an IDBDatabase. The second parameter to the open method is the version of the database. The version of the databas...
...Otherwise, if there was any problem, an error event (that is, a DOM event whose type property is set to "error") is fired at ...
...Otherwise, if there was any problem, an error event (that is, a DOM event whose type property is set to "error") is fired at request. This...
...And 61 more matches
WebIDL bindings
ed as described below. In addition to those, all methods that are allowed to throw will get an ErrorResult& argument appended to their argument list. Non-static methods that use certain WebIDL types like any or object will get a JSContext* argument prepended to the argument list. Static methods will be passed a const GlobalObject& for the relevant global and can get a JSContext* by calling Context
() on it. The name of the C++ method is simply the name of the WebIDL operation with the first letter converted to uppercase. WebIDL overloads are turned into C++ overloads: they simply call C++ methods with the same name and different signatures. For example, this webidl: interface MyInterface { void doSomething(long number); double doSomething(MyInterface? otherInstance); [Throws] MyI...
... const Sequence<JS::Value>& arg2, const Optional<JS::Handle<JS::Value> >& arg3, JS::MutableHandle<JS::Value> retval); boolean The boolean WebIDL type is represented as a C++ bool. ...
... So float and unrestricted float become a C++ float, while double and unrestricted double become a C++ double. ...
...And 60 more matches
Mozilla internal string guide
ng: the abstract base class for all strings. It provides an API for assignment, individual character access, basic manipulation of characters in the string, and string comparison. This class corresponds to the XPIDL AString parameter type. nsAString is not necessarily null-terminated. nsString/nsCString: builds on nsAString by guaranteeing a null-terminated storage. ...
...uilds on nsAString by guaranteeing a null-terminated storage. This allows for a method (.get
()) to access the underlying character buffer. The remainder of the string classes inherit from either nsAString or nsString. Thus, every string class is compatible with nsAString. Since every string derives from nsAString (or nsACString), they all share a simple API. Common read-only methods: .Length
() - the number of code units (bytes for 8-bit string classes and char16_ts for 16-bit string classes) in the string. .IsEmpty
() - the fastest way of determining if the string has any value. Use this instead of testing string.Length == 0 .Equals(string) - TRUE if the given string has the same value as the current string. Common methods that modify the string: .Assign(string) - Assigns a new v...
...tyle format string and parameter list. There are also a number of concrete classes that are created as a side-effect of helper routines, etc. You should avoid direct use of these classes. Let the string library create the class for you. nsSubstringTuple - created via string concatenation nsDependentSubstring - created through Substring nsPromiseFlatString - created through PromiseFlatString
() nsLiteral[C]String - created through the ""_ns and u""_ns user-defined literals Of course, there are times when it is necessary to reference these string classes in your code, but as a general rule they should be avoided. Iterators Because Mozilla strings are always a single buffer, iteration over the characters in the string is done using raw pointers: /** * Find whether there is a tab ch...
...And 58 more matches
nsIMsgFolder
The nsIMsgFolder interface is used to interact with folders in Thunderbird. This page is out of date. Check //github.com/RealityRipple/UXP/blob/master/mailnews/base/public/nsIMsgFolder.idl for the newer methods (esp. isSpecialFolder and such). ...
... The nsIMsgFolder interface is used to interact with folders in Thunderbird. This page is out of date. Check //github.com/RealityRipple/UXP/blob/master/mailnews/base/public/nsIMsgFolder.idl for the newer methods (esp. isSpecialFolder and such). ...
...ic/nsIMsgFolder.idl for the newer methods (esp. isSpecialFolder and such). ...
...And 58 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
To understand asynchronous loops and intervals and what they are useful for. Introduction For a long time, the web platform has offered JavaScript programmers a number of functions that allow them to asynchronously execute code after a certain time interval has elapsed, and to repeatedly execute a block of code asynchronously until you tell it to stop. These functions are: setTimeout
() Execute a specified block of code once after a specified time has elapsed. setInterval
() Execute a specified block of code repeatedly with a fixed time delay between each call. requestAnimationFrame
() The modern version of setInterval
(). Executes a specified block of code before the browser next repaints the display, allowing an animation to be run at a suitable framerate regardless of the e...
...Depending on how processor-intensive these operations are, they can delay your async code even further, as any async code will execute only after the main thread is available. (In other words, when the stack is empty.) You will learn more on this matter as you progress through this article. ...
...rowser next repaints the display, allowing an animation to be run at a suitable framerate regardless of the environment it is being run in. The asynchronous code set up by these functions runs on the main thread (after their specified timer has elapsed). It's important to know that you can (and often will) run other code before a setTimeout
() call executes, or between iterations of setInterval
(). Depending on how processor-intensive these operations are, they can delay your async code even further, as any async code will execute only after the main thread is available. (In other words, when the stack is empty.) You will learn more on this matter as you progress through this article. In any case, these functions are used for running constant animations and other background processing o...
...And 57 more matches
Drawing graphics - Learn web development
ndered, and just like any other image (the rendered canvas is just an image), the image could become pixellated/distorted. Getting the canvas context and final setup We need to do one final thing before we can consider our canvas template finished. To draw onto the canvas we need to get a special reference to the drawing area called a context. This is done using the HTMLCanvasElement.getContext
() method, which for basic usage takes a single string as a parameter representing the type of context you want to retrieve. In this case we want a 2d canvas, so add the following JavaScript line below the others inside the <script> element: const ctx = canvas.getContext('2d'); Note: other context values you could choose include webgl for WebGL, webgl2 for WebGL 2, etc., but we won't need those ...
... so forth are performed in the order in which they occur. Think of it like painting a wall, where each coat of paint overlaps and may even hide what's underneath. You can't do anything to change this, so you have to think carefully about the order in which you draw the graphics. Note that you can draw semi-transparent graphics by specifying a semi-transparent color, for example by using rgba
(). The a value defines what's called the "alpha channel, " or the amount of transparency the color has. The higher its value, the more it will obscure whatever's behind it. Add the following to your code: ctx.fillStyle = 'rgba(255, 0, 255, 0.75)'; ctx.fillRect(25, 100, 175, 50); Now try drawing some more rectangles of your own; have fun! Strokes and line widths So far we've looked at ...
...h the pen should move along on your canvas to trace the shape you want to draw. Canvas includes functions for drawing straight lines, circles, Bezier curves, and more. Let's start the section off by making a fresh copy of our canvas template (1_canvas_template.html), in which to draw the new example. ...
...And 54 more matches
JXON - Archive of obsolete content
work |*| |*| https://developer.mozilla.org/docs/JXON |*| https://developer.mozilla.org/User:fusionchess |*| |*| This framework is released under the GNU Public License, version 3 or later. ...
...ext (sValue) { if (/^\s*$/.test(sValue)) { return null; } if (/^(?:true|false)$/i.test(sValue)) { return sValue.toLowerCase
() === "true"; } if (isFinite(sValue)) { return parseFloat(sValue); } if (isFinite(Date.parse(sValue))) { return new Date(sValue); } return sValue; } function JXONTree (oXMLParent) { var nAttrLen = 0, nLength = 0, sCollectedTxt = ""; if (oXMLParent.hasChildNodes
()) { for (var oNode, sProp, vContent, nItem = 0; nItem < oXMLParent.childNodes.length; nItem++) { oNode = oXMLParent.childNodes.item(nItem); if ((oNode.nodeType - 1 | 1) === 3) { sCollectedTxt += oNode.nodeType === 3 ? ...
...lue); } return sValue; } function JXONTree (oXMLParent) { var nAttrLen = 0, nLength = 0, sCollectedTxt = ""; if (oXMLParent.hasChildNodes
()) { for (var oNode, sProp, vContent, nItem = 0; nItem < oXMLParent.childNodes.length; nItem++) { oNode = oXMLParent.childNodes.item(nItem); if ((oNode.nodeType - 1 | 1) === 3) { sCollectedTxt += oNode.nodeType === 3 ? ...
...And 52 more matches
Client-side storage - Learn web development
e data is contained within two object-like structures inside the browser: sessionStorage and localStorage. The first one persists data for as long as the browser is open (the data is lost when the browser is closed) and the second one persists data even after the browser is closed and then opened again. We'll use the second one in this article as it is generally more useful. The Storage.setItem
() method allows you to save a data item in storage -- it takes two parameters: the name of the item, and its value. Try typing this into your JavaScript console (change the value to your own name, if you wish!): localStorage.setItem('name','Chris'); The Storage.getItem
() method takes one parameter -- the name of a data item you want to retrieve -- and returns the item's value. Now type the...
...Type the following lines into your JavaScript console: localStorage.removeItem('name'); let myName = localStorage.getItem('name'); myName The third line should now return null -- the name item no longer exists in the web storage. ...
...eting = document.querySelector('.personal-greeting'); Next up, we need to include a small event listener to stop the form from actually submitting itself when the submit button is pressed, as this is not the behavior we want. ...
...And 51 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
perations. The standard arithmetic operators are supported, including addition, subtraction, modulus (or remainder) arithmetic, and so forth. There's also a built-in object that we did not mention earlier called Math that provides advanced mathematical functions and constants: Math.sin(3.5); var circumference = 2 * Math.PI * r; You can convert a string to an integer using the built-in parseInt
() function. This takes the base for the conversion as an optional second argument, which you should always provide: parseInt('123', 10); // 123 parseInt('010', 10); // 10 In older browsers, strings beginning with a "0" are assumed to be in octal (radix 8), but this hasn't been the case since 2013 or so. Unless you're certain of your string format, you can get surprising results on those older br...
...ich you should always provide: parseInt('123', 10); // 123 parseInt('010', 10); // 10 In older browsers, strings beginning with a "0" are assumed to be in octal (radix 8), but this hasn't been the case since 2013 or so. Unless you're certain of your string format, you can get surprising results on those older browsers: parseInt('010'); // 8 parseInt('0x10'); // 16 Here, we see the parseInt
() function treat the first string as octal due to the leading 0, and the second string as hexadecimal due to the leading "0x". The hexadecimal notation is still in place; only octal has been removed. If you want to convert a binary number to an integer, just change the base: parseInt('11', 2); // 3 Similarly, you can parse floating point numbers using the built-in parseFloat
() function. Unlike ...
...eat the first string as octal due to the leading 0, and the second string as hexadecimal due to the leading "0x". The hexadecimal notation is still in place; only octal has been removed. If you want to convert a binary number to an integer, just change the base: parseInt('11', 2); // 3 Similarly, you can parse floating point numbers using the built-in parseFloat
() function. Unlike its parseInt
() cousin, parseFloat
() always uses base 10. You can also use the unary + operator to convert values to numbers: + '42'; // 42 + '010'; // 10 + '0x10'; // 16 A special value called NaN (short for "Not a Number") is returned if the string is non-numeric: parseInt('hello', 10); // NaN NaN is toxic: if you provide it as an operand to any mathematical operation, the result will also be NaN: N...
...And 50 more matches
nsIAnnotationService
ion. Removed at 7 days. TYPE_INT32 1 INT32 type constant. TYPE_DOUBLE 2 DOUBLE type constant. TYPE_STRING 3 STRING type constant. TYPE_BINARY 4 BINARY type constant. TYPE_INT64 5 INT64 type constant. Note: Use of value "1" is omitted due to it's temporary use as EXPIRE_NEVER in bug 319455. Methods setPageAnnotation
() This method sets an annotation for given URI, overwriting any previous annotation with the same URL/name. IT IS YOUR JOB TO NAMESPACE YOUR ANNOTATION NAMES. Use the form "namespace/value", so your name would be like "bills_extension/page_state" or "history/thumbnail". Do not use characters that are not valid in URLs such as spaces, ":", commas, or most other symbols. You should stick to ASCII l...
...ch as spaces, ":", commas, or most other symbols. You should stick to ASCII letters and numbers plus "_", "-", and "/". The annotation "favicon" is special. Favicons are stored in the favicon service, but are special cased in the protocol handler so they look like annotations. Do not set favicons using this service, it will not work. Binary annotations should be set using setItemAnnotationBinary
() or setPageAnnotationBinary
(). For other types, only C++ consumers may use the type-specific methods. void setPageAnnotation( in nsIURI aURI, in AUTF8String aName, in nsIVariant aValue, in long aFlags, in unsigned short aExpiration ); Parameters aURI The URI on which the annotation is to be set. aName The annotation name. aValue The annotation value. aFlags Should be "0" for...
...n history as annotations but the user has no way of knowing it, potentially violating their privacy expectations about actions such as Clear history. If there is an important annotation that the user or extension wants to keep, you should add a bookmark for the page and use an EXPIRE_NEVER annotation. This will ensure the annotation exists until the item is removed by the user. setItemAnnotation
() This method sets an annotation for given item, overwriting any previous annotation with the same URL/name. IT IS YOUR JOB TO NAMESPACE YOUR ANNOTATION NAMES. Use the form "namespace/value", so your name would be like "bills_extension/page_state" or "history/thumbnail". Do not use characters that are not valid in URLs such as spaces, ":", commas, or most other symbols. You should stick to ASCII ...
...And 49 more matches
nsINavBookmarksService
Implemented by: @mozilla.org/browser/nav-bookmarks-service;1. ...
...Obsolete since Gecko 1.9 void getBookmarkIdsForURI(in nsIURI aURI, [optional] out unsigned long count, [array, retval, size_is(count)] ...
...TYPE_BOOKMARK 1 This is an index for type "Bookmark". TYPE_FOLDER 2 This is an index for type "Folder". TYPE_SEPARATOR 3 This is an index for type "Separator". TYPE_DYNAMIC_CONTAINER 4 This is an index for type "Dynamic Container". Dynamic containers were removed in Gecko 11, but the type index remains to prevent reuse. Methods addObserver
() This method adds a bookmark observer. If ownsWeak is false, the bookmark service will keep an owning reference to the observer. If ownsWeak is true, then aObserver must implement nsISupportsWeakReference, and the bookmark service will keep a weak reference to the observer. void addObserver( in nsINavBookmarkObserver observer, in boolean ownsWeak ); Parameters observer The bookmark obs...
...And 49 more matches
Signaling and video calling - Web APIs
nsure unrecognized message types are passed through and delivered, without the server needing to know what they are. This lets us send signaling messages using this same server, instead of needing a separate server. Let's take a look which changes we need to make to the chat server support WebRTC signaling. This is in the file chatserver.js. First up is the addition of the function sendToOneUser
(). As the name suggests, this sends a stringified JSON message to a particular username. function sendToOneUser(target, msgString) { var isUnique = true; var i; for (i=0; i<connectionArray.length; i++) { if (connectionArray[i].username === target) { connectionArray[i].send(msgString); break; } } } This function iterates over the list of connected users until it finds ...
...ing the specified username, then sends the message to that user. The parameter msgString is a stringified JSON object. We could have made it receive our original message object, but in this example it's more efficient this way. Since the message has already been stringified, we can send it with no further processing. Each entry in connectionArray is a WebSocket object, so we can just call its send
() method directly. Our original chat demo didn't support sending messages to a specific user. The next task is to update the main WebSocket message handler to support doing so. This involves a change near the end of the "connection" message handler: if (sendToClients) { var msgString = JSON.stringify(msg); var i; if (msg.target && msg.target !== undefined && msg.target.length !== 0) { ...
...fined && msg.target.length !== 0) { sendToOneUser(msg.target, msgString); } else { for (i=0; i<connectionArray.length; i++) { connectionArray[i].send(msgString); } } } This code now looks at the pending message to see if it has a target property. If that property is present, it specifies the username of the client to which the message is to be sent, and we call sendToOneUser
() to send the message to them. Otherwise, the message is broadcast to all users by iterating over the connection list, sending the message to each user. As the existing code allows the sending of arbitrary message types, no additional changes are required. Our clients can now send messages of unknown types to any specific user, letting them send signaling messages back and forth as desired. That'...
...And 49 more matches
Drawing shapes with canvas - Web APIs
e. strokeRect(x, y, width, height) Draws a rectangular outline. clearRect(x, y, width, height) Clears the specified rectangular area, making it fully transparent. Each of these three functions takes the same parameters. x and y specify the position on the canvas (relative to the origin) of the top-left corner of the rectangle. width and height provide the rectangle's size. ...
...ng it fully transparent. Each of these three functions takes the same parameters. x and y specify the position on the canvas (relative to the origin) of the top-left corner of the rectangle. width and height provide the rectangle's size. Below is the draw
() function from the previous page, but now it is making use of these three functions. Rectangular shape example <html> <body onload="draw
();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> function draw
() { var canvas = document.getElementById('canvas'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); ctx.fillRect(25, 25, 100, 100); ctx.clearRect(45, 45, 60, 60); ctx.strokeRect(50, 50, 50, 50); } } This example's output is shown below. ScreenshotLive sample The fil...
... <canvas id="canvas" width="150" height="150"></canvas> </body> </html> function draw
() { var canvas = document.getElementById('canvas'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); ctx.fillRect(25, 25, 100, 100); ctx.clearRect(45, 45, 60, 60); ctx.strokeRect(50, 50, 50, 50); } } This example's output is shown below. ScreenshotLive sample The fillRect
() function draws a large black square 100 pixels on each side. The clearRect
() function then erases a 60x60 pixel square from the center, and then strokeRect
() is called to create a rectangular outline 50x50 pixels within the cleared square. In upcoming pages we'll see two alternative methods for clearRect
(), and we'll also see how to change the color and stroke style of the rendered shapes. Unli...
...And 48 more matches
OS.File for the main thread
d some understanding of the Promise library. See the Promise object documentation for details. Also, OS.File plays very nicely with Task.jsm. Example: Read the contents of a file as text The following snippet opens a file "file.txt" and read its contents as a string, using the default encoding (utf-8). The content is read asynchronously. The result is a Promise. let decoder = new TextDecoder
(); // This decoder can be reused for several reads let promise = OS.File.read("file.txt"); // Read the complete file as an array promise = promise.then( function onSuccess(array) { return decoder.decode(array); // Convert this array to a text } ); This example requires Firefox 18 or a more recent version. Example: Write a string to a file The following snippet writes the...
...n. Example: Write a string to a file The following snippet writes the text "This is some text" to a string "file.txt", using the default encoding (utf-8). ...
...ext"); // Convert the text to an array let promise = OS.File.writeAtomic("file.txt", array, // Write the array atomically to "file.txt", using as temporary {tmpPath: "file.txt.tmp"}); // buffer "file.txt.tmp". ...
...And 47 more matches
Box-shadow generator - CSS: Cascading Style Sheets
g: border-box; box-sizing: border-box; -moz-user-select: text; -webkit-user-select: text; -ms-user-select: text; } #output .css-property { width: 100%; float: left; white-space: pre; } #output .name { width: 35%; float: left; } #output .value { width: 65%; float: left; } JavaScript Content 'use strict'; /** * UI-SlidersManager */ var SliderManager = (function SliderManager
() { var subscribers = {}; var sliders = []; var Slider = function(node) { var min = node.getAttribute('data-min') | 0; var max = node.getAttribute('data-max') | 0; var step = node.getAttribute('data-step') | 0; var value = node.getAttribute('data-value') | 0; var snap = node.getAttribute('data-snap'); var topic = node.getAttribute('data-topic'); this.min = min; this.max = max ...
...ild(pointer); this.pointer = pointer; setMouseTracking(node, updateSlider.bind(this)); sliders[topic] = this; setValue(topic, this.value); } var setButtonComponent = function setButtonComponent(node) { var type = node.getAttribute('data-type'); var topic = node.getAttribute('data-topic'); if (type === "sub") { node.textContent = '-'; node.addEventListener("click", function
() { decrement(topic); }); } if (type === "add") { node.textContent = '+'; node.addEventListener("click", function
() { increment(topic); }); } } var setInputComponent = function setInputComponent(node) { var topic = node.getAttribute('data-topic'); var unit_type = node.getAttribute('data-unit'); var input = document.createElement('input'); var unit = document.c...
...nputComponent(node) { var topic = node.getAttribute('data-topic'); var unit_type = node.getAttribute('data-unit'); var input = document.createElement('input'); var unit = document.createElement('span'); unit.textContent = unit_type; input.setAttribute('type', 'text'); node.appendChild(input); node.appendChild(unit); input.addEventListener('click', function(e) { this.select
(); }); input.addEventListener('change', function(e) { setValue(topic, e.target.value | 0); }); subscribe(topic, function(value) { node.children[0].value = value; }); } var increment = function increment(topic) { var slider = sliders[topic]; if (slider === null || slider === undefined) return; if (slider.value + slider.step <= slider.max) { slider.value += slider.st...
...And 46 more matches
Setting up your own test automation environment - Learn web development
, follow the instructions at How can I add a new folder to my system path? OK, let's try a quick test to make sure everything is working. ...
...dd a new folder to my system path? OK, let's try a quick test to make sure everything is working. ...
...project directory called google_test.js: Give it the following contents, then save it: const webdriver = require('selenium-webdriver'), By = webdriver.By, until = webdriver.until; const driver = new webdriver.Builder
() .forBrowser('firefox') .build
(); driver.get('http://www.google.com'); driver.findElement(By.name('q')).sendKeys('webdriver'); driver.sleep(1000).then(function
() { driver.findElement(By.name('q')).sendKeys(webdriver.Key.TAB); }); driver.findElement(By.name('btnK')).click
(); driver.sleep(2000).then(function
() { driver.getTitle
().then(function(title) { if(title === 'webdriver - Google Search') { console.log('Test passed'); } else { console.log('Test failed'); } driver.quit
(); }); }); In terminal, make sure you are in...
...And 42 more matches
Shell global objects
command-line interpreter when you start the program. Note: this list overlaps with "Built-in functions" in Introduction to the JavaScript shell and is probably not complete. See js/src/shell/js.cpp (around shell_functions) for more. This page lists variables and functions available on SpiderMonkey 53. There may be some difference between each versions. You can get the list of functions by help
() function in js shell. Variables scriptArgs An array that contains arguments passed to js shell. scriptPath A string that is a path of script. console An object that has following property: log Evaluate and print expressions to stdout. This function is an alias of the print
() function. timesAccessed Returns a number that indicates how many times this variable is accessed Perf...
...Bytecode and saveBytecode are true, then the loaded bytecode and the encoded bytecode are compared. and an assertion is raised if they differ. run('foo.js') Run the file named by the first argument, returning the number of of milliseconds spent compiling and executing it. read('bar.js') Reads the file named by the first argument, returning the content of the file as string. readline
() Read a single line from stdin. readlineBuf([ buf ]) Emulate readline
() on the specified string. The first call with a string argument sets the source buffer. Subsequent calls without an argument then read from this buffer line by line. print([exp ...]) Evaluate and print expressions to stdout. printErr([exp ...]) Evaluate and print expressions to stderr. putstr([exp]) Evaluate and print ...
...adlineBuf([ buf ]) Emulate readline
() on the specified string. The first call with a string argument sets the source buffer. Subsequent calls without an argument then read from this buffer line by line. print([exp ...]) Evaluate and print expressions to stdout. printErr([exp ...]) Evaluate and print expressions to stderr. putstr([exp]) Evaluate and print expression without newline. dateNow
() Return the current time with sub-ms precision. help([name ...]) Display usage and help messages. quit
() Quit the shell. assertEq(actual, expected[, msg]) Throw if the first two arguments are not the same (both +0 or both -0, both NaN, or non-zero and ===). startTimingMutator
() Start accounting time to mutator vs GC. ...
...And 42 more matches
Migrating from webkitAudioContext - Web APIs
st code targetting webkitAudioContext to work on the standards based AudioContext out of the box, but it currently doesn't handle all of the cases below. Please consult the README file for that library to see a list of APIs that are automatically handled by it. Changes to the creator methods Three of the creator methods on webkitAudioContext have been renamed in AudioContext. ...
...e standards based AudioContext out of the box, but it currently doesn't handle all of the cases below. Please consult the README file for that library to see a list of APIs that are automatically handled by it. Changes to the creator methods Three of the creator methods on webkitAudioContext have been renamed in AudioContext. createGainNode
() has been renamed to createGain. createDelayNode
() has been renamed to createDelay. ...
...rently doesn't handle all of the cases below. Please consult the README file for that library to see a list of APIs that are automatically handled by it. Changes to the creator methods Three of the creator methods on webkitAudioContext have been renamed in AudioContext. createGainNode
() has been renamed to createGain. createDelayNode
() has been renamed to createDelay. createJavaScriptNode
() has been renamed to createScriptProcessor. ...
...And 42 more matches
nsIMsgDatabase
base.idlScriptable Please add a summary to this article. ...
...rForMessageID(in string messageID); boolean ContainsKey(in nsMsgKey key); nsIMsgDBHdr CreateNewHdr(in nsMsgKey key); void AddNewHdrToDB(in nsIMsgDBHdr newHdr, in boolean notify); nsIMsgDBHdr CopyHdrFromExistingHdr(in nsMsgKey key, in nsIMsgDBHdr existingHdr, in boolean addHdrToDB); void ListAllKeys(in nsMsgKeyArrayRef outputKeys); Native code only! ...
...ean ContainsKey(in nsMsgKey key); nsIMsgDBHdr CreateNewHdr(in nsMsgKey key); void AddNewHdrToDB(in nsIMsgDBHdr newHdr, in boolean notify); nsIMsgDBHdr CopyHdrFromExistingHdr(in nsMsgKey key, in nsIMsgDBHdr existingHdr, in boolean addHdrToDB); void ListAllKeys(in nsMsgKeyArrayRef outputKeys); Native code only! ...
...And 41 more matches
Capabilities, constraints, and settings - Web APIs
des an example we call the Constraint Exerciser. The Constraint Exerciser lets you experiment with the results of different constraint sets being applied to the audio and video tracks coming from the computer's A/V input devices (such as its webcam and microphone). Overview The process works like this (using MediaStreamTrack as an example): If needed, call MediaDevices.getSupportedConstraints
() to get the list of supported constraints, which tells you what constrainable properties the browser knows about. This isn't always necessary, since any that aren't known will simply be ignored when you specify them--but if you have any that you can't get by without, you can start by checking to be sure they're on the list. Once the script knows whether the property or properties it wishes to use...
... any that aren't known will simply be ignored when you specify them--but if you have any that you can't get by without, you can start by checking to be sure they're on the list. ...
... be sure they're on the list. Once the script knows whether the property or properties it wishes to use are supported, it can then check the capabilities of the API and its implementation by examining the object returned by the track's getCapabilities
() method; this object lists each supported constraint and the values or range of values which are supported. Finally, the track's applyConstraints
() method is called to configure the API as desired by specifying the values or ranges of values it wishes to use for any of the constrainable properties about which it has a preference. The track's getConstraints
() method returns the set of constraints passed into the most recent call to applyConstraints
(). This may not represent the actual current state of the track, due to properties whose reque...
...And 41 more matches
Modularization techniques - Archive of obsolete content
l is the nsISupports interface, our equivalent to COM's IUnknown interface. nsISupports provides two key features, interface interrogation and reference counting. Interface interrogation is a simple, uniform mechanism for determining which interfaces a object supports, and for hiding the the mechanics of how the object was implemented. ...
...d reference counting. Interface interrogation is a simple, uniform mechanism for determining which interfaces a object supports, and for hiding the the mechanics of how the object was implemented. Interface interrogation is performed using the QueryInterface
() method. The caller passes in an ID and a pointer to a address to place the resulting interface. If the query is successful, QueryInterface
() will return NS_OK. If the object does not support the given interface, it will return NS_NOINTERFACE. ...
...chanics of how the object was implemented. Interface interrogation is performed using the QueryInterface
() method. The caller passes in an ID and a pointer to a address to place the resulting interface. If the query is successful, QueryInterface
() will return NS_OK. If the object does not support the given interface, it will return NS_NOINTERFACE. Reference counting is performed using the AddRef
() and Release
() methods. An objects reference count generally starts at zero. AddRef
() increments that reference count, and Release
() decrements it. If a call to Release
() causes the reference count to hit zero, the object will generally free itself. ...
...And 40 more matches
Background Tasks API - Web APIs
Concepts and usage The main thread of a Web browser is centered around its event loop. This code draws any pending updates to the Document currently being displayed, runs any JavaScript code the page needs to run, accepts events from input devices, and dispatches those events to the elements that should receive them. ...
...d screen updates are two of the most obvious ways users notice performance issues, it's important for your code to be a good citizen of the Web and help to prevent stalls in the execution of the event loop. In the past, there's been no way to do this reliably other than by writing code that's as efficient as possible and by offloading as much work as possible to workers. Window.requestIdleCallback
() makes it possible to become actively engaged in helping to ensure that the browser's event loop runs smoothly, by allowing the browser to tell your code how much time it can safely use without causing the system to lag. If you stay within the limit given, you can make the user's experience much better. Getting the most out of idle callbacks Because idle callbacks are intended to give your code ...
...ile the browser, your code, and the Web in general will continue to run normally if you go over the specified time limit (even if you go way over it), the time restriction is intended to ensure that you leave the system enough time to finish the current pass through the event loop and get on to the next one without causing other code to stutter or animation effects to lag. Currently, timeRemaining
() has an upper limit of 50 milliseconds, but in reality you will often have less time than that, since the event loop may already be eating into that time on complex sites, with browser extensions needing processor time, and so forth. Avoid making changes to the DOM within your idle callback. By the time your callback is run, the current frame has already finished drawing, and all layout updates a...
...And 40 more matches
Using DTMF with WebRTC - Web APIs
sh to transmit DTMF signals, you first need to decide which track to send them on, since DTMF is sent as a series of out-of-band payloads on the RTCRtpSender responsible for transmitting that track's data to the other peer. Once the track is selected, you can obtain from its RTCRtpSender the RTCDTMFSender object you'll use for sending DTMF. From there, you can simply call RTCDTMFSender.insertDTMF
() to enqueue DTMF signals to be sent on the track to the other peer. The RTCRtpSender will then send the tones to the other peer as packets alongside the track's audio data. Each time a tone is sent, the RTCPeerConnection receives a tonechange event with a tone property specifying which tone finished playing, which is an opportunity to update interface elements, for example. When the tone buffer i...
...cope 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
(). Once the tones finish transmitting, the connection is closed. Note: This example is obviously somewhat contrived, since normally the two RTCPeerConnection objects would exist on different devices, and signaling would be done over the network instead of it all being simply linked up inline as it is here. HTML The HTML for this example is very basic; there are only three elements of importanc...
... = { offerToReceiveAudio: 1, offerToReceiveVideo: 0 }; let dialButton = null; let logElement = null; These are, in order: dialString The DTMF string the caller will send when the "Dial" button is clicked. callerPC and receiverPC The RTCPeerConnection objects representing the caller and the receiver, respectively. ...
...And 40 more matches
StringView - Archive of obsolete content
web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using WebSockets, and so forth, it has become clear that there are times when it would be helpful for JavaScript code to be able to quickly and easily manipulate raw binary data. In the past, this had to be simulated by treating the raw data as a string and using the charCodeAt
() method to read the bytes from the data buffer. However, this is slow and error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32-bit integers or floats). JavaScript typed arrays provide a mechanism for accessing raw binary data much more efficiently. The StringView constructor is one level above typed arrays. T...
...and error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32-bit integers or floats). JavaScript typed arrays provide a mechanism for accessing raw binary data much more efficiently. The StringView constructor is one level above typed arrays. ...
...c License, version 3 or later. ...
...And 39 more matches
Applying styles and colors - Web APIs
eenshot. There is nothing too spectacular happening here. We use the two variables i and j to generate a unique RGB color for each square, and only modify the red and green values. The blue channel has a fixed value. By modifying the channels, you can generate all kinds of palettes. By increasing the steps, you can achieve something that looks like the color palettes Photoshop uses. ...
...uses. function draw
() { var ctx = document.getElementById('canvas').getContext('2d'); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.fillStyle = 'rgb(' + Math.floor(255 - 42.5 * i) + ', ' + Math.floor(255 - 42.5 * j) + ', 0)'; ctx.fillRect(j * 25, i * 25, 25, 25); } } } <canvas id="canvas" width="150" height="150"></canvas> draw
(); The result looks like this: ScreenshotLive sample A strokeStyle example This example is similar to the one above, but uses the strokeStyle property to change the colors of the shapes' outlines. We use the arc
() method to draw circles instead of squares. ...
...'; ctx.fillRect(j * 25, i * 25, 25, 25); } } } <canvas id="canvas" width="150" height="150"></canvas> draw
(); The result looks like this: ScreenshotLive sample A strokeStyle example This example is similar to the one above, but uses the strokeStyle property to change the colors of the shapes' outlines. We use the arc
() method to draw circles instead of squares. ...
...And 39 more matches
Using readable streams - Web APIs
ng it is a matter of just accessing the body property of the response: // Fetch the original image fetch('./tortoise.png') // Retrieve its body as ReadableStream .then(response => response.body) This provides us with a ReadableStream object. Attaching a reader Now we've got our streaming body, reading the stream requires attaching a reader to it. This is done using the ReadableStream.getReader
() method: // Fetch the original image fetch('./tortoise.png') // Retrieve its body as ReadableStream .then(response => response.body) .then(body => { const reader = body.getReader
(); Invoking this method creates a reader and locks it to the stream -- no other reader may read this stream until this reader is released, e.g. by invoking ReadableStreamDefaultReader.releaseLock
(). Also note that th...
...This reads one chunk out of the stream, which you can then do anything you like with. ...
...can be reduced by one step, as response.body is synchronous and so doesn't need the promise: // Fetch the original image fetch('./tortoise.png') // Retrieve its body as ReadableStream .then(response => { const reader = response.body.getReader
(); Reading the stream Now you've got your reader attached, you can read data chunks out of the stream using the ReadableStreamDefaultReader.read
() method. This reads one chunk out of the stream, which you can then do anything you like with. ...
...And 39 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
The sounds are based on a dial-up modem. If you are unaware of how one sounds you can listen to one here. Creating an audio context As you should be used to by now, each Web Audio API app starts with an ...
...plified version of such an instrument. The sounds are based on a dial-up modem. If you are unaware of how one sounds you can listen to one here. Creating an audio context As you should be used to by now, each Web Audio API app starts with an audio context: // for cross browser compatibility const AudioContext = window.AudioContext || window.webkitAudioContext; const audioCtx = new AudioContext
(); The "sweep" -- oscillators, periodic waves, and envelopes For what we will call the "sweep" sound, that first noise you hear when you dial up, we're going to create an oscillator to generate the sound. The OscillatorNode comes with basic waveforms out of the box -- sine, square, triangle or sawtooth. However, instead of using the standard waves that come by default, we're going to create our ...
... the standard waves that come by default, we're going to create our own using the PeriodicWave interface and values set in a wavetable. We can use the BaseAudioContext.createPeriodicWave method to use this custom wave with an oscillator. The periodic wave First of all, we'll create our periodic wave. To do so, We need to pass real and imaginary values into the BaseAudioContext.createPeriodicWave
() method.: let wave = audioCtx.createPeriodicWave(wavetable.real, wavetable.imag); Note: In our example the wavetable is held in a separate JavaScript file (wavetable.js), because there are so many values. It is taken from a repository of wavetables, which can be found in the Web Audio API examples from Google Chrome Labs. The Oscillator Now we can create an OscillatorNode and set its wave t...
...And 39 more matches
Python binding for NSS
hey can be iterated over, indexed by position, or used as slices. NSS/NSPR objects whose collection elements can be referenced by name support associative indexing. NSS/NSPR objects which have "get" and "set" API function calls are exposed as Python properties. All NSS/NSPR Python objects can print their current value by evaluting the Python object in a string context or by using the Python str
() function. Support threading. The Python Global Interpreter Lock (GIL) is released prior to calling NSS/NSPR C functions and reaquired after the NSS/NSPR C function returns. This allows other Python threads to execute during the time a NSS/NSPR function is progress in another thread. Also, any "global" values which are set in python-nss are actually thread-local. Examples of this are the various ...
... ssl_example.py and test_client_server.py where complete data was not read from socket. The Beast CVE fix in NSS causes only one octet to be sent in the first socket packet and then the remaining data is sent normally, this is known as 1/n-1 record splitting. The example and test SSL code sent short messages and then did a sock.recv(1024). We had always received the entire message in one sock.recv
() call because it was so short. But sock.recv
() does not guarantee how much data will be received, thus this was a coding mistake. The solution is straight forward, use newlines as a record separator and call sock.readline
() instead of sock.recv
(). sock.readline
() calls sock.recv
() internally until a complete line is read or the socket is closed. Rewrite setup_certs.py, it was wri...
... Source Download https://ftp.mozilla.org/pub/mozilla.org/security/python-nss/releases/PYNSS_RELEASE_0_14_0/src/ Change Log The primary enhancements in this version is support of certifcate validation, OCSP support, and support for the certificate "Authority Information Access" extension. Enhanced certifcate validation including CA certs can be done via Certificate.verify
() or Certificate.is_ca_cert
(). When cert validation fails you can now obtain diagnostic information as to why the cert failed to validate. This is encapsulated in the CertVerifyLog class which is a iterable collection of CertVerifyLogNode objects. Most people will probablby just print the string representation of the returned CertVerifyLog object. Cert validation logging is handled by the Certifica...
...And 38 more matches
Basic animations - Web APIs
complex frames and the performance depends highly on the speed of the computer it's running on. Basic animation steps These are the steps you need to take to draw a frame: Clear the canvas Unless the shapes you'll be drawing fill the complete canvas (for instance a backdrop image), you need to clear any shapes that have been drawn previously. The easiest way to do this is using the clearRect
() method. Save the canvas state If you're changing any setting (such as styles, transformations, etc.) which affect the canvas state and you want to make sure the original state is used each time a frame is drawn, you need to save that original state. Draw animated shapes The step where you do the actual frame rendering. Restore the canvas state If you've saved the state, restore it before dr...
...alling custom functions. In normal circumstances, we only see these results appear on the canvas when the script finishes executing. For instance, it isn't possible to do an animation from within a for loop. That means we need a way to execute our drawing functions over a period of time. There are two ways to control an animation like this. Scheduled updates First there's the window.setInterval
(), window.setTimeout
(), and window.requestAnimationFrame
() functions, which can be used to call a specific function over a set period of time. setInterval(function, delay) Starts repeatedly executing the function specified by function every delay milliseconds. setTimeout(function, delay) Executes the function specified by function in delay milliseconds. requestAnimationFrame(callback) Tells...
...ed by function every delay milliseconds. setTimeout(function, delay) Executes the function specified by function in delay milliseconds. requestAnimationFrame(callback) Tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. If you don't want any user interaction you can use the setInterval
() function which repeatedly executes the supplied code. If we wanted to make a game, we could use keyboard or mouse events to control the animation and use setTimeout
(). By setting EventListeners, we catch any user interaction and execute our animation functions. In the examples below, we'll use the window.requestAnimationFrame
() method to control the animation. The requestAnimationFrame method p...
...And 38 more matches
this - JavaScript
A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode. In most cases, the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind
() method to set the value of a function's this regardless of how it's called, and ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context). 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/interacti...
...e global object using the global globalThis property, regardless of the current context in which your code is running. Function context Inside a function, the value of this depends on how the function is called. Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser. ...
...s property, regardless of the current context in which your code is running. Function context Inside a function, the value of this depends on how the function is called. Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser. ...
...And 38 more matches
nsIHTMLEditor
e(in nsIDOMNode aNode); boolean canDrag(in nsIDOMEvent aEvent); void checkSelectionStateForAnonymousButtons(in nsISelection aSelection); nsIDOMElement createAnonymousElement(in AString aTag, in nsIDOMNode aParentNode, in AString aAnonClass, in boolean aIsCreatedHidden); nsIDOMElement createElementWithDefaults(in AString aTagName); void decreaseFontSize
(); void doDrag(in nsIDOMEvent aEvent); void getAlignment(out boolean aMixed, out short aAlign); AString getBackgroundColorState(out boolean aMixed); nsIDOMElement getElementOrParentByTagName(in AString aTagName, in nsIDOMNode aNode); AString getFontColorState(out boolean aMixed); AString getFontFaceState(out boolean aMixed); AString get...
...Drag(in nsIDOMEvent aEvent); void getAlignment(out boolean aMixed, out short aAlign); AString getBackgroundColorState(out boolean aMixed); nsIDOMElement getElementOrParentByTagName(in AString aTagName, in nsIDOMNode aNode); AString getFontColorState(out boolean aMixed); AString getFontFaceState(out boolean aMixed); AString getHeadContentsAsHTML
(); AString getHighlightColorState(out boolean aMixed); void getIndentState(out boolean aCanIndent, out boolean aCanOutdent); void getInlineProperty(in nsIAtom aProperty, in AString aAttribute, in AString aValue, out boolean aFirst, out boolean aAny, out boolean aAll); AString getInlinePropertyWithAttrValue(in nsIAtom aProperty, in AString aAttribute, in AString a...
...anIndent, out boolean aCanOutdent); void getInlineProperty(in nsIAtom aProperty, in AString aAttribute, in AString aValue, out boolean aFirst, out boolean aAny, out boolean aAll); AString getInlinePropertyWithAttrValue(in nsIAtom aProperty, in AString aAttribute, in AString aValue, out boolean aFirst, out boolean aAny, out boolean aAll); nsISupportsArray getLinkedObjects
(); void getListItemState(out boolean aMixed, out boolean aLI, out boolean aDT, out boolean aDD); void getListState(out boolean aMixed, out boolean aOL, out boolean aUL, out boolean aDL); AString getParagraphState(out boolean aMixed); nsIDOMElement getSelectedElement(in AString aTagName); nsIDOMElement getSelectionContainer
(); void ignoreSpurious...
...And 37 more matches
nsIXPConnect
js/src/xpconnect/idl/nsIXPConnect.idlNot scriptable Provides the XPConnect service. ...
...underbird 3.3 / SeaMonkey 2.1) To access the XPConnect service, use code like this: nsresult rv; nsCOMPtr<nsIXPConnect> xpconnect = do_GetService(nsIXPConnect::GetCID
(), &rv); if (NS_SUCCEEDED(rv)) { /* use the object */ } Method overview void addJSHolder(in voidPtr aHolder, in nsScriptObjectTracerPtr aTracer); Native code only! void clearAllWrappedNativeSecurityPolicies
(); nsIXPConnectJSObjectHolder createSandbox(in JSContextPtr cx, in nsIPrincipal principal); Native code only! nsIStackFrame createStackFrameLocation(in PRUint32 aLanguage, in string aFilename, in string aFunctionName, in PRInt32 aLineNumber, in nsIStackFrame aCaller); void debugDump(in short depth); void debugDumpEvalInJSStackFrame(in PRUint32 aFrameNumber, in s...
..., in PRUint32 flags, in PRUint32 interfaceCount, [array, size_is(interfaceCount)] in nsIIDPtr interfaceArray); jsval evalInSandboxObject(in AString source, in JSContextPtr cx, in nsIXPConnectJSObjectHolder sandbox, in PRBool returnStringOnly); Native code only! void flagSystemFilenamePrefix(in string aFilenamePrefix, in PRBool aWantNativeWrappers); void GarbageCollect
(); [noscript,notxpcom] void getCaller(out JSContextPtr aJSContext, out JSObjectPtr aObject); JSVal getCOWForObject(in JSContextPtr aJSContext, in JSObjectPtr aParent, in JSObjectPtr aWrappedObj); Native code only! Obsolete since Gecko 2.0 void getDefaultSecurityManager(out nsIXPCSecurityManager aManager, out PRUint16 flags); nsIXPCFunctionThisTranslator getFun...
...And 37 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
et shaderProgram = null; let programInfo = null; let buffers = null; let texture = null; let mouseYaw = 0; let mousePitch = 0; This is followed by a set of constants, mostly to contain various vectors and matrices used while rendering the scene. const viewerStartPosition = vec3.fromValues(0, 0, -10); const viewerStartOrientation = vec3.fromValues(0, 0, 1.0); const cubeOrientation = vec3.create
(); const cubeMatrix = mat4.create
(); const mouseMatrix = mat4.create
(); const inverseOrientation = quat.create
(); const RADIANS_PER_DEGREE = Math.PI / 180.0; The first two--viewerStartPosition and viewerStartOrientation--indicate where the viewer will be placed relative to the center of the space, and the direction in which they'll initially be looking. cubeOrientation will store the current orie...
...nt the rotation to apply to the reference space for the object in the frame being rendered. RADIANS_PER_DEGREEE is the value to multiply an angle in degrees by to convert the angle into radians. The last four variables declared are storage for references to the <div> elements into which we'll output the matrices when we want to show them to the user. ...
...ns. The last four variables declared are storage for references to the <div> elements into which we'll output the matrices when we want to show them to the user. Logging errors A function called LogGLError
() is implemented to provide an easily customized way to output logging information for errors that occur while executing WebGL functions. function LogGLError(where) { let err = gl.getError
(); if (err) { console.error(`WebGL error returned by ${where}: ${err}`); } } This takes as its only input a string, where, which is used to indicate what part of the program generated the error, since similar errors can have in multiple situations. The vertex and fragment shaders The vertex and fragment shaders are both exactly the same as those used in the example for our article Light...
...And 37 more matches
IPDL Tutorial
This generated code manages the details of the underlying communication layer (sockets and pipes), constructing and sending messages, ensuring that all actors adhere to their specifications, and handling many error conditions. The following IPDL code defines a very basic interaction of browser and plugin actors: async protocol PPlugin { child: async Init(nsCString pluginPath); async Shutdown
(); parent: async Ready
(); }; This code declares the PPlugin protocol. Two messages can be sent from the parent to the child, Init
() and Shutdown
(). One message can be sent from the child to the parent, Ready
(). IPDL protocols start with the letter P. The file in which the protocol is declared must have a matching name, PPlugin.ipdl. Generated C++ Code When PPlugin.ipdl is compiled, the head...
...in the ipc/ipdl/_ipdlheaders/ directory of the build tree. The PPluginParent and PPluginChild classes are abstract classes that must be subclassed. Each outgoing message is a C++ method which can be called. ...
...tory of the build tree. The PPluginParent and PPluginChild classes are abstract classes that must be subclassed. Each outgoing message is a C++ method which can be called. ...
...And 36 more matches
Mozilla DOM Hacking Guide
use it safely. When, in JavaScript, a client tries to access a DOM object or a DOM method on a DOM object, the JS engine asks XPConnect to search for the relevant C++ method to call. For example, when we ask for |document.getElementById("myID");|, XPConnect will find that |document| is a property of the window object, so it will look on the interface nsIDOMWindow, and it will find the GetDocument
() method. The return value of GetDocument
() is a nsIDOMDocument. So XPConnect will then try to find a method named GetElementById
() on the nsIDOMDocument interface. And indeed it will find it, and thus call it. This is the schema used most of the time when using W3C DOM objects and methods. It is however different for some DOM Level 0 objects and methods. I'll take two very different examples. The...
...DOM objects and methods. It is however different for some DOM Level 0 objects and methods. I'll take two very different examples. The first one is the window.location object (the same holds true for document.location, actually). We can change the URL of the current window by assigning window.location. In IDL, location is declared to be a readonly attribute. This is because, if we had a SetLocation
() method, it would take an nsIDOMLocation parameter, and not a URL string. Instead, in the helper class for the window object (nsWindowSH, see the next Section), we define the GetProperty
() member function. GetProperty
() is a function used by XPConnect when we are setting an unknown property on the object (window, in our case). In GetProperty
(), we check if the property being set is "location". If ...
...In fact, when setting window.location, we really set window.location.href. This is all possible thanks to the magic of the interaction between XPConnect and the DOM. The second example is the history object. ...
...And 36 more matches
Making asynchronous programming easier with async and await - Learn web development
o parts to using async/await in your code. The async keyword First of all we have the async keyword, which you put in front of a function declaration to turn it into an async function. An async function is a function that knows how to expect the possibility of the await keyword being used to invoke asynchronous code. Try typing the following lines into your browser's JS console: function hello
() { return "Hello" }; hello
(); The function returns "Hello" -- nothing special, right? But what if we turn this into an async function? Try the following: async function hello
() { return "Hello" }; hello
(); Ah. Invoking the function now returns a promise. This is one of the traits of async functions -- their return values are guaranteed to be converted to promises. You can also create an async...
..." -- nothing special, right? But what if we turn this into an async function? ...
... But what if we turn this into an async function? Try the following: async function hello
() { return "Hello" }; hello
(); Ah. Invoking the function now returns a promise. This is one of the traits of async functions -- their return values are guaranteed to be converted to promises. You can also create an async function expression, like so: let hello = async function
() { return "Hello" }; hello
(); And you can use arrow functions: let hello = async
() => { return "Hello" }; These all do basically the same thing. To actually consume the value returned when the promise fulfills, since it is returning a promise, we could use a .then
() block: hello
().then((value) => console.log(value)) or even just shorthand such as hello
().then(console.log) Like we saw in the last article. So the asy...
...And 35 more matches
Functions — reusable blocks of code - Learn web development
d 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 been talking about them very much. Now is the time, however, for us to start talking about functions explicitly, and really exploring their syntax. Pretty much anytime you make use of a JavaScript structure that features a pair of parentheses --
() -- and you're not using a common built-in language structure like a for loop, while or do...while loop, or if...else statement, you are making use of a function. Built-in browser functions We've made use of functions built in to the browser a lot in this course. Every time we manipulated a text string, for example: let myText = 'I am a string'; let newString = myText.replace('string', 'sausage...
... language structure like a for loop, while or do...while loop, or if...else statement, you are making use of a function. Built-in browser functions We've made use of functions built in to the browser a lot in this course. ...
... Note: Feel free to enter these lines into your browser's...
...And 35 more matches
Secure Development Guidelines
within the available storage space MAX + 1 will be 0 and 0 - 1 will be MAX! ...
... newchars = (jschar *) JS_malloc(cx, (newlength + 1) * sizeof(jschar)); ... for (i = 0, ni = 0; i <...
... signed long long -9223372036854775808 - +9223372036854775807 unsigned long long 0 - +18446744073709551615 int vuln_funct(int size) { char buf[1024]; if (size > sizeof(buf) - 1) return -1; } Signedness Issues: Don't mix signed and unsigned integers Use unsigned integers for sizes, offsets, and indexes Casting and Truncation Example: void vuln_funct
() { u_int32_t size1 = 0xffffffff; u_int16_t size2 = size1; void *ptr = malloc(size2); if (!ptr) exit(EXIT_FAILURE); memcpy(ptr, user_data, size1); } Casting Issues: Sign Extension Example: int main
() { int32_t new_size = 0; int8_t size = 0xFF; new_size = size; printf("0x%08x\r\n", new_size); } Casting Issues: Sign Extension Prevention B...
...And 35 more matches
IAccessibleText
IA2_TEXT_BOUNDARY_SENTENCE is optional. When a method doesn't implement this method it must return S_FALSE. ...
... feature would not be implemented by an application. However, if the application developer was not satisfied with how screen readers have handled the reading of sentences this boundary type could be implemented and screen readers could use the application's version of a sentence rather than the screen reader's. The rest of the boundary types must be supported. This enum is used in textBeforeOffset
(), textAtOffset
(), and textAfterOffset
(). Method overview HRESULT addSelection([in] long startOffset, [in] long endOffset ); [propget] HRESULT attributes([in] long offset, [out] long startOffset, [out] long endOffset, [out] BSTR textAttributes ); [propget] HRESULT caretOffset([out] long offset ); [propget] HRESULT characterExtents([in] long offset, [in] enum IA2CoordinateType coordType, [o...
...[propget] HRESULT attributes( [in] long offset, [out] long startOffset, [out] l...
...And 35 more matches
Using Promises - JavaScript
ct representing the eventual completion or failure of an asynchronous operation. Since most people are consumers of already-created promises, this guide will explain consumption of returned promises before explaining how to create them. Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. ...
...y, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. Imagine a function, createAudioFileAsync
(), which asynchronously generates a sound file given a configuration record and two callback functions, one called if the audio file is successfully created, and the other called if an error occurs. ...
...This convention has several advantages. ...
...And 35 more matches
Index - Archive of obsolete content
182 Drag & Drop Code snippets 183 Embedding SVG Code snippets No summary! 184 Examples and demos from articles No summary! 185 File I/O Add-ons, Code snippets, Extensions, Files, Streams, Tutorial No summary! ...
... web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using WebSockets, and so forth, it has become clear that there are times when it would be helpful for JavaScript code to be able to quickly and easily manipulate raw binary data. In the past, this had to be simulated by treating the raw data as a string and using the charCodeAt
() method to read the bytes from the data buffer. 213 Tabbox No summary! 214 Toolbar Add-ons, Code snippets, Extensions, Toolbars No summary! 215 Tree Code snippets No summary! 216 URI parsing No summary! 217 View Source for XUL Applications No summary! 218 Windows Add-ons, Code...
...dangerous) will use all of them. 231 Downloading JSON and JavaScript in extensions AJAX, Add-ons, Extensions, JSON, XMLHttpRequest A common practice found in many extensions is using XMLHttpRequest (or some other mechanism) to download JavaScript or JSON (they are different) from a remote website. Once the content has been downloaded, the extension authors proceed to use eval
() to decode the string content into JavaScript objects. This practice is dangerous and will not, in fact, pass an AMO review. So the extension will not be allowed to move out of the AMO sandbox. 233 Enhanced Extension Installation Add-ons, Extensions No summary! 234 Extension Etiquette Add-ons, Extensions, Guide No summary! 235 Extension Library ...
...And 34 more matches
Inheritance in JavaScript - Learn web development
members are inherited going up a chain. But mostly this has involved built-in browser functions. How do we create an object in JavaScript that inherits from another object? Let's explore how to do this with a concrete example. Getting started First of all, make yourself a local copy of our oojs-class-inheritance-start.html file (see it running live also). Inside here you'll find the same Person
() constructor example that we've been using all the way through the module, with a slight difference -- we've defined only the properties inside the constructor: function Person(first, last, age, gender, interests) { this.name = { first, last }; this.age = age; this.gender = gender; this.interests = interests; }; The methods are all defined on the constructor's prototype. For ex...
...ll the way through the module, with a slight difference -- we've defined only the properties inside the constructor: function Person(first, last, age, gender, interests) { this.name = { first, last }; this.age = age; this.gender = gender; this.interests = interests; }; The methods are all defined on the constructor's prototype. For example: Person.prototype.greeting = function
() { alert('Hi! I\'m ' + this.name.first + '.'); }; Note: In the source code, you'll also see bio
() and farewell
() methods defined. Later you'll see how these can be inherited by other constructors. Say we wanted to create a Teacher class, like the one we described in our initial object-oriented definition, which inherits all the members from Person, but also includes: A new property, subje...
...e, you'll also see bio
() and farewell
() methods defined. Later you'll see how these can be inherited by other constructors. Say we wanted to create a Teacher class, like the one we described in our initial object-oriented definition, which inherits all the members from Person, but also includes: A new property, subject -- this will contain the subject the teacher teaches. An updated greeting
() method, which sounds a bit more formal than the standard greeting
() method -- more suitable for a teacher addressing some students at school. ...
...And 34 more matches
React interactivity: Events and state - Learn web development
learn about handling events and state in React, and use those to start making the case study app interactive. Handling events If you've only written vanilla JavaScript before now, you might be used to having a separate JavaScript file, where you query for some DOM nodes and attach listeners to them. For example: const btn = document.querySelector('button'); btn.addEventListener('click',
() => { alert("hi!"); }); In React, we write event handlers directly on the elements in our JSX, like this: <button type="button" onClick={
() => alert("hi!")} > Say hi! </button> Note: This may seem counter-intuitive regarding best-practice advice that tends to advise against use of inline event handlers on HTML, but remember that JSX is actually part of your JavaScript. In the above e...
...re of onClick is important -- JSX will not recognize onclick (again, it is already used in JavaScript for a specific purpose, which is related but different -- standard onclick handler properties). All browser events follow this format in JSX - on, followed by the name of the event. Let's apply this to our app, starting in the Form.js component. ...
...k (again, it is already used in JavaScript for a specific purpose, which is related but different -- standard onclick handler properties). All browser events follow this format in JSX - on, followed by the name of the event. Let's apply this to our app, starting in the Form.js component. Handling form submission At the top of the Form
() component function, create a function named handleSubmit
(). ...
...And 34 more matches
Using Web Workers - Web APIs
/O using XMLHttpRequest (although the responseXML and channel attributes are always null). Once created, a worker can send messages to the JavaScript code that created it by posting messages to an event handler specified by that code (and vice versa). 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 dedicat...
...a worker, or use some default methods and properties of the window object. But you can use a large number of items available under window, including WebSockets, and data storage mechanisms like IndexedDB. See Functions and classes available to workers for more details. Data is sent between workers and the main thread via a system of messages -- both sides send their messages using the postMessage
() method, and respond to messages via the onmessage event handler (the message is contained within the Message event's data attribute.) The data is copied rather than shared. Workers may, in turn, spawn new workers, as long as those workers are hosted within the same origin as the parent page. In addition, workers may use XMLHttpRequest for network I/O, with the exception that the responseXML and ...
...u to basic worker concepts. More advanced details are covered later on in the article. Worker feature detection For slightly more controlled error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following (main.js): if (window.Worker) { ... } Spawning a dedicated worker Creating a new worker is simple. ...
...And 34 more matches
Closures - JavaScript
closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time. ...
...rounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time. ...
... lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time. ...
...And 34 more matches
imgIContainer
2.0 void appendPalettedFrame(in PRInt32 aX, in PRInt32 aY, in PRInt32 aWidth, in PRInt32 aHeight, in gfxImageFormat aFormat, in PRUint8 aPaletteDepth, [array, size_is(imageLength)] out PRUint8 imageData, out unsigned long imageLength, [array, size_is(paletteLength)] out PRUint32 paletteData, out unsigned long paletteLength); Native code only! ...
...PRInt32 aWidth, in PRInt32 aHeight, in gfxImageFormat aFormat, in PRUint8 aPaletteDepth, [array, size_is(imageLength)] out PRUint8 imageData, out unsigned long imageLength, [array, size_is(paletteLength)] out PRUint32 paletteData, out unsigned long paletteLength); Native code only! Obsolete since Gecko 2.0 void clear
(); Obsolete since Gecko 1.9.2 gfxImageSurface copyCurrentFrame
(); Native code only! ...
...y, size_is(paletteLength)] out PRUint32 paletteData, out unsigned long paletteLength); Native code only! Obsolete since Gecko 2.0 void clear
(); Obsolete since Gecko 1.9.2 gfxImageSurface copyCurrentFrame
(); Native code only! Obsolete since Gecko 2.0 gfxImageSurface copyFrame(in PRUint32 aWhichFrame, in PRUint32 aFlags); Native code only! void decodingComplete
(); Obsolete since Gecko 2.0 void draw(in gfxContext aContext, in gfxGraphicsFilter aFilter, [const] in gfxMatrix aUserSpaceToImageSpace, [const] in gfxRect aFill, [const] in nsIntRect aSubimage, [const] in nsIntSize aViewportSize, in PRUint32 aFlags); Native code only! void endFrameDecode(in unsigned long framenumber); Obsolete since Gecko 2.0 void ensureCleanFrame(in un...
...And 33 more matches
Working with data
. These are JavaScript constructors; as such, they're callable functions that you can use to create new CData objects of that type. There are several ways you can go about creating new CData objects. Creating uninitialized CData objects There are three forms of the syntax for creating CData objects without immediately assigning them a value: var myCDataObj = new type; var myCDataObj = new type
(); var myCDataObj = type
(); These all do the same thing: they return a new CData object of the specified type, whose data buffer has been populated entirely with zeroes. Note: If type.size is undefined, creating a new object this way will throw a TypeError exception. Creating initialized CData objects Similarly, you can initialize CData objects with specific values at the type of creation by s...
...void_t, a TypeError is thrown. Example: Creating an array let arrayType = ctypes.ArrayType(ctypes.int32_t); let myArray = new arrayType(5); At this point, myArray.length is 5; there are 5 entries in the array. myArray.constructor.size is 20; the total size of the array's data buffer is 20 bytes (5 entries, 4 bytes apiece). ...
...eating an array let arrayType = ctypes.ArrayType(ctypes.int32_t); let myArray = new arrayType(5); At this point, myArray.length is 5; there are 5 entries in the array. myArray.constructor.size is 20; the total size of the array's data buffer is 20 bytes (5 entries, 4 bytes apiece). ...
...And 33 more matches
WebGLRenderingContext - Web APIs
The WebGLRenderingContext interface provides an interface to the OpenGL ES 2.0 graphics rendering context for the drawing surface of an HTML <canvas> element. To get an access to a WebGL context for 2D and/or 3D graphics rendering, call getContext
() on a <canvas> element, supplying "webgl" as the argument: var canvas = document.getElementById('myCanvas'); var gl = canvas.getContext('webgl'); Once you have the WebGL rendering context for a canvas, you can render within it. The WebGL tutorial has more information, examples, and resources on how to get started with WebGL. If you require a WebGL 2.0 context, see WebGL2RenderingContext; this supplies access to an implementation of OpenGL ES 3.0 graphics. Constants See the WebGL constants page. The WebGL context The following propertie...
...n implementation of OpenGL ES 3.0 graphics. Constants See the WebGL constants page. The WebGL context The following properties and methods provide general information and functionality to deal with the WebGL context: WebGLRenderingContext.canvas A read-only back-reference to the HTMLCanvasElement. Might be null if it is not associated with a <canvas> element. WebGLRenderingContext.commit
() Pushes frames back to the original HTMLCanvasElement, if the context is not directly fixed to a specific canvas. WebGLRenderingContext.drawingBufferWidth The read-only width of the current drawing buffer. Should match the width of the canvas element associated with this context. WebGLRenderingContext.drawingBufferHeight The read-only height of the current drawing buffer. Should match t...
...cific canvas. WebGLRenderingContext.drawingBufferWidth The read-only width of the current drawing buffer. Should match the width of the canvas element associated with this context. WebGLRenderingContext.drawingBufferHeight The read-only height of the current drawing buffer. Should match the height of the canvas element associated with this context. ...
...And 33 more matches
Border-image generator - CSS: Cascading Style Sheets
gin: 0; color: #555; font-size: 14px; line-height: 18px; float: left; } #output .css-property .name { width: 30%; font-weight: bold; text-align: right; float: left; } #output .css-property .value { width: 65%; padding: 0 2.5%; word-break: break-all; float: left; } JavaScript Content 'use strict'; /** * UI-SlidersManager */ var InputSliderManager = (function InputSliderManager
() { var subscribers = {}; var sliders = []; var InputComponent = function InputComponent(obj) { var input = document.createElement('input'); input.setAttribute('type', 'text'); input.style.width = 50 + obj.precision * 10 + 'px'; input.addEventListener('click', function(e) { this.select
(); }); input.addEventListener('change', function(e) { var value = parseFloat(e.target.val...
... if (name) { var info = document.createElement('span'); info.className = 'ui-input-slider-info'; info.textContent = name; node.appendChild(info); } node.appendChild(slider_left); node.appendChild(input); node.appendChild(slider_right); this.input = input; sliders[topic] = this; setValue(topic, value); }; InputSlider.prototype.setInputValue = function setInputValue
() { this.input.value = this.value.toFixed(this.precision) + this.unit; }; var setValue = function setValue(topic, value, send_notify) { var slider = sliders[topic]; if (slider === undefined) return; value = parseFloat(value.toFixed(slider.precision)); if (value > slider.max) value = slider.max; if (value < slider.min) value = slider.min; slider.value = value; slider.node.se...
...n) + this.unit; }; var setValue = function setValue(topic, value, send_notify) { var slider = sliders[topic]; if (slider === undefined) return; value = parseFloat(value.toFixed(slider.precision)); if (value > slider.max) value = slider.max; if (value < slider.min) value = slider.min; slider.value = value; slider.node.setAttribute('data-value', value); slider.setInputValue
(); if (send_notify === false) return; notify.call(slider); }; var setMax = function setMax(topic, value) { var slider = sliders[topic]; if (slider === undefined) return; slider.max = value; setValue(topic, slider.value); }; var setMin = function setMin(topic, value) { var slider = sliders[topic]; if (slider === undefined) return; slider.min = value; setValue(t...
...And 33 more matches
Using Fetch - Web APIs
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch
() method that provides an easy, logical way to fetch resources asynchronously across the network. This kind of functionality was previously achieved using XMLHttpRequest. Fetch provides a better alternative that can be easily used by other technologies such as Service Workers. Fetch also provides a single logical place to define other HTTP-related concepts such as CORS and extensions to HTTP. The fetch specification differs from jQuery.ajax
() in three main ways: The Promise returned from fetch
() won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok sta...
...Set-Cookie headers from other sites are silently ignored. fetch won't send cookies, unless you set the credentials init option. (Since Aug 25, 2017. ...
...kie headers from other sites are silently ignored. fetch won't send cookies, unless you set the credentials init option. (Since Aug 25, 2017. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.) A basic fetch request is really simple to set up. Have a look at the following code: fetch('http://example.com/movies.json') .then(response => response.json
()) .then(data => console.log(data)); Here we are fetching a JSON file across the network and printing it to the console. The simplest use of fetch
() takes one argument -- the path to the resource you want to fetch -- and returns a promise containing the response (a Response object). This is just an HTTP response, not the actual JSON. To extract the JSON body content from the response, we use t...
...And 32 more matches
Using files from web applications - Web APIs
The multiple attribute on the input element allows the user to select multiple files. Accessing the first selected file using a classical DOM selector: const selectedFile = document.getElementById('input').files[0]; Accessing selected file(s) on a change event It is also possible (but not mandatory) to access the FileList through the change event. ...
....getElementById('input').files[0]; Accessing selected file(s) on a change event It is also possible (but not mandatory) to access the FileList through the change event. You need to use EventTarget.addEventListener
() to add the change event listener, like this: const inputElement = document.getElementById("input"); inputElement.addEventListener("change", handleFiles, false); function handleFiles
() { const fileList = this.files; /* now you can work with the file list */ } Getting information about selected file(s) The FileList object provided by the DOM lists all of the files selected by the user, each specified as a File object. You can determine how many files the user selected by checking the value of the file list's length attribute: const numFiles = fileList.length; Individual Fi...
...ml> <html> <head> <meta charset="UTF-8"> <title>File(s) size</title> </head> <body> <form name="uploadForm"> <div> <input id="uploadInput" type="file" name="myFiles" multiple> selected files: <span id="fileNum">0</span>; total size: <span id="fileSize">0</span> </div> <div><input type="submit" value="Send file"></div> </form> <script> function updateSize
() { let nBytes = 0, oFiles = this.files, nFiles = oFiles.length; for (let nFileId = 0; nFileId < nFiles; nFileId++) { nBytes += oFiles[nFileId].size; } let sOutput = nBytes + " bytes"; // optional code for multiples approximation const aMultiples = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]; for (nMultiple = 0, nApprox = nBytes / 1024;...
...And 32 more matches
Using XMLHttpRequest - Web APIs
ts in order to exchange data between the web site and a server. Examples of both common and more obscure use cases for XMLHttpRequest are included. To send an HTTP request, create an XMLHttpRequest object, open a URL, and send the request. After the transaction completes, the object will contain useful information such as the response body and the HTTP status of the result. function reqListener
() { console.log(this.responseText); } var oReq = new XMLHttpRequest
(); oReq.addEventListener("load", reqListener); oReq.open("GET", "http://www.example.org/example.txt"); oReq.send
(); Types of requests A request made via XMLHttpRequest can fetch the data in one of two ways, asynchronously or synchronously. The type of request is dictated by the optional async argument (the third argument) that...
...If this argument is true or not specified, the XMLHttpRequest is processed asynchronously, otherwise the process is handled synchronously. A detailed discussion and demonstrations of these two types of requests can be found on the synchronous and asynchronous requests page. Do not use synchronous requests outside Web Workers. ...
...ue to the negative effects to the user experience. Note: The constructor function XMLHttpRequest isn't limited to only XML documents. It starts with "XML" because when it was created the main format that was originally used for Asynchronous Data Exchange were XML Handling responses There are several types of response attributes defined by the living standard specification for the XMLHttpRequest
() constructor. These tell the client making the XMLHttpRequest important information about the status of the response. Some cases where dealing with non-text response types may involve some manipulation and analysis are outlined in the following sections. Analyzing and manipulating the responseXML property If you use XMLHttpRequest to get the content of a remote XML document, the responseXML prop...
...And 32 more matches
CustomizableUI.jsm
aToolbar, aExistingChildren); void registerMenuPanel(aPanel); void unregisterArea(aAreaId, aDestroyPlacements); void addWidgetToArea(aWidgetId, aAreaId, [optional] aPosition); void removeWidgetFromArea(aWidgetId); void moveWidgetWithinArea(aWidgetId, aPosition); void ensureWidgetPlacedInWindow(aWidgetId, aWindow); void beginBatchUpdate
(); void endBatchUpdate(aForceDirty); WidgetGroupWrapper createWidget(aWidgetSpecification); void destroyWidget(aWidgetId); WidgetGroupWrapper getWidget(aWidgetId); Array getUnusedWidgets(aWindow); Array getWidgetIdsInArea(aAreaId); Array getWidgetsInArea(aAreaId); String getAreaType(aAreaId); DOMElement getCustomizeTar...
... WidgetGroupWrapper createWidget(aWidgetSpecification); void destroyWidget(aWidgetId); WidgetGroupWrapper getWidget(aWidgetId); Array getUnusedWidgets(aWindow); Array getWidgetIdsInArea(aAreaId); Array getWidgetsInArea(aAreaId); String getAreaType(aAreaId); DOMElement getCustomizeTargetForArea(aAreaId, aWindow); void reset
(); void undoReset
(); void removeExtraToolbar
(); Object getPlacementOfWidget(aWidgetId); bool isWidgetRemovable(aWidgetNodeOrWidgetId); bool canWidgetMoveToArea(aWidgetId); void getLocalizedProperty(aWidget, aProp, aFormatArgs, aDef); void hidePanelForNode(aNode); bool isSpecialWidget(aWidgetId); void addPanelCloseListe...
... Parameters aAreaId The name of the area to register. Can only contai...
...And 31 more matches
source-editor.jsm
source:///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. ...
... Search operations Number find(String aString, [optional] Object options); Number findNext(Boolean aWrap); Number findPrevious(Boolean aWrap); Event management void addEventListener(String aEventType, Function aCallback); void removeEventListener(String aEventType, Function aCallback); Undo stack operations Boolean canRedo
(); Boolean canUndo
(); void endCompoundChange
(); Boolean redo
(); void resetUndo
(); void startCompoundChange
(); Boolean undo
(); Display management operations void focus
(); Number getTopIndex
(); Boolean hasFocus
(); void setTopIndex(Number aTopIndex); Content management operations Number ...
...oolean canUndo
(); void endCompoundChange
(); Boolean redo
(); void resetUndo
(); void startCompoundChange
(); Boolean undo
(); Display management operations void focus
(); Number getTopIndex
(); Boolean hasFocus
(); void setTopIndex(Number aTopIndex); Content management operations Number getCharCount
(); String getIndentationString
(); String getLineDelimiter
(); Number getLineCount
(); Number getLineEnd(Number aLineIndex, Boolean aIncludeDelimiter); Number getLineStart(Number aLineIndex); String getMode
(); String getText([optional] Number aStart, [optional] Number aEnd); String getSelectedText
(); void setMode(Strin...
...And 31 more matches
nsIMsgIncomingServer
nsIMsgIncomingServer mailnews/base/public/nsIMsgIncomingServer.idlScriptable ??? Add brief description of Interface ??? ...
... nsIMsgIncomingServer mailnews/base/public/nsIMsgIncomingServer.idlScriptable ??? Add brief description of Interface ??? ...
... nsIMsgIncomingServer mailnews/base/public/nsIMsgIncomingServer.idlScriptable ??? Add brief description of Interface ??? ...
...And 31 more matches
Using the CSS Painting API - Web APIs
The CSS Paint API is designed to enable developers to programmatically define images which can then be used anywhere a CSS image can be invoked, such as CSS background-image, border-image, mask-image, etc. To programmatically create an image used by a CSS stylesheet we need to work through a few steps: Define a paint worklet using the registerPaint
() function Register the worklet Include the paint
() CSS function To elaborate over these steps, we're going to start by creating a half-highlight background, like on this header: CSS paint worklet In an external script file, we employ the registerPaint
() function to name our CSS Paint worklet. It takes two parameters. The first is the name we give the worklet -- this is the name we will use in our CSS as the parameter of the pa...
...The second parameter is the class that does all the magic, defining the context options and what to paint to the two-dimensional canvas that will be our image. registerPaint('headerHighlight', class { /* define if alphatransparency is allowed alpha is set to true by default. ...
...econd parameter is the class that does all the magic, defining the context options and what to paint to the two-dimensional canvas that will be our image. registerPaint('headerHighlight', class { /* define if alphatransparency is allowed alpha is set to true by default. ...
...And 31 more matches
Timing element visibility with the Intersection Observer API - Web APIs
ight: 20px; width: 120px; font-size: 14px; bottom: 30px; border: 1px solid black; background-color: rgba(255, 255, 255, 0.5); } There's nothing magic in here. It's fairly basic CSS. Tying it together with JavaScript That brings us to the JavaScript code which makes everything work. Let's start with the global variables: let contentBox; let nextArticleID = 1; let visibleAds = new Set
(); let previouslyVisibleAds = null; let adObserver; let refreshIntervalID = 0; These are used as follows: contentBox A reference to the <main> element's HTMLElement object in the DOM. This is where we'll insert the articles and ads. nextArticleID Each article is given a unique ID number; this variable tracks the next ID to use, starting with 1. visibleAds A Set which we'll use to track th...
...ads currently visible on the screen. previouslyVisibleAds Used to temporarily store the list of visible ads while the document is not visible (for example, if the user has tabbed to another page). adObserver Will hold our IntersectionObserver used to track the intersection between the ads and the <main> element's bounds. refreshIntervalID Used to store the interval ID returned by setInterval
(). ...
...visible (for example, if the user has tabbed to another page). adObserver Will hold our IntersectionObserver used to track the intersection between the ads and the <main> element's bounds. refreshIntervalID Used to store the interval ID returned by setInterval
(). This interval will be used to trigger our periodic refreshes of the ads' content. ...
...And 31 more matches
panel - Archive of obsolete content
A panel is a dialog. Its content is specified as HTML and you can execute scripts in it, so the appearance and behavior of the panel is limited only by what you can do using HTML, CSS, and JavaScript. ...
...ted, before the panel is shown, and the content remains loaded when a panel is hidden, so it is possible to keep a panel around in the background, updating its content as appropriate in preparation for the next time it is shown. Your add-on can receive notifications when a panel is shown or hidden by listening to its show and hide events. Opening a panel will close any panel created by the Panel
() constructor that is already open, even if that panel was opened by a different Add-on SDK based extension. If you want to close an existing panel without opening a new one, you can call the hide
() or the destroy
() method. Panel content The panel's content is specified as HTML, which is loaded from the URL supplied in the contentURL option to the panel's constructor. You can load remote HTML i...
...he hide
() or the destroy
() method. Panel content The panel's content is specified as HTML, which is loaded from the URL supplied in the contentURL option to the panel's constructor. You can load remote HTML into the panel: var myPanel = require("sdk/panel").Panel({ width: 180, height: 180, contentURL: "https://en.wikipedia.org/w/index.php?title=Jetpack&useformat=mobile" }); myPanel.show
(); You can also load HTML that's been packaged with your add-on, and this is most probably how you will create dialogs. ...
...And 30 more matches
Fetching data from the server - Learn web development
load a different verse of the poem (which you may well recognize) via XHR when it's selected in the drop-down menu. Just inside the <script> element, add the following code. This stores a reference to the <select> and <pre> elements in constants and defines an onchange event handler function so that when the select's value is changed, its value is passed to an invoked function updateDisplay
() as a parameter. const verseChoose = document.querySelector('select'); const poemDisplay = document.querySelector('pre'); verseChoose.onchange = function
() { const verse = verseChoose.value; updateDisplay(verse); }; Let's define our updateDisplay
() function. First of all, put the following beneath your previous code block -- this is the empty shell of the function. Note: Steps 4 - 9 ...
...xample "Verse 1". The corresponding verse text file is "verse1.txt", and is in the same directory as the HTML file, therefore just the file name will do. However, web servers tend to be case sensitive, and the file name doesn't have a space in it. To convert "Verse 1" to "verse1.txt" we need to convert the V to lower case, remove the space, and add .txt on the end. This can be done with replace
(), toLowerCase
(), and simple string concatenation. Add the following lines inside your updateDisplay
() function: verse = verse.replace(" ", ""); verse = verse.toLowerCase
(); let url = verse + '.txt'; To begin creating an XHR request, you need to create a new request object using the XMLHttpRequest
() constructor. You can call this object anything you like, but we'll call it request to keep ...
...We'll just use the GET method here and set the URL as our url variable. ...
...And 30 more matches
JSAPI Cookbook
mon JavaScript idioms. Note: The FOSS wiki page contains a few links to other libraries and programs that can make life easier when using SpiderMonkey and JSAPI. Basics Working with values The basic, undifferentiated value type in the JSAPI is JS::Value. ...
...S::Value. ...
...lue has a particular type, use a correspondingly named member testing function: // JavaScript var v = computeSomeValue
(); var isString = typeof v === "string"; var isNumber = typeof v === "number"; var isNull = v === null; var isBoolean = typeof v === "boolean"; var isObject = typeof v === "object" && v !== null; /* JSAPI */ JS::RootedValue v(cx, ComputeSomeValue
()); bool isString = v.isString
(); bool isNumber = v.isNumber
(); bool isInt32 = v.isInt32
(); // NOTE: internal representation, not numeric value bool isNull = v.isNull
(); bool isBoolean = v.isBoolean
(); bool isObject = v.isObject
(); // NOTE: not broken like typeof === "object" is :-) To set a value use a correspondingly named member mutator function, or assign the result of the correspondingly named standalone function: // Java...
...And 30 more matches
Functions - JavaScript
JavaScript, a function can be defined based on a condition. For example, the following function definition defines myFunc only if num equals 0: var myFunc; if (num === 0) { myFunc = function(theObject) { theObject.make = 'Toyota'; } } In addition to defining functions as described here, you can also use the Function constructor to create functions from a string at runtime, much like eval
(). A method is a function that is a property of an object. Read more about objects and methods in Working with objects. Calling functions Defining a function does not execute it. Defining it simply names the 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 fun...
...ed, 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. function funcName
(){}). The code below will not work. This means that function hoisting only works with function declarations--not with function expressions. console.log(square) // square is hoisted with an initial value undefined. console.log(square(5)) // Uncaught TypeError: square is not a function const square = function(n) { return n * n; } The arguments of a function are not limited to strings and nu...
...isting only works with function declarations--not with function expressions. console.log(square) // square is hoisted with an initial value undefined. console.log(square(5)) // Uncaught TypeError: square is not a function const square = function(n) { return n * n; } The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The show_props
() function (defined in Working with objects) is an example of a function that takes an object as an argument. A function can call itself. For example, here is a function that computes factorials recursively: function factorial(n) { if ((n === 0) || (n === 1)) return 1; else return (n * factorial(n - 1)); } You could then compute the factorials of 1 through 5 as follows: var a, b, c...
...And 30 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
xplorer, also support pre-W3C APIs and have never added extensive support for the W3C-compliant ones. Before I go into the differences between Mozilla and Internet Explorer, I'll cover some basic ways you can make a Web application extensible in order to add new browser support later. Since different browsers sometimes use different APIs for the same functionality, you can often find multiple if
() else
() blocks throughout the code to differentiate between the browsers. The following code shows blocks designated for Internet Explorer: . . . var elm; if (ns4) elm = document.layers["myID"]; else if (ie4) elm = document.all["myID"] The above code isn't extensible, so if you want it to support a new browser, you must update these blocks throughout the Web application. The easiest way ...
...esignated for Internet Explorer: . . . var elm; if (ns4) elm = document.layers["myID"]; else if (ie4) elm = document.all["myID"] The above code isn't extensible, so if you want it to support a new browser, you must update these blocks throughout the Web application. The easiest way to eliminate the need to recode for a new browser is to abstract out functionality. Rather than multiple if
() else
() blocks, you increase efficiency by taking common tasks and abstracting them out into their own functions. Not only does this make the code easier to read, it simplifies adding support for new clients: var elm = getElmById("myID"); function getElmById(aID){ var element = null; if (isMozilla || isIE5) element = document.getElementById(aID); else if (isNetscape4) element = do...
...upport the Netscape 4 document.layers method and Internet Explorer's document.all. While document.getElementById lets you retrieve one element, you can also use document.layers and document.all to obtain a list of all document elements with a certain tag name, such as all <div> elements. The W3C DOM Level 1 method gets references to all elements with the same tag name through getElementsByTagName
(). The method returns an array in JavaScript, and can be called on the document element or other nodes to search only their subtree. To get an array of all elements in the DOM tree, you can use getElementsByTagName("*"). The DOM Level 1 methods, as shown in Table 1, are commonly used to move an element to a certain position and toggle its visibility (menus, animations). Netscape 4 used the <layer>...
...And 29 more matches
Bytecode Descriptions
l 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
()/.valueOf
() methods and can throw. The result on success is always a Number. (Per spec, unary - supports BigInts, but unary + does not.) Format: JOF_IC Neg Stack: val => (-val) The unary - operator. Convert val to a numeric value, then push -val. The conversion can call .toString
()/.valueOf
() methods and can throw. The result on success is always numeric. Format: JOF_IC BitNot Stack: val => ...
...The result on success is always an Int32 or BigInt value. Format: JOF_IC Not Stack: val => (!val) The logical NOT operator (!). val is first converted with ToBoolean, then logically negated. ...
...The result on success is always an Int32 or BigInt value. Format: JOF_IC Not Stack: val => (!val) The logical NOT operator (!). val is first converted with ToBoolean, then logically negated. ...
...And 29 more matches
Add to iPhoto
bjects, among others. These are core system data formats that are used by other frameworks, and we'll be making use of them. The Core Foundation API is implemented by the CoreFoundation object, which consists of two methods to initialize and shut down the library, a reference to the library, and all the types and methods declared to support Core Foundation. ...
...d by other frameworks, and we'll be making use of them. The Core Foundation API is implemented by the CoreFoundation object, which consists of two methods to initialize and shut down the library, a reference to the library, and all the types and methods declared to support Core Foundation. ...
... CFRange CFRange is a structure that identifies a range; that is, it identifies an offset to an item in a list and a number of items. ...
...And 29 more matches
Extending a Protocol
are implementing DOM/Web APIs that need to, for example, send a message to the OS or spin up something off the main thread - so it's biased towards supporting W3C/WHATWG DOM APIs. What are we going to implement? tl:dr: you can see the final implementation of PEcho.ipdl as a diff in Phabricator. To make this tutorial less abstract (more fun!), we are going to implement a JS method called echo
() on the Navigator interface. The method will take one argument, a DOMString, which we will pass to the parent process. Then we will send that same string back to the child process. The WebIDL for this will be: partial interface Navigator { Promise<DOMString> echo(DOMString someString); }; Learning goals are: Extending an existing IPDL protocol. Simple message passing. Working with MozPr...
...ending an existing IPDL protocol. Simple message passing. Working with MozPromises and JS promises. Managing child actors with reference counting. Visually, it's going to look something like this (except for the Operating System bit, which we are not actually going to do - just to illustrate what we could do): Let's start by implementing the WebIDL above. ...
...ating System bit, which we are not actually going to do - just to illustrate what we could do): Let's start by implementing the WebIDL above. Implementing the navigator.echo
() In your favorite editor, open dom/webidl/Navigator.webidl At the end of the file, add: partial interface Navigator { [Throws] Promise<DOMString> echo(DOMString aString); }; Now we need to implement the Echo
() method in C++, so open up ./dom/base/Navigator.h and let's add the method definition, so under public:: already_AddRefed<Promise> Echo(const nsAString& aString, ErrorResult& aRv); We use nsAString& as the DOMString comes in from JS as UTF-16. This will matter later, as we will need to convert it to UTF-8 (using nsCString) to send it to the parent process. Now let's implement the method i...
...And 28 more matches
RTCPeerConnection - Web APIs
n" target="_top"><rect x="151" y="1" width="170" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="236" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">RTCPeerConnection</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} ConstructorRTCPeerConnection
() The RTCPeerConnection
() constructor returns a newly-created RTCPeerConnection, which represents a connection between the local device and a remote peer.PropertiesAlso inherits properties from: EventTargetcanTrickleIceCandidatesThe read-only RTCPeerConnection property canTrickleIceCandidates returns a Boolean which indicates whether or not the remote peer can accept trickled ICE candidates.connec...
...tion object describing the remote end of the connection as it was most recently successfully negotiated since the last time the RTCPeerConnection finished negotiating and connecting to a remote peer. Also included is a list of any ICE candidates that may already have been generated by the ICE agent since the offer or answer represented by the description was first instantiated.getDefaultIceServers
() The getDefaultIceServers
() method of the RTCPeerConnection interface returns an array of objects based on the RTCIceServer dictionary, which indicates what, if any, ICE servers the browser will use by default if none are provided to the RTCPeerConnection in its RTCConfiguration. However, browsers are not required to provide any default ICE servers at all.iceConnectionState Read only The read-onl...
...ersAlso inherits event handlers from: EventTargetonaddstream The RTCPeerConnection.onaddstream event handler is a property containing the code to execute when the addstream event, of type MediaStreamEvent, is received by this RTCPeerConnection. Such an event is sent when a MediaStream is added to this connection by the remote peer. The event is sent immediately after the call setRemoteDescription
() and doesn't wait for the result of the SDP negotiation.onconnectionstatechangeThe RTCPeerConnection.onconnectionstatechange property specifies an EventHandler which is called to handle the connectionstatechange event when it occurs on an instance of RTCPeerConnection. This happens whenever the aggregate state of the connection changes.ondatachannel The RTCPeerConnection.ondatachannel property is...
...And 28 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
is obviously not a real one; you'll need to replace stun.myserver.tld with the address of a real STUN server. const constraints = { audio: true, video: true }; const config = { iceServers: [{ urls: "stun:stun.mystunserver.tld" }] }; const selfVideo = document.querySelector("video.selfview"); const remoteVideo = document.querySelector("video.remoteview"); const signaler = new SignalingChannel
(); const pc = new RTCPeerConnection(config); This code also gets the <video> elements using the classes "selfview" and "remoteview"; these will contain, respectively, the local user's self-view and the view of the incoming stream from the remote peer. Connecting to a remote peer The start
() function shown here can be called by either of the two end-points that want to talk to one another. It do...
...s using the classes "selfview" and "remoteview"; these will contain, respectively, the local user's self-view and the view of the incoming stream from the remote peer. Connecting to a remote peer The start
() function shown here can be called by either of the two end-points that want to talk to one another. It doesn't matter who does it first; the negotiation will just work. async function start
() { try { const stream = await navigator.mediaDevices.getUserMedia(constraints); for (const track of stream.getTracks
()) { pc.addTrack(track, stream); } selfVideo.srcObject = stream; } catch(err) { console.error(err); } } This isn't appreciably different from older WebRTC connection establishment code. The user's camera and microphone are obtained by calling getUs...
...y { const stream = await navigator.mediaDevices.getUserMedia(constraints); for (const track of stream.getTracks
()) { pc.addTrack(track, stream); } selfVideo.srcObject = stream; } catch(err) { console.error(err); } } This isn't appreciably different from older WebRTC connection establishment code. The user's camera and microphone are obtained by calling getUserMedia
(). The resulting media tracks are then added to the RTCPeerConnection by passing them into addTrack
(). Then, finally, the media source for the self-view <video> element indicated by the selfVideo constant is set to the camera and microphone stream, allowing the local user to see what the other peer sees. Handling incoming tracks We next need to set up a handler for track events to handle inbound ...
...And 28 more matches
Inheritance and the prototype chain - JavaScript
ct but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached. Following the ECMAScript standard, the notation someObject.[[Prototype]] is used to designate the prototype of someObject. Since ECMAScript 2015, the [[Prototype]] is accessed using the accessors Object.getPrototypeOf
() and Object.setPrototypeOf
(). This is equivalent to the JavaScript property __proto__ which is non-standard but de-facto implemented by many browsers. It should not be confused with the func.prototype property of functions, which instead specifies the [[Prototype]] to be assigned to all instances of objects created by the given function when used as a constructor. The Object.prototype property re...
...c.prototype property of functions, which instead specifies the [[Prototype]] to be assigned to all instances of objects created by the given function when used as a constructor. The Object.prototype property represents the Object prototype object. Here is what happens when trying to access a property: // Let's create an object o from function f with its own properties a and b: let f = function
() { this.a = 1; this.b = 2; } let o = new f
(); // {a: 1, b: 2} // add properties in f function's prototype f.prototype.b = 3; f.prototype.c = 4; // do not set the prototype f.prototype = {b:3,c:4}; this will break the prototype chain // o.[[Prototype]] has properties b and c. // o.[[Prototype]].[[Prototype]] is Object.prototype. // Finally, o.[[Prototype]].[[Prototype]].[[Prototype]] is nul...
...ny function can be added to an object in the form of a property. An inherited function acts just as any other property, including property shadowing as shown above (in this case, a form of method overriding). When an inherited function is executed, the value of this points to the inheriting object, not to the prototype object where the function is an own property. var o = { a: 2, m: function
() { return this.a + 1; } }; console.log(o.m
()); // 3 // When calling o.m in this case, 'this' refers to o var p = Object.create(o); // p is an object that inherits from o p.a = 4; // creates a property 'a' on p console.log(p.m
()); // 5 // when p.m is called, 'this' refers to p. // So when p inherits the function m of o, // 'this.a' means p.a, the property 'a' of p Using prototypes in J...
...And 28 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
versions) is was in MOZILLA_HOME/default/autoconfig/prefcalls.js. The presence of pref("general.config.filename", "mozilla.cfg"); in any appropriate .js file (here we use autoconf.js dedicated file) enables the read and execution of prefcalls.js. Do not use the name all.js because it is reserved. ...
....smtpserver.smtp1.try_ssl", 0); lockPref("mail.smtpserver.smtp1.username", ""); lockPref("mail.smtpservers", "smtp1"); lockPref("mail.startup.enabledMailCheckOnce", true); lockPref("mailnews.quotingPrefs.version", 1); lockPref("mailnews.ui.threadpane.version", 5); /* 3) define here (because if set after "4)" below it doesn't work!) processLDAPValues which is eventually called by getLDAPAttributes
() just below, check getLDAPAttributes
() code from $MOZILLA_HOME/defaults/autoconfig/prefcalls.js to see the inside call to "user defined" processLDAPValues */ function processLDAPValues(values) { if(values) { // set the global var with the values returned from the LDAP query ldap_values = values; var uid = getLDAPValue(values, "uid"); var cn = getLDAPValue(values, "cn"); var ...
...tenv("MOZILLA_DEBUG"); if (env_mozdebug) {displayError("NO ERROR, just a debug, cn =" + cn + " and mail = " + mail); } } } // 4) Call LDAP servers to get LDAP Attributes (mail & cn), this will finally call processLDAPValues, "3)" just above. getLDAPAttributes("ldap2.int-evry.fr","ou=people,dc=int-evry,dc=fr","uid=" + env_user,"uid,cn,mail,labeledURI"); // Close the try, and call the catch
() } catch(e) { displayError("lockedPref", e); } thunderbird.cfg (Version 2 with AD) Using Thunderbird 9.0.1 and try to use a Active Directory (Windows Server 2008) as LDAP-Source did not work with Version 1. Here's my own version. //Note: for accessing the Active Directory of Windows Server later than 2000 //it is necessary to allow anonymous read access. Please see //(German) http://interop.
...And 27 more matches
Message manager overview
loaded separately into every open tab: three times, in the diagram above. Similarly, if you send a message using the global frame message manager, it's received by all content tabs, and is then delivered to any frame scripts that are listening for it. ...
... diagram above. Similarly, if you send a message using the global frame message manager, it's received by all content tabs, and is then delivered to any frame scripts that are listening for it. ...
...anager, it's received by all content tabs, and is then delivered to any frame scripts that are listening for it. ...
...And 27 more matches
CanvasRenderingContext2D - Web APIs
and other objects. See the interface's properties and methods in the sidebar and below. The Canvas tutorial has more explanation, examples, and resources, as well. ...
...xt, call getContext
() on the <canvas> element, supplying '2d' as the argument: const canvas = document.getElementById('my-house'); const ctx = canvas.getContext('2d'); With the context in hand, you can draw anything you like. This code draws a house: // Set line width ctx.lineWidth = 10; // Wall ctx.strokeRect(75, 140, 150, 110); // Door ctx.fillRect(130, 190, 40, 60); // Roof ctx.beginPath
(); ctx.moveTo(50, 140); ctx.lineTo(150, 60); ctx.lineTo(250, 140); ctx.closePath
(); ctx.stroke
(); The resulting drawing looks like this: Reference Drawing rectangles There are three methods that immediately draw rectangles to the canvas. ...
...dth = 10; // Wall ctx.strokeRect(75, 140, 150, 110); // Door ctx.fillRect(130, 190, 40, 60); // Roof ctx.beginPath
(); ctx.moveTo(50, 140); ctx.lineTo(150, 60); ctx.lineTo(250, 140); ctx.closePath
(); ctx.stroke
(); The resulting drawing looks like this: Reference Drawing rectangles There are three methods that immediately draw rectangles to the canvas. CanvasRenderingContext2D.clearRect
() Sets all pixels in the rectangle defined by starting point (x, y) and size (width, height) to transparent black, erasing any previously drawn content. CanvasRenderingContext2D.fillRect
() Draws a filled rectangle at (x, y) position whose size is determined by width and height. ...
...And 27 more matches
Date - JavaScript
Coordinated Universal Time (UTC), the global standard time defined by the World Time Standard. (This time is historically known as Greenwich Mean Time, as UTC lies along the meridian that includes London--and nearby Greenwich--in the United Kingdom.) The user's device provides the local time. In addition to methods to read and alter individual components of the local date and time (such as getDay
() and setHours
()), there are also versions of the same methods that read and manipulate the date and time using UTC (such as getUTCDay
() and setUTCHours
()). Constructor Date
() Creates a new Date object. Static methods Date.now
() Returns the numeric value corresponding to the current time--the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC, with leap seconds ignored. D...
...ours
()), there are also versions of the same methods that read and manipulate the date and time using UTC (such as getUTCDay
() and setUTCHours
()). Constructor Date
() Creates a new Date object. Static methods Date.now
() Returns the numeric value corresponding to the current time--the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC, with leap seconds ignored. Date.parse
() Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00 UTC, with leap seconds ignored. Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies. Date.UTC
() Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds s...
...:00:00 UTC, with leap seconds ignored. Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies. Date.UTC
() Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored. Instance methods Date.prototype.getDate
() Returns the day of the month (1-31) for the specified date according to local time. Date.prototype.getDay
() Returns the day of the week (0-6) for the specified date according to local time. ...
...And 27 more matches
Introducing asynchronous JavaScript - Learn web development
is section recaps some of the information we saw in the previous article. A lot of the functionality we have looked at in previous learning area modules is synchronous -- you run some code, and the result is returned as soon as the browser can do so. Let's look at a simple example (see it live here, and see the source): const btn = document.querySelector('button'); btn.addEventListener('click',
() => { alert('You clicked me!'); let pElem = document.createElement('p'); pElem.textContent = 'This is a newly-added paragraph.'; document.body.appendChild(pElem); }); In this block, the lines are executed one after the other: We grab a reference to a <button> element that is already available in the DOM. We add a click event listener to it so that when the button is clicked: A...
... alert('You clicked me!'); let pElem = document.createElement('p'); pElem.textContent = 'This is a newly-added paragraph.'; document.body.appendChild(pElem); }); In this block, the lines are executed one after the other: We grab a reference to a <button> element that is already available in the DOM. We add a click event listener to it so that when the button is clicked: An alert
() message appears. Once the alert is dismissed, we create a <p> element. We then give it some text content. Finally, we append the paragraph to the document body. While each operation is being processed, nothing else can happen -- rendering is paused. This is because as we said in the previous article, JavaScript is single threaded. Only one thing can happen at a time, on a single m...
...JavaScript is single threaded. Only one thing can happen at a time, on a single main thread, and everything else is blocked until an operation completes. So in the example above, after you've clicked the button the paragraph won't appear until after the OK button is pressed in the alert box. You can try it for yourself: <button>Click me</button> Note: It is important to remember that alert
(), while being very useful for demonstrating a synchronous blocking operation, is terrible for use in real world applications. Asynchronous JavaScript For reasons illustrated earlier (e.g. related to blocking), many Web API features now use asynchronous code to run, especially those that access or fetch some kind of resource from an external device, such as fetching a file from the network, acce...
...And 26 more matches
A first splash into JavaScript - Learn web development
<label for="guessField">Enter a guess: </label><input type="text" id="guessField" class="guessField"> <input type="submit" value="Submit guess" class="guessSubmit"> </div> <div class="resultParas"> <p class="guesses"></p> <p class="lastResult"></p> <p class="lowOrHi"></p> </div> <script> // Your JavaScript goes here let randomNumber = Math.floor(Math.random
() * 100) + 1; const guesses = document.querySelector('.guesses'); const lastResult = document.querySelector('.lastResult'); const lowOrHi = document.querySelector('.lowOrHi'); const guessSubmit = document.querySelector('.guessSubmit'); const guessField = document.querySelector('.guessField'); let guessCount = 1; let resetButton; function checkGuess
() { let use...
... let userGuess = Number(guessField.value); if (guessCount === 1) { guesses.textContent = 'Previous guesses: '; } guesses.textContent += userGuess + ' '; if (userGuess === randomNumber) { lastResult.textContent = 'Congratulations! ...
...ses.textContent += userGuess + ' '; if (userGuess === randomNumber) { lastResult.textContent = 'Congratulations! ...
...And 26 more matches
Accessing the Windows Registry Using XPCOM
ple example Here's a simple example showing how to read your Windows ProductId: var wrk = Components.classes["@mozilla.org/windows-registry-key;1"] .createInstance(Components.interfaces.nsIWindowsRegKey); wrk.open(wrk.ROOT_KEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion", wrk.ACCESS_READ); var id = wrk.readStringValue("ProductId"); wrk.close
(); This example, while simple, shows several important things about using the interface. First, you must use createInstance
() to get an object implementing this interface, not getService
(). Second, you must call open
() on the key before attempting to read a value. Notice in the open
() call that the root key to use is specified using the named constants available on the nsIWindowsRegKey interface...
...MACHINE in the Windows registry. Also notice that the path to the key has backslashes escaped, a necessity in JavaScript and C++ string constants. The desired access rights are specified using a named constant from the interface, in this example ACCESS_READ. This can be very important when dealing with non-Administrator accounts with restricted privileges. The value is read using readStringValue
(). You have to specify what type of data you expect to read, which we will expand on later. Finally, note that you should close the key when you are done to avoid wasting system resources. Opening Registry Keys Before doing anything with a registry key you must first open the key you are interested in. The example above demonstates this using the open
() method. If you want to create a new key, yo...
...y what type of data you expect to read, which we will expand on later. Finally, note that you should close the key when you are done to avoid wasting system resources. Opening Registry Keys Before doing anything with a registry key you must first open the key you are interested in. The example above demonstates this using the open
() method. If you want to create a new key, you can use the create
() method, which takes the same parameters as open
(). Note that it is not an error to call create
() on an existing key, and doing so has the same result as calling open
(). Both of these methods take a root key as the first parameter. From JavaScript, you will want to use the named constants on the interface for this parameter. They are: ROOT_KEY_CLASSES_ROOT -- Corresponds to HKEY_CLASSES_ROOT ...
...And 26 more matches
Video and Audio APIs - Learn web development
by hiding the native controls (by removing the controls attribute), and programming your own with HTML, CSS, and JavaScript. In the next section we'll look at the basic tools we have available to do this. The HTMLMediaElement API Part of the HTML5 spec, the HTMLMediaElement API provides features to allow you to control video and audio players programmatically -- for example HTMLMediaElement.play
(), HTMLMediaElement.pause
(), etc. This interface is available to both <audio> and <video> elements, as the features you'll want to implement are nearly identical. Let's go through an example, adding features as we go. Our finished example will look (and function) something like the following: Getting started To get started with this example, download our media-player-start.zip and unzip it int...
...ur code: media.removeAttribute('controls'); controls.style.visibility = 'visible'; These two lines remove the default browser controls from the video, and make the custom controls visible. Playing and pausing the video Let's implement probably the most important control -- the play/pause button. ...
...rom the video, and make the custom controls visible. Playing and pausing the video Let's implement probably the most important control -- the play/pause button. First of all, add the following to the bottom of your code, so that the playPauseMedia
() function is invoked when the play button is clicked: play.addEventListener('click', playPauseMedia); Now to define playPauseMedia
() -- add the following, again at the bottom of your code: function playPauseMedia
() { if(media.paused) { play.setAttribute('data-icon','u'); media.play
(); } else { play.setAttribute('data-icon','P'); media.pause
(); } } Here we use an if statement to check whether the video is paused. The HTMLMediaElement.paused property returns true if the media is paused, which is any t...
...And 25 more matches
Working with Svelte stores - Learn web development
d and your component hierarchy gets complex, it might become too difficult for components to relay data between each other. In that case, moving to a global data store might be a good option. If you've already worked with Redux or Vuex, then you'll be familiar with how this kind of store works. Svelte stores offer similar features for state management. A store is simply an object with a subscribe
() method that allows interested parties to be notified whenever the store value changes, and an optional set
() method that allows you to set new values for the store. This minimal API is known as the store contract. Svelte provides functions for creating readable, writable, and derived stores in the svelte/store module. Svelte also provides a very intuitive way to integrate stores into its reacti...
...er the store is modified. Create a new file -- stores.js -- inside your src directory. Give it the following content: import { writable } from 'svelte/store' export const alert = writable('Welcome to the To-Do list app!') Note: Stores can be defined and used outside of Svelte components, so you can organize them in any way you please. In the above code we import the writable
() function from svelte/store and use it to create a new store called alert with an initial value of "Welcome to the To-Do list app!". We then export the store. Creating the actual component Let's now create our Alert component and see how we can read values from the store. Create another new file named src/components/Alert.svelte. Give it the following content: <script> import { ...
... see how we can read values from the store. Create another new file named src/components/Alert.svelte. ...
...And 25 more matches
Using the Browser API
ere. The JavaScript implementation To wire up the functionality required by our simple browser, we've written some basic JavaScript (see the full JavaScript listing.) Wiring up the back and forward buttons Early on in the code we implement two simple event listeners to move the browser back and forward in history when the relevant buttons are pressed: back.addEventListener('touchend',function
() { browser.goBack
(); }); fwd.addEventListener('touchend',function
() { browser.goForward
(); }); The functions can be handled using the Browser API HTMLIFrameElement.goBack
() and HTMLIFrameElement.goForward
() methods. You'll also notice that we're also firing these functions on the touchend event, which is effective as Firefox OS devices are generally touchscreen. Enabling/disabling the back ...
...that we're also firing these functions on the touchend event, which is effective as Firefox OS devices are generally touchscreen. Enabling/disabling the back and forward buttons You will also notice after a bit of surfing that the back and forward buttons are disabled when you cannot move backwards/forwards, and enabled when you can. ...
... the touchend event, which is effective as Firefox OS devices are generally touchscreen. Enabling/disabling the back and forward buttons You will also notice after a bit of surfing that the back and forward buttons are disabled when you cannot move backwards/forwards, and enabled when you can. ...
...And 25 more matches
IAccessibleTable
other-licenses/ia2/AccessibleTable.idlNot scriptable This interface gives access to a two-dimensional table. 1.0 66 Introduced Gecko 1.9 Inherits from: IUnknown Last changed in Gecko 1.9 (Firefox 3) Typically all accessible objects that represent cells or cell-clusters of a table will be at the same time children of the table. In this case IAccessible2.indexInParent
() will return the child index which then can be used when calling rowIndex
() and columnIndex
(). However, in some cases that kind of implementation will not be possible. When the table cells are not direct children of a table, the object representing the cell can define a "table-cell-index" object attribute identifying the 0 based table cell index. This object attribute is obtained by parsing the at...
...d when calling rowIndex
() and columnIndex
(). However, in some cases that kind of implementation will not be possible. When the table cells are not direct children of a table, the object representing the cell can define a "table-cell-index" object attribute identifying the 0 based table cell index. This object attribute is obtained by parsing the attribute string returned by IAccessible2.attributes
(). The "table-cell-index" attribute can be used just like a child index of the typical case. ATs should first test for the presence of the "table-cell-index" attribute and if it is not present then IAccessible2.indexInParent
() can be used as in the typical case where cells are direct children of the table. The range of valid coordinates for this interface are implementation dependent. However, that...
...nd if it is not present then IAccessible2.indexInParent
() can be used as in the typical case where cells are direct children of the table. The range of valid coordinates for this interface are implementation dependent. However, that range includes at least the intervals from the from the first row or column with the index 0 up to the last (but not including) used row or column as returned by nRows
() and nColumns
(). Method overview [propget] HRESULT accessibleAt([in] long row, [in] long column, [out] IUnknown accessible ); [propget] HRESULT caption([out] IUnknown accessible ); [propget] HRESULT childIndex([in] long rowIndex, [in] long columnIndex, [out] long cellIndex ); [propget] HRESULT columnDescription([in] long column, [out] BSTR description ); [propget] HRESULT columnExtentAt...
...And 25 more matches
mozIStorageConnection
executing SQL, and examining database errors. 1.0 68 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) For a general overview on how to use this interface, see Storage. ...
...(Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) For a general overview on how to use this interface, see Storage. ...
...nkey 2.1) For a general overview on how to use this interface, see Storage. ...
...And 25 more matches
nsITreeView
hasNextSibling(in long rowIndex, in long afterIndex); boolean isContainer(in long index); boolean isContainerEmpty(in long index); boolean isContainerOpen(in long index); boolean isEditable(in long row, in nsITreeColumn col); boolean isSelectable(in long row, in nsITreeColumn col); boolean isSeparator(in long index); boolean isSorted
(); void performAction(in wstring action); void performActionOnCell(in wstring action, in long row, in nsITreeColumn col); void performActionOnRow(in wstring action, in long row); void selectionChanged
(); void setCellText(in long row, in nsITreeColumn col, in AString value); void setCellValue(in long row, in nsITreeColumn col, in AString value); ...
... boolean canDrop( in long index, in long orientat...
... boolean canDrop( in long index, in long orientation, in nsIDOMDataTransfer dataTransfer ); Parameters index The index of the row. orientation The position around the given row. Defined in constants. ...
...And 25 more matches
Transformations - Web APIs
he default grid and changed the size of the overall canvas for our needs. With transformations there are more powerful ways to translate the origin to a different position, rotate the grid and even scale it. Saving and restoring state Before we look at the transformation methods, let's look at two other methods which are indispensable once you start generating ever more complex drawings. save
() Saves the entire state of the canvas. restore
() Restores the most recently saved canvas state. Canvas states are stored on a stack. Every time the save
() method is called, the current drawing state is pushed onto the stack. A drawing state consists of The transformations that have been applied (i.e. translate, rotate and scale - see below). The current values of the following attributes:...
...d scale - see below). The current values of the following attributes: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled. The current clipping path, which we'll see in the next section. ...
... attributes: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled. The current clipping path, which we'll see in the next section. You can call the save
() method as many times as you like. ...
...And 25 more matches
Element - Web APIs
app is running in the background. Element.onfullscreenerror An event handler for the fullscreenerror event, which is sent when an error occurs while attempting to change into full-screen mode. Methods Inherits methods from its parents Node, and its own parent, EventTarget, and implements those of ParentNode, ChildNode, NonDocumentTypeChildNode, and Animatable. ...
...creenerror event, which is sent when an error occurs while attempting to change into full-screen mode. Methods Inherits methods from its parents Node, and its own parent, EventTarget, and implements those of ParentNode, ChildNode, NonDocumentTypeChildNode, and Animatable. EventTarget.addEventListener
() Registers an event handler to a specific event type on the element. ...
...nherits methods from its parents Node, and its own parent, EventTarget, and implements those of ParentNode, ChildNode, NonDocumentTypeChildNode, and Animatable. EventTarget.addEventListener
() Registers an event handler to a specific event type on the element. Element.attachShadow
() Attaches a shadow DOM tree to the specified element and returns a reference to its ShadowRoot. Element.animate
() A shortcut method to create and run an animation on an element. Returns the created Animation object instance. Element.closest
() Returns the Element which is the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter. Element.createShadowRoot
() Creates a shadow DOM on on the element, turning it into a shadow host. Return...
...And 25 more matches
A simple RTCDataChannel sample - Web APIs
API makes heavy use of Promises. They make it very easy to chain the steps of the connection process together; if you haven't already read up on this functionality of ECMAScript 2015, you should read up on them. Similarly, this example uses arrow functions to simplify syntax. ...
...ake it very easy to chain the steps of the connection process together; if you haven't already read up on this functionality of ECMAScript 2015, you should read up on them. Similarly, this example uses arrow functions to simplify syntax. Starting up When the script is run, we set up an load event listener, so that once the page is fully loaded, our startup
() function is called. ...
...ener('click', connectPeers, false); disconnectButton.addEventListener('click', disconnectPeers, false); sendButton.addEventListener('click', sendMessage, false); } This is quite straightforward. We grab references to all the page elements we'll need to access, then set event listeners on the three buttons. ...
...And 25 more matches
Numbers and dates - JavaScript
ween 1 and the smallest value greater than 1 that can be represented as a Number (2.220446049250313e-16) Number.MIN_SAFE_INTEGER Minimum safe integer in JavaScript (-253 + 1, or -9007199254740991) Number.MAX_SAFE_INTEGER Maximum safe integer in JavaScript (+253 - 1, or +9007199254740991) Methods of Number Method Description Number.parseFloat
() Parses a string argument and returns a floating point number. Same as the global parseFloat
() function. Number.parseInt
() Parses a string argument and returns an integer of the specified radix or base. Same as the global parseInt
() function. Number.isFinite
() Determines whether the passed value is a finite number. Number.isInteger
() Determines whethe...
... The Number prototype provides methods for retrieving information from Number objects in various formats. ...
...ring argument and returns an integer of the specified radix or base. Same as the global parseInt
() function. Number.isFinite
() Determines whether the passed value is a finite number. Number.isInteger
() Determines whether the passed value is an integer. Number.isNaN
() Determines whether the passed value is NaN. More robust version of the original global isNaN
(). Number.isSafeInteger
() Determines whether the provided value is a number that is a safe integer. The Number prototype provides methods for retrieving information from Number objects in various formats. The following table summarizes the methods of Number.prototype. ...
...And 25 more matches
CSS3 - Archive of obsolete content
s and Backgrounds Level 4 already have an Editor's Draft, though they haven't yet reached the First Published Working Draft status. CSS modules status Completed modules A few CSS modules already became a standard as a W3C Recommendation. These should be no more changes. CSS Color Module Level 3 Recommendation since June 7th, 2011 Adds the opacity property, and the hsl
(), hsla
(), rgba
() and rgb
() functions to create <color> values. It also defines the currentcolor keyword as a valid color. The transparent color is now a real color (thanks to the support for the alpha channel) and is a now an alias for rgba(0,0,0,0.0). It deprecates the system-color keywords that shouldn't be used in a production environment anymore. CSS Namespaces Mo...
...pped at the Candidate Recommendation stage. These modules extend and amend the CSS2.1 specification which build the core of the specification. Together with it, they are the current snapshot of the CSS specification. CSS Backgrounds and Borders Module Level 3 Candidate Recommendation Adds: Support, on backgrounds, for any type of <image>, and not only for uri
() defined ones. Support for multiple background images. The background-repeat space and round values, and for the 2-value syntax of this CSS property. The background-attachment local value. The CSS background-origin, background-size, and background-clip properties. Support for curved border corners, with the CSS border-radius, border-top-left-radius, border-top-right-radius...
...property). CSS Conditional Rules Module Level 3 Candidate Recommendation Adds features for conditional processing of parts of style sheets, conditioned on capabilities of the browser or the document the style sheet is being applied to. It consists mainly in allowing nested at-rules inside @media and the adding of a new CSS at-rule, @supports, and a new DOM method CSS.supports
(). CSS Multi-column Layout Module Working Draft Adds support for easy multi-column layouts using the CSS columns, column-count, column-fill, column-gap, column-rule, column-rule-color, column-rule-style, column-rule-width, column-span, column-width, break-after, break-before, and break-inside. CSS Values and Units Module Level 3 Candidate Recommendatio...
...And 24 more matches
HTML parser threading
HTML Parser Threading The HTML parser parses data received from the network off the main thread. (There's currently one parser thread serving all parser instances.) Data received from document.write
() is parsed on the main thread. Main Objects nsHtml5Parser contains the code for dealing with data from document.write
(). (For historical reasons, it also contains unrelated fragment parsing code that should be refactored into a separate class in due course.) nsHtml5StreamParser contains the code for dealing with data from the network. nsHtml5Parser owns nsHtml5StreamParser. Script-created parsers (i.e. parsers created using document.open
()) don't have an nsHtml5StreamParser instance. nsHtml5Parser has one tokenizer/tree builder pair for parsing data from document.write
(). It also has ano...
...nsHtml5StreamParser has one tokenizer/tree builder pair for parsing data from the network. ...
...nsHtml5StreamParser has one tokenizer/tree builder pair for parsing data from the network. Additionally, each nsHtml5Parser has an associated nsHtml5TreeOpExecutor that turns the output (tree operations; discussed later) of the portable parser core into actions performed on the Gecko DOM. ...
...And 24 more matches
Places utilities for JavaScript
allBookmarksFolderId The id of the "All Bookmarks" folder shown in the Library's left pane. placesFlavors GENERIC_VIEW_DROP_TYPES Methods createFixedURI nsIURI createFixedURI(string aSpec) Takes in a spec and returns a valid uri based on it using the nsIURIFixup service. Parameters aSpec a url string that needs fixup Return type Returns a correct nsIURI. ...
...ype Returns a correct nsIURI. getFormattedString
() string getFormattedString(string key, array string params) Parameters key The string name to get from the string bundle params Strings to substitute into the bundle at designated points See XUL:stringbundle for more information. Return type Returns a string from the default places stringbundle. getString
() string getString(string key) Parameters key The name of the string to get. Return type Returns a string from the default places stringbundle. nodeIs
() There are a ton of nodeIs(something) functions in here to check properties of a bookmark node. The all take in the same argument and return a boolean true or false, so I'm just going to list them all in one lump: boolean nodeIsFolde...
...(e.g. for the file browser service where you get your folders in bookmark menus). boolean nodeIsLivemarkContainer(aNode) Determines whether a result node is a remote container registered by the livemark service. boolean nodeIsLivemarkItem(aNode) Determines whether a result node is a live-bookmark item Parameters aNode The node to check. Return type Returns a boolean. ...
...And 24 more matches
nsIFile
ocalFile was merged with this interface in Gecko 14. Much of the documentation has not been updated to reflect this change. ...
...ollowingLinksNative(in nsIFile newParentDir, in ACString newName); Native code only! void CopyToNative(in nsIFile newParentDir, in ACString newName); Native code only! ...
...ions); void createUnique(in unsigned long type, in unsigned long permissions); boolean equals(in nsIFile inFile); boolean exists
(); ACString getRelativeDescriptor(in nsIFile fromFile); void initWithFile(in nsIFile aFile); void initWithNativePath(in ACString filePath); void initWithPath(in AString filePath); boolean isDirectory
(); boolean isExecutable
(); boolean isFile
(); boolean isHidden
(); boolean isReadable
(); boolean isSpecial
(); boolean isSymlink
(); boolean isWritable
(); void launch
(); PRLibraryStar load
(); void moveTo(in nsIFile newParentDir, in AString newName); void moveToNative(in nsIFile newParentDir, in ACString n...
...And 24 more matches
Advanced animations - Web APIs
ing to add some physics to make our animations more advanced. Drawing a ball We are going to use a ball for our animation studies, so let's first draw that ball onto the canvas. The following code will set us up. <canvas id="canvas" width="600" height="300"></canvas> As usual, we need a drawing context first. ...
...ll set us up. <canvas id="canvas" width="600" height="300"></canvas> As usual, we need a drawing context first. To draw the ball, we will create a ball object which contains properties and a draw
() method to paint it on the canvas. var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var ball = { x: 100, y: 100, radius: 25, color: 'blue', draw: function
() { ctx.beginPath
(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true); ctx.closePath
(); ctx.fillStyle = this.color; ctx.fill
(); } }; ball.draw
(); Nothing special here, the ball is actually a simple circle and gets drawn with the help of the arc
() method. Adding velocity Now that we have a ball, we are ready to add a basic animation like we have learned in the las...
..., 0, Math.PI * 2, true); ctx.closePath
(); ctx.fillStyle = this.color; ctx.fill
(); } }; ball.draw
(); Nothing special here, the ball is actually a simple circle and gets drawn with the help of the arc
() method. Adding velocity Now that we have a ball, we are ready to add a basic animation like we have learned in the last chapter of this tutorial. Again, window.requestAnimationFrame
() helps us to control the animation. The ball gets moving by adding a velocity vector to the position. For each frame, we also clear the canvas to remove old circles from prior frames. ...
...And 24 more matches
Using the Payment Request API - Web APIs
PI, with examples and suggested best practices. The basics of making a payment This section details the basics of using the Payment Request API to make a payment. Note: The code snippets from this section are from our Feature detect support demo. Creating a new payment request object A payment request always starts with the creation of a new PaymentRequest object -- using the PaymentRequest
() constructor. This takes two mandatory parameters and one option parameter: methodData -- an object containing information concerning the payment provider, such as what payment methods are supported, etc. details -- an object containing information concerning the specific payment, such as the total payment amount, tax, shipping cost, etc. options (optional) -- an object containing addtional o...
...t payment methods are supported, etc. details -- an object containing information concerning the specific payment, such as the total payment amount, tax, shipping cost, etc. options (optional) -- an object containing addtional options related to the payment. ...
...ontaining information concerning the specific payment, such as the total payment amount, tax, shipping cost, etc. options (optional) -- an object containing addtional options related to the payment. ...
...And 24 more matches
Using the Web Animations API - Web APIs
s the browser's animation engine to developers and manipulation by JavaScript. This API was designed to underlie implementations of both CSS Animations and CSS Transitions, and leaves the door open to future animation effects. It is one of the most performant ways to animate on the Web, letting the browser make its own internal optimizations without hacks, coercion, or Window.requestAnimationFrame
(). With the Web Animations API, we can move interactive animations from stylesheets to JavaScript, separating presentation from behavior. We no longer need to rely on DOM-heavy techniques such as writing CSS properties and scoping classes onto elements to control playback direction. And unlike pure, declarative CSS, JavaScript also lets us dynamically set values from properties to durations. For b...
...n offset directly in the object, separated from the declaration with a comma. In the above example, to make sure that Alice's color changes at 30% (not 50%) for the color change, we are giving it offset: 0.3. Currently, there should be at least two keyframes specified (representing the starting and ending states of the animation sequence). If your keyframe list has only one entry, Element.animate
() may throw a NotSupportedError exception in some browsers until they are updated. So to recap, the keys are equally spaced by default unless you specify an offset on a key. Handy, no? Representing timing properties We'll also need to create an object of timing properties (an AnimationEffectTimingProperties object) corresponding to the values in Alice's animation: var aliceTiming = { duration...
...d to create an object of timing properties (an AnimationEffectTimingProperties object) corresponding to the values in Alice's animation: var aliceTiming = { duration: 3000, iterations: Infinity } You'll notice a few differences here from how equivalent values are represented in CSS: For one, the duration is in milliseconds as opposed to seconds -- 3000 not 3s. Like WindowTimers.setTimeout
() and Window.requestAnimationFrame
(), the Web Animations API only takes milliseconds. The other thing you'll notice is that it's iterations, not iteration-count. There are a number of small differences between the terminology used in CSS Animations and the terminology used in Web Animations. For instance, Web Animations doesn't use the string "infinite", but instead uses the JavaScript keyword ...
...And 24 more matches
Functions - XPath
EXSLT functions, XPath functions, XPath axes The following is an annotated list of core XPath functions and XSLT-specific additions to XPath, including a description, syntax, a list of arguments, result-type, source in the appropriate W3C Recommendation, and degree of present Gecko support. For further information on using XPath/XSLT functions, please see the For Further Reading page. ...
...tions, XPath functions, XPath axes The following is an annotated list of core XPath functions and XSLT-specific additions to XPath, including a description, syntax, a list of arguments, result-type, source in the appropriate W3C Recommendation, and degree of present Gecko support. For further information on using XPath/XSLT functions, please see the For Further Reading page. ...
...th functions, XPath axes The following is an annotated list of core XPath functions and XSLT-specific additions to XPath, including a description, syntax, a list of arguments, result-type, source in the appropriate W3C Recommendation, and degree of present Gecko support. For further information on using XPath/XSLT functions, please see the For Further Reading page. ...
...And 24 more matches
widget - Archive of obsolete content
or example, this widget contains an image, so it looks like a simple icon: require("sdk/widget").Widget({ id: "mozilla-icon", label: "My Mozilla Widget", contentURL: "http://www.mozilla.org/favicon.ico" }); You can make contentURL point to an HTML or icon file which you have packaged inside your add-on. ...
...or interacting with web content. While content scripts can access the content they're attached to, they can't use the SDK's APIs. So implementing a complete solution usually means you have to send messages between the content script and the main add-on code. You can specify one or more content scripts to load into the widget using the contentScript or contentScriptFile options to the Widget
() constructor. You can communicate with the script using either the postMessage
() API or (preferably, usually) the port API. Unless your content script is extremely simple and consists only of a static string, don't use contentScript: if you do, you may have problems getting your add-on approved on AMO. Instead, keep the script in a separate file and load it using contentScriptFile. Thi...
...n"> </body> </html> We just include three icons, and assign an ID to each one. This HTML file, and the icon files it references, are saved in the add-on's data directory. Next, we write a content script that listens for click events on each icon and sends the corresponding message to the main add-on code: var play_button = document.getElementById("play-button"); play_button.onclick = function
() { self.port.emit("play"); } var pause_button = document.getElementById("pause-button"); pause_button.onclick = function
() { self.port.emit("pause"); } var stop_button = document.getElementById("stop-button"); stop_button.onclick = function
() { self.port.emit("stop"); } We save this file in the add-on's data directory as "button-script.js". Finally. in the add-on's "main.js" file, we crea...
...And 23 more matches
New in JavaScript 1.3 - Archive of obsolete content
rsions up to 1.3. Note that Communicator and Navigator 4.0-4.05 and earlier ignored scripts with the language attribute set to "JavaScript1.3" and higher. <SCRIPT LANGUAGE="JavaScript1.2"> <!-- JavaScript for Navigator 4.0. --> <SCRIPT LANGUAGE="JavaScript1.3"> <!-- JavaScript for Navigator 4.5. ...
... Communicator and Navigator 4.0-4.05 and earlier ignored scripts with the language attribute set to "JavaScript1.3" and higher. <SCRIPT LANGUAGE="JavaScript1.2"> <!-- JavaScript for Navigator 4.0. --> <SCRIPT LANGUAGE="JavaScript1.3"> <!-- JavaScript for Navigator 4.5. ...
...4.0-4.05 and earlier ignored scripts with the language attribute set to "JavaScript1.3" and higher. <SCRIPT LANGUAGE="JavaScript1.2"> <!-- JavaScript for Navigator 4.0. --> <SCRIPT LANGUAGE="JavaScript1.3"> <!-- JavaScript for Navigator 4.5. ...
...And 23 more matches
nsITextInputProcessor
entation of this class can be a cushion from the impact of Gecko's change. You can create an instance of this interface with the following code: var TIP = Components.classes["@mozilla.org/text-input-processor;1"]. createInstance(Components.interfaces.nsITextInputProcessor); Next, you need to get the rights to create composition or dispatch keyboard events with beginInputTransaction
() or beginInputTransactionForTests
(): if (!TIP.beginInputTransaction(window, callback)) { return; } If beginInputTransaction
() or beginInputTransactionForTests
() returns false, it means that another instance of nsITextInputProcessor has composition on the window or is dispatching an event. In this case, other instances cannot create composition nor dispatch keyboard events on the window. The ...
...s false, it means that another instance of nsITextInputProcessor has composition on the window or is dispatching an event. In this case, other instances cannot create composition nor dispatch keyboard events on the window. The second argument, callback, should be an object which implements nsITextInputProcessorCallback or just a function which is the same as nsITextInputProcessorCallback.onNotify
(). See the document of nsITextInputProcessorCallback for the detail. Next, you can set the composition string or dispatch keyboard events. The following example sets "foo-bar-buzz", "bar" is selected clause to convert, and caret position is the end of the selected clause: // First, sets composition string. TIP.setPendingCompositionString("foo-bar-buzz"); // Next, append clauses. TIP.appendClause...
...However, if the event is consumed by web content, it returns false. In this case, composition isn't created. So, JS-IME shouldn't continue to compose the string. Finally, when you commit the composition with the last compos...
...And 23 more matches
Using the CSS Typed Object Model - Web APIs
vaScript representations and back (via HTMLElement.style) can incur a significant performance overhead. The CSS Typed OM makes CSS manipulation more logical and performant by providing object features (rather than CSSOM string manipulation), providing access to types, methods, and an object model for CSS values. This article provides an introduction to all of its main features. computedStyleMap
() With the CSS Typed OM API, we can access all the CSS properties and values -- including custom properties -- that are impacting an element. Let's see how this works by creating our first example, which explores computedStyleMap
(). We start with some HTML: a paragraph with a link, as well as a definition list to which we will add all the CSS Property / Value pairs. <p> <a href="https://exam...
...es computedStyleMap
(). We start with some HTML: a paragraph with a link, as well as a definition list to which we will add all the CSS Property / Value pairs. <p> <a href="https://example.com">Link</a> </p> <dl id="regurgitation"></dl> We add JavaScript to grab our unstyled link and return back a definition list of all the default CSS property values impacting the link using computedStyleMap
(). ...
...urgitation"></dl> We add JavaScript to grab our unstyled link and return back a definition list of all the default CSS property values impacting the link using computedStyleMap
(). ...
...And 23 more matches
Using the Screen Capture API - Web APIs
In this article, we will examine how to use the Screen Capture API and its getDisplayMedia
() method to capture part or all of a screen for streaming, recording, or sharing during a WebRTC conference session. Note: It may be useful to note that recent versions of the WebRTC adapter.js shim include implementations of getDisplayMedia
() to enable screen sharing on browsers that support it but do not implement the current standard API. This works with at least Chrome, Edge, and Firefox. Capturing screen contents Capturing screen contents as a live MediaStream is initiated by calling navigator.mediaDevices.getDisplayMedia
(), which returns a promise that resolves to a stream containing the live screen contents. Starting screen capture: async/await style async function startCapture(displayM...
...e: Promise style function startCapture(displayMediaOptions) { let captureStream = null; return navigator.mediaDevices.getDisplayMedia(displayMediaOptions) .catch(err => { console.error("Error:" + err); return null; }); } Either way, the user agent responds by presenting a user interface that prompts the user to choose the screen area to share. Both of these implementations of startCapture
() return the MediaStream containing the captured display imagery. See Options and constraints, below, for more on both how to specify the type of surface you want as well as other ways to adjust the resulting stream. Example of a window allowing the user to select a display surface to capture You can then use the captured stream, captureStream, for anything that accepts a stream as input. Th...
... the entire content of an obscured window after gaining permission from the user to do so. In this case, the user agent may include the obscured content, either by getting the current contents of the hidden portion of the window or by presenting the most-recently-visible contents if the current contents are not available. Options and constraints The constraints object passed into getDisplayMedia
() is a DisplayMediaStreamConstraints object which is used to configuring the resulting stream. Note: Unlike most uses of constraints in media APIs, here it's solely used to define the stream configuration, and not to filter the available choices. There are three new constraints added to MediaTrackConstraints (as well as to MediaTrackSupportedConstraints and MediaTrackSettings) for configuring a...
...And 23 more matches
Getting Started - Developer guides
ActiveX object called XMLHTTP. Then, Mozilla, Safari, and other browsers followed, implementing an XMLHttpRequest object that supported the methods and properties of Microsoft's original ActiveX object. Meanwhile, Microsoft implemented XMLHttpRequest as well. // Old compatibility code, no longer needed. if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ... httpRequest = new XMLHttpRequest
(); } else if (window.ActiveXObject) { // IE 6 and older httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } Note: For illustration purposes, the above is a somewhat simplified version of the code to be used for creating an XMLHttp instance. For a more realistic example, see step 3 of this article. After making a request, you will receive a response back. At this stage, you need to tell t...
... no parentheses or parameters after the function name, because you're assigning a reference to the function, rather than actually calling it. ...
... a function name, you can use the JavaScript technique of defining functions on the fly (called "anonymous functions") to define the actions that will process the response, like this: httpRequest.onreadystatechange = function
(){ // Process the server response here. }; Next, after declaring what happens when you receive the response, you need to actually make the request, by calling the open
() and send
() methods of the HTTP request object, like this: httpRequest.open('GET', 'http://www.example.org/some.file', true); httpRequest.send
(); The first parameter of the call to open
() is the HTTP request method - GET, POST, HEAD, or another method supported by your server. Keep the method all-capitals as per the HTTP standard, otherwise some browsers (like Firefox) might not process the r...
...And 23 more matches
Object.prototype.constructor - JavaScript
ut: theTree.constructor is function Tree(name) { this.name = name } Changing the constructor of an object The following example shows how to modify the constructor value of generic objects. Only true, 1, and "test" will not be affected (as they have read-only native constructors). This example shows that it is not always safe to rely on the constructor property of an object. ...
...tion Tree(name) { this.name = name } Changing the constructor of an object The following example shows how to modify the constructor value of generic objects. Only true, 1, and "test" will not be affected (as they have read-only native constructors). This example shows that it is not always safe to rely on the constructor property of an object. ...
...s.name = name } Changing the constructor of an object The following example shows how to modify the constructor value of generic objects. Only true, 1, and "test" will not be affected (as they have read-only native constructors). This example shows that it is not always safe to rely on the constructor property of an object. ...
...And 23 more matches
String - JavaScript
The String object is used to represent and manipulate a sequence of characters. Description Strings are useful for holding data that can be represented in text form. ...
...represent and manipulate a sequence of characters. Description Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their length, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the indexOf
() method, or extracting substrings with the substring
() method. Creating strings Strings can be created as primitives, from string literals, or as objects, using the String
() constructor: const string1 = "A string primitive"; const string2 = 'Also a string primitive'; const string3 = `Yet another string primitive`; const string4 = new String("A String object"); String primitives and string objects can be used interchangeably in most situations. ...
... most situations. See "String primitives and String objects" below. String literals can be specified using single or double quotes, which are treated identically, or using the backtick character `. This last form specifies a template literal: with this form you can interpolate expressions. Character access There are two ways to access an individual character in a string. The first is the charAt
() method: return 'cat'.charAt(1) // returns "a" The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index: return 'cat'[1] // returns "a" When using bracket notation for character access, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither w...
...And 23 more matches
HTML text fundamentals - Learn web development
bel { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode
() { output.innerHTML = textarea.value; } reset.addEventListener('click', function
() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode
(); }); solution.addEventListener('click', function
() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; }...
...area.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode
(); }); solution.addEventListener('click', function
() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Show solution'; } updateCode
(); }); var htmlSolution = '<h1>My short story</h1>\n<p>I am a statistician and my name is Trish.</p>\n<p>My legs are made of cardboard and I am married to a fish.</p>'; var solutionEntry = htmlSolution; textarea.addEventListener('input', updateCode); window.addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead text...
...and my name is Trish.</p>\n<p>My legs are made of cardboard and I am married to a fish.</p>'; var solutionEntry = htmlSolution; textarea.addEventListener('input', updateCode); window.addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault
(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur
(); } }; function insertAtCaret(text) { var scrollPos = textarea.scrollTop; var caretPos = textarea.selectionStart; var front = (textarea.value).substring(0, caretPos); var back = (textarea.value).substring(textarea.selectionEnd, textarea.value.length); textarea.value = front + text + back; caretPos = caretP...
...And 22 more matches
nsIDocShell
Obsolete since Gecko 1.8 nsISimpleEnumerator getDocShellEnumerator(in long aItemType, in long aDirection); nsIDOMStorage getSessionStorageForPrincipal(in nsIPrincipal pr...
...Obsolete since Gecko 1.8 nsISimpleEnumerator getDocShellEnumerator(in long aItemType, in long aDirection); nsIDOMStorage getSessionStorageForPrincipal(in nsIPrincipal principal, in DOMString documentURI, in boolean create); nsIDOMS...
...Viewer viewer, in boolean top); void createAboutBlankContentViewer(in nsIPrincipal aPrincipal); void createLoadInfo(out nsIDocShellLoadInfo loadInfo); void DetachEditorFromWindow
(); Violates the XPCOM interface guidelines void finishRestore
(); void firePageHideNotification(in boolean isUnload); Native code only! void fireUnloadNotification
(); Native code only! Obsolete since Gecko 1.8 nsISimpleEnumerator getDocShellEnumerator(in long aItemType, in long aDirection); nsIDOMStorage getSessionStorageForPrincipal(in nsIPrincipal principal, in DOMString documentURI, in boolean create); nsIDOMStorage getSessionStorageForURI(in nsIURI uri, in DOMString documentURI); void historyPurged(in long numEntries)...
...And 22 more matches
DevTools API - Firefox Developer Tools
eters: target {Target} - The target the toolbox is debugging. Return value: Toolbox object or undefined if there's no toolbox for the given target.. closeToolbox(target) Closes the toolbox for given target. Parameters: target {Target} - The target of the toolbox that should be closed. Return value: A Promise that is fulfilled once the toolbox has been destroyed. getDefaultTools
() Returns an Array of ToolDefinition objects for the built-in tools. getAdditionalTools
() Returns an Array of ToolDefinition objects for tools added by addons. getToolDefinition(toolId) Fetch the ToolDefinition object for a tool if it exists and is enabled. Parameters: toolId {String} - The ID of the tool. Return value: A ToolDefinition if a tool with the given ID exists and is...
... getThemeDefinition(themeId) Fetch the ThemeDefinition object for the theme with the given id. ...
...ols added by addons. getToolDefinition(toolId) Fetch the ToolDefinition object for a tool if it exists and is enabled. Parameters: toolId {String} - The ID of the tool. Return value: A ToolDefinition if a tool with the given ID exists and is enabled, null otherwise. getToolDefinitionMap
() Returns a toolId -> ToolDefinition map for tools that are enabled. ...
...And 22 more matches
Using images - Web APIs
ted by the browser, such as PNG, GIF, or JPEG. You can even use the image produced by other canvas elements on the same page as the source! Importing images into a canvas is basically a two step process: Get a reference to an HTMLImageElement object or to another canvas element as a source. It is also possible to use images by providing a URL. Draw the image on the canvas using the drawImage
() function. Let's take a look at how to do this. Getting images to draw The canvas API is able to use any of the following data types as an image source: HTMLImageElement These are images created using the Image
() constructor, as well as any <img> element. SVGImageElement These are images embedded using the <image> element. HTMLVideoElement Using an HTML <video> element as your image so...
... HTMLCanvasElement You can use another <canvas> element as your image source. These sources are collectively referred to by the type CanvasImageSource. There are several ways to get images for use on a canvas. Using images from the same page We can obtain a reference to images on the same page as the canvas by using one of: The document.images collection The document.getElementsByTagName
() method If you know the ID of the specific image you wish to use, you can use document.getElementById
() to retrieve that specific image Using images from other domains Using the crossorigin attribute of an <img> element (reflected by the HTMLImageElement.crossOrigin property), you can request permission to load an image from another domain for use in your call to drawImage
(). If the hosting do...
...Be sure you've drawn something to the source canvas before using it in your target canvas. One of the more practical uses of this would be to use a second canvas element as a thumbnail view of the other larger canvas. ...
...And 22 more matches
Using Service Workers - Web APIs
s HTTPS for security reasons. GitHub is therefore a good place to host experiments, 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...
...vailable for use offline. When the oninstall handler completes, the service worker is considered installed. Next is activation. When the service worker is installed, it then receives an activate event. The primary use of onactivate is for cleanup of resources used in previous versions of a Service worker script. The Service worker will now control pages, but only those opened after the register
() is successful. i.e. a document starts life with or without a Service worker and maintains that for its lifetime. So documents will have to be reloaded to actually be controlled. The below graphic shows a summary of the available service worker events: Promises Promises are a great mechanism for running async operations, with success dependant on one another. This is central to the way ser...
...to actually be controlled. The below graphic shows a summary of the available service worker events: Promises Promises are a great mechanism for running async operations, with success dependant on one another. This is central to the way service workers work. ...
...And 22 more matches
A basic 2D WebGL animation example - Web APIs
to convert the coordinates we're using for our scene into clipspace coordinates (that is, the system by which (0, 0) is at the center of the context and each axis extends from -1.0 to 1.0 regardless of the actual size of the context). ...
...d vertex's position. Fragment shader Next comes the fragment shader. Its role is to return the color of each pixel in the shape being rendered. Since we're drawing a solid, untextured object with no lighting applied, this is exceptionally simple: <script id="fragment-shader" type="x-shader/x-fragment"> #ifdef GL_ES precision highp float; #endif uniform vec4 uGlobalColor; void main
() { gl_FragColor = uGlobalColor; } </script> This starts by specifying the precision of the float type, as required. Then we set the global gl_FragColor to the value of the uniform uGlobalColor, which is set by the JavaScript code to the color being used to draw the square. HTML The HTML consists solely of the <canvas> that we'll obtain a WebGL context on. <canvas id="glcanvas" width="600...
... = [1.0, 1.0]; // Vertex information let vertexArray; let vertexBuffer; let vertexNumComponents; let vertexCount; // Rendering data shared with the // scalers. ...
...And 22 more matches
WebGL constants - Web APIs
bugInfo.UNMASKED_VENDOR_WEBGL); The WebGL tutorial has more information, examples, and resources on how to get started with WebGL. Table of contents Standard WebGL 1 constants Standard WebGL 2 constants WebGL extension constants Standard WebGL 1 constants These constants are defined on the WebGLRenderingContext interface. Clearing buffers Constants passed to WebGLRenderingContext.clear
() to clear buffer masks. Constant name Value Description DEPTH_BUFFER_BIT 0x00000100 Passed to clear to clear the current depth buffer. STENCIL_BUFFER_BIT 0x00000400 Passed to clear to clear the current stencil buffer. COLOR_BUFFER_BIT 0x00004000 Passed to clear to clear the current color buffer. Rendering primitives Constants...
...me Value Description DEPTH_BUFFER_BIT 0x00000100 Passed to clear to clear the current depth buffer. STENCIL_BUFFER_BIT 0x00000400 Passed to clear to clear the current stencil buffer. COLOR_BUFFER_BIT 0x00004000 Passed to clear to clear the current color buffer. Rendering primitives Constants passed to WebGLRenderingContext.drawElements
() or WebGLRenderingContext.drawArrays
() to specify what kind of primitive to render. Constant name Value Description POINTS 0x0000 Passed to drawElements or drawArrays to draw single points. LINES 0x0001 Passed to drawElements or drawArrays to draw lines. Each vertex connects to the one after it. LINE_LOOP 0x0002 Passed to drawElement...
... creates a separate triangle. TRIANGLE_STRIP 0x0005 Passed to drawElements or drawArrays to draw a connected group of triangles. TRIANGLE_FAN 0x0006 Passed to drawElements or drawArrays to draw a connected group of triangles. Each vertex connects to the previous and the first vertex in the fan. Blending modes Constants passed to WebGLRenderingContext.blendFunc
() or WebGLRenderingContext.blendFuncSeparate
() to specify the blending mode (for both, RBG and alpha, or separately). Constant name Value Description ZERO 0 Passed to blendFunc or blendFuncSeparate to turn off a component. ONE 1 Passed to blendFunc or blendFuncSeparate to turn on a component. SRC_COLOR 0x0300 Passed to blendFunc or bl...
...And 22 more matches
Arrow function expressions - JavaScript
ctors. Syntax Basic syntax (param1, param2, ..., paramN) => { statements } (param1, param2, ..., paramN) => expression // equivalent to: => { return expression; } // Parentheses are optional when there's only one parameter name: (singleParam) => { statements } singleParam => { statements } // The parameter list for a function with no parameters should be written with a pair of parentheses. ...
... Two factors influenced the introduction of arrow functions: the need for shorter functions and the behavior of the this keyword. Shorter functions var elements = [ 'Hydrogen', 'Helium', 'Lithium', 'Beryllium' ]; // This statement returns the array: [8, 6, 7, 9] elements.map(function(element) { return...
...[8, 6, 7, 9] No separate this Before arrow functions, every new function defined its own this value based on how the function was called: A new object in the case of a constructor. undefined in strict mode function calls. The base object if the function was called as an "object method". etc. This proved to be less than ideal with an object-oriented style of programming. ...
...And 22 more matches
Promise - JavaScript
ted with a reason (error). When either of these options happens, the associated handlers queued up by a promise's then method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached. As the Promise.prototype.then
() and Promise.prototype.catch
() methods return promises, they can be chained. Not to be confused with: Several other languages have mechanisms for lazy evaluation and deferring a computation, which they also call "promises", e.g. Scheme. Promises in JavaScript represent processes that are already happening, which can be chained with callback functions. If you are looking to lazily evaluate an e...
...an be chained. Not to be confused with: Several other languages have mechanisms for lazy evaluation and deferring a computation, which they also call "promises", e.g. Scheme. Promises in JavaScript represent processes that are already happening, which can be chained with callback functions. If you are looking to lazily evaluate an expression, consider the arrow function with no arguments: f =
() => expression to create the lazily-evaluated expression, and f
() to evaluate. Note: A promise is said to be settled if it is either fulfilled or rejected, but not pending. You will also hear the term resolved used with promises -- this means that the promise is settled or "locked in" to match the state of another promise. States and fates contains more details about promise terminology. Chai...
...aluated expression, and f
() to evaluate. Note: A promise is said to be settled if it is either fulfilled or rejected, but not pending. You will also hear the term resolved used with promises -- this means that the promise is settled or "locked in" to match the state of another promise. States and fates contains more details about promise terminology. Chained Promises The methods promise.then
(), promise.catch
(), and promise.finally
() are used to associate further action with a promise that becomes settled. These methods also return a newly generated promise object, which can optionally be used for chaining; for example, like this: const myPromise = (new Promise(myExecutorFunc)) .then(handleFulfilledA,handleRejectedA) .then(handleFulfilledB,handleRejectedB) .then(handleFulfi...
...And 22 more matches
Iteration protocols - JavaScript
enerator function, so that when invoked, an iterator object is returned. Inside of this generator function, each entry can be provided by using yield. The iterator protocol The iterator protocol defines a standard way to produce a sequence of values (either finite or infinite), and potentially a return value when all values have been generated. An object is an iterator when it implements a next
() method with the following semantics: Property Value next
() A zero-argument function that returns an object with at least the following two properties: done (boolean) Has the value false if the iterator was able to produce the next value in the sequence. (This is equivalent to not specifying the done property altogether.) Has the value true i...
...lse if the iterator was able to produce the next value in the sequence. (This is equivalent to not specifying the done property altogether.) Has the value true if the iterator has completed its sequence. In this case, value optionally specifies the return value of the iterator. value Any JavaScript value returned by the iterator. Can be omitted when done is true. The next
() method must always return an object with appropriate properties including done and value. If a non-object value gets returned (such as false or undefined), a TypeError ("iterator.next
() returned a non-object value") will be thrown. Note: It is not possible to know reflectively whether a particular object implements the iterator protocol. However, it is easy to create an object that sa...
...r, it is easy to create an object that satisfies both the iterator and iterable protocols (as shown in the example below). Doing so allows an iterator to be consumed by the various syntaxes expecting iterables. Thus, it is seldom useful to implement the Iterator Protocol without also implementing Iterable. ...
...And 22 more matches
Interacting with page scripts - Archive of obsolete content
se objects to page scripts Until Firefox 30, you could use unsafeWindow to perform the reverse procedure, and make objects defined in content scripts available to page scripts: // content-script.js unsafeWindow.contentScriptObject = {"greeting" : "hello from add-on"}; // page-script.js var button = document.getElementById("show-content-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...
...ches a content script to it: // main.js var tabs = require("sdk/tabs"); var self = require("sdk/self"); tabs.open({ url: self.data.url("page.html"), onReady: attachScript }); function attachScript(tab) { tab.attach({ contentScriptFile: self.data.url("content-script.js") }); } The content script defines an object and assigns it to unsafeWindow twice: the first time using cloneInto
(), the second time using simple assignment: // content-script.js var contentScriptObject = {"greeting" : "hello from add-on"}; unsafeWindow.clonedContentScriptObject = cloneInto(contentScriptObject, unsafeWindow); unsafeWindow.assignedContentScriptObject = contentScriptObject; The "page.html" file adds two buttons and assigns an event listener to each: one listener displays a property of the cl...
...Clicking "I will not work" f...
...And 21 more matches
ui/frame - Archive of obsolete content
ML file's location. Messages logged from a frame script using the console will not appear in the terminal when you run the add-on using jpm run. However, they will appear in the Browser Console. This issue is being tracked as bug 982385. Communicating with frames You can exchange messages between the main add-on code and scripts loaded into the frame using an API modeled on window.postMessage
(). A frame creates a separate iframe instance for each browser window. So there are three cases to consider: sending messages from a frame script to the main add-on code sending messages from the main add-on code to all instances of a frame, across all browser windows sending messages from the main add-on code to a single instance of a frame, attached to a specific browser window In all case...
...tes a separate iframe instance for each browser window. So there are three cases to consider: sending messages from a frame script to the main add-on code sending messages from the main add-on code to all instances of a frame, across all browser windows sending messages from the main add-on code to a single instance of a frame, attached to a specific browser window In all cases, postMessage
() takes two arguments: the message itself and a targetOrigin. The targetOrigin argument can be either the URI of the document hosted by the target, or the wildcard "*". If you use the URI, then the message will only be dispatched to the window whose document matches that URI. If you know the target URI, you should use it, as this is more secure: it prevents another window from intercepting message...
...t, or the wildcard "*". If you use the URI, then the message will only be dispatched to the window whose document matches that URI. If you know the target URI, you should use it, as this is more secure: it prevents another window from intercepting messages that were intended for someone else. From frame to add-on To send a message from a frame script to the add-on, use window.parent.postMessage
(). This takes two arguments, the message itself and a target origin. If the frame script initiates the conversation, you need to specify "*" as the origin: window.parent.postMessage("ping", "*"); If the frame script has received a message from the add-on already, it can use the origin property of the event object passed to the message hander: // listen for messages from the add-on, and send a r...
...And 21 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
ute to accept. Within the window are a label element and textbox element, wrapped in a hbox element so that they are arranged horizontally. ...
...At this point, it's important that you disabled the XUL cac...
...At this point, it's important that you disabled the XUL cache as discussed in the...
...And 21 more matches
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
s nsIxxx. In order to have access to the corresponding functions, it is necessary to use the component with the interface you want to use. Some XPCOM components are services, that means only one instance in memory. For instance, this is the case for the bookmarks component, which is actually a service. It lets you access and manipulate the user's bookmarks. Those should be accessed with getService
(). For other components, you can create as many instances as you need. For instance, this is the case for files (nsILocalFile). Those are created with createInstance
(). It's important to know whether a component should be created with getService
() or createInstance
(), because using one instead of the other can cause problems. Listing 1: Calling XPCOM functions using XPConnect <?xml version="1.0" ...
...on to that window. To overcome this limitation, nsIWindowMediator makes it possible to access all of Firefox's windows. Get active window One thing that nsIWindowMediator is often used for is to get the active window. Listing 4 shows how to get the active browser window and the number of open tabs. Passing the name of the window type as the parameter of the nsIWindowMediator.getMostRecentWindow
() method returns the most recently active window from among the root element's windows with that type set for the windowtype attribute value. Setting the parameter to null returns the active window from among all windows, including dialogs, etc. Listing 4: Get active browser window netscape.security.PrivilegeManager .enablePrivilege('UniversalXPConnect'); var WindowMediator = Components .c...
...vilegeManager .enablePrivilege('UniversalXPConnect'); var WindowMediator = Components .classes['@mozilla.org/appshell/window-mediator;1'] .getService(Components.interfaces.nsIWindowMediator); var browser = WindowMediator.getMostRecentWindow('navigator:browser'); alert(browser.gBrowser.mTabs.length); Get overview of all windows with a certain type Use the nsIWindowMediator.getEnumerator
() method to get an overview of all windows that have a certain type. Listing 5 shows how to get a summary of all browser windows in Firefox and then close them. Listing 5: Closing all browser windows var browsers = WindowMediator.getEnumerator('navigator:browser'); var browser; while (browsers.hasMoreElements
()) { browser = browsers.getNext
().QueryInterface(Components.interfaces.nsIDOMWindowInt...
...And 21 more matches
Promises - Archive of obsolete content
h a coding style similar to synchronous variants. The following examples make use of the Task API, which harnesses generator functions to remove some of the syntactic clutter of raw Promises, such that asynchronous promise code more closely resembles synchronous, procedural code. ...
...s a synchronous API. This interface replaces the previous, complicated XPCOM nsIFile and streams APIs, and their related JavaScript helper modules. These older interfaces should be avoided, even in their asynchronous forms, due to their performance penalties and needless complexity. Representative Example Usage Components.utils.import("resource://gre/modules/osfile.jsm"); Task.spawn(function*
() { // Retrieve file metadata to check modification time. let info = yield OS.File.stat(configPath); if (info.lastModificationDate <= timestamp) return; timestamp = info.lastModificationDate; // Read the file as a UTF-8 string, parse as JSON. let config = JSON.parse( yield OS.File.read(configPath, { encoding: "utf-8" })); let files = []; // Get th...
... { encoding: "utf-8" })); let files = []; // Get the directory contents from a list of directories. for (let dir of config.directories) { // Iterate over the contents of the directory. ...
...And 21 more matches
2D maze game with device orientation - Game development
<title>Cyber Orb demo</title> <style> body { margin: 0; background: #333; } </style> <script src="src/phaser-arcade-physics.2.2.2.min.js"></script> <script src="src/Boot.js"></script> <script src="src/Preloader.js"></script> <script src="src/MainMenu.js"></script> <script src="src/Howto.js"></script> <script src="src/Game.js"></script> </head> <body> <script> (function
() { var game = new Phaser.Game(320, 480, Phaser.CANVAS, 'game'); game.state.add('Boot', Ball.Boot); game.state.add('Preloader', Ball.Preloader); game.state.add('MainMenu', Ball.MainMenu); game.state.add('Howto', Ball.Howto); game.state.add('Game', Ball.Game); game.state.start('Boot'); })
(); </script> </body> </html> So far we have a simple HTML website with some basic c...
... like graphics and audio, MainMenu is the menu with the start button, Howto shows the "how to play" instructions and the Game state lets you actually play the game. Let's quickly go though the content of those states. Boot.js The Boot state is the first one in the game. ...
... game. Let's quickly go though the content of those states. Boot.js The Boot state is the first one in the game. ...
...And 21 more matches
Introduction to events - Learn web development
handlers used in many of the examples, but let's recap just to cement our knowledge. In the following example, we have a single <button>, which when pressed, makes the background change to a random color: <button>Change color</button> button { margin: 10px }; The JavaScript looks like so: const btn = document.querySelector('button'); function random(number) { return Math.floor(Math.random
() * (number+1)); } btn.onclick = function
() { const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundColor = rndCol; } In this code, we store a reference to the button inside a constant called btn, using the Document.querySelector
() function. We also define a function that returns a random number. The third part of the code is the even...
...vaScript as it is used in other environments. For example, Node.js is a very popular JavaScript runtime that enables developers to use JavaScript to build network and server-side applications. The Node.js event model relies on listeners to listen for events and emitters to emit events periodically -- it doesn't sound that different, but the code is quite different, making use of functions like on
() to register an event listener, and once
() to register an event listener that unregisters after it has run once. The HTTP connect event docs provide a good example. You don't need to understand anything about other such environments at this stage in your learning; we just wanted to make it clear that events can differ in different programming environments. Ways of using web events There are a n...
...tener code to web pages so it runs when the associated event fires. In this section, we review the various mechanisms and discuss which ones you should use. Event handler properties These are the properties that exist to contain event handler code we have seen most frequently during the course. Returning to the above example: const btn = document.querySelector('button'); btn.onclick = function
() { const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundColor = rndCol; } The onclick property is the event handler property being used in this situation. It is essentially a property like any other available on the button (e.g. btn.textContent, or btn.style), but it is a special type -- when you set it to be equal to some code, that...
...And 21 more matches
Arrays - Learn web development
rticle), but briefly, this code is saying: Start looping at item number 0 in the array. Stop looping at the item number equal to the length of the array. This works for an array of any length, but in this case it stops looping at item number 7 (this is good, as the last item -- which we want the loop to include -- is item 6). For each item, print it out to the browser console with console.log
(). Some useful array methods In this section we'll look at some rather useful array-related methods that allow us to split strings into array items and vice versa, and add new items into arrays. Converting between strings and arrays Often you'll be presented with some raw data contained in a big long string, and you might want to separate the useful items out into a more useful form and then d...
...-related methods that allow us to split strings into array items and vice versa, and add new items into arrays. Converting between strings and arrays Often you'll be presented with some raw data contained in a big long string, and you might want to separate the useful items out into a more useful form and then do things to them, like display them in a data table. To do this, we can use the split
() method. In its simplest form, this takes a single parameter, the character you want to separate the string at, and returns the substrings between the separator as items in an array. Note: Okay, this is technically a string method, not an array method, but we've put it in with arrays as it goes well here. Let's play with this, to see how it works. First, create a string in your console: le...
...(Try running Step 4 with a different character than a...
...And 21 more matches
Accessibility in React - Learn web development
's useRef hook creates an object with a single property: current. This property can be a reference to anything we want and look that reference up later. It's particularly useful for referring to DOM elements. Change the import statement at the top of Todo.js so that it includes useRef: import React, { useRef, useState } from "react"; Then, create two new constants beneath the hooks in your Todo
() function. Each should be a ref - one for the "Edit" button in the view template and one for the edit field in the editing template. const editFieldRef = useRef(null); const editButtonRef = useRef(null); These refs have a default value of null because they will not have value until we attach them to their respective elements. To do that, we'll add an attribute of ref to each element, and set the...
...o each element, and set their values to the appropriately named ref objects. ...
...leChange} ref={editFieldRef} /> The "Edit" button in your view template should read like this: <button type="button" className="btn" onClick={
() => setEditing(true)} ref={editButtonRef} > Edit <span className="visually-hidden">{props.name}</span> </button> Focusing on our refs with useEffect To use our refs for their intended purpose, we need to import another React hook: useEffect
(). useEffect
() is so named because it runs after React renders a given component, and will run any side-effects that we'd like to add to the render process, which we can't run inside the main function body. useEffect
() is useful in the current situation because we cannot focus on an element until after the <Todo /> component renders and React knows where our refs are. Change the import statement o...
...And 21 more matches
React interactivity: Editing, filtering, conditional rendering - Learn web development
e HTML, CSS, and JavaScript languages, knowledge of the terminal/command line. Objective: To learn about conditional rendering in React, and implementing list filtering and an editing UI in our app. Editing the name of a task We don't have a user interface for editing the name of a task yet. We'll get to that in a moment. ...
...he terminal/command line. Objective: To learn about conditional rendering in React, and implementing list filtering and an editing UI in our app. Editing the name of a task We don't have a user interface for editing the name of a task yet. We'll get to that in a moment. To start with, we can at least implement an editTask
() function in App.js. ...
... Editing the name of a task We don't have a user interface for editing the name of a task yet. We'll get to that in a moment. To start with, we can at least implement an editTask
() function in App.js. It'll be similar to deleteTask
() because it'll take an id to find its target object, but it'll also take a newName property containing the name to update the task to. We'll use Array.prototype.map
() instead of Array.prototype.filter
() because we want to return a new array with some changes, instead of deleting something from the array. ...
...And 21 more matches
TypeScript support in Svelte - Learn web development
e the content of the FilterButton.svelte file with the following: <!-- components/FilterButton.svelte --> <script lang='ts'> import { Filter } from '../types/filter.enum' export let filter: Filter = Filter.ALL </script> <div class="filters btn-group stack-exception"> <button class="btn toggle-btn" class:btn__primary={filter === Filter.ALL} aria-pressed={filter === Filter.ALL} on:click={
()=> filter = Filter.ALL} > <span class="visually-hidden">Show</span> <span>All</span> <span class="visually-hidden">tasks</span> </button> <button class="btn toggle-btn" class:btn__primary={filter === Filter.ACTIVE} aria-pressed={filter === Filter.ACTIVE} on:click={
()=> filter = Filter.ACTIVE} > <span class="visually-hidden">Show</span> <span>Active</span> <span class="v...
...gle-btn" class:btn__primary={filter === Filter.ACTIVE} aria-pressed={filter === Filter.ACTIVE} on:click={
()=> filter = Filter.ACTIVE} > <span class="visually-hidden">Show</span> <span>Active</span> <span class="visually-hidden">tasks</span> </button> <button class="btn toggle-btn" class:btn__primary={filter === Filter.COMPLETED} aria-pressed={filter === Filter.COMPLETED} on:click={
()=> filter = Filter.COMPLETED} > <span class="visually-hidden">Show</span> <span>Completed</span> <span class="visually-hidden">tasks</span> </button> </div> Here we are just importing the Filter enum, and using it instead of the string values we used previously. Todos.svelte We will also use the Filter enum in the Todos.svelte component. First add the lang='ts' attribute ...
...atus // reference to TodosStatus instance $: newTodoId = todos.length > 0 ? ...
...And 21 more matches
nsISelectionController
content/base/public/nsISelectionController.idlScriptable Please add a summary to this article. ...
... content/base/public/nsISelectionController.idlScriptable Please add a summary to this article. ...
...void characterExtendForDelete
(); Native code only! ...
...And 21 more matches
SubtleCrypto - Web APIs
ors in security system design and implementation can make the security of the system completely ineffective. If you're not sure you know what you are doing, you probably shouldn't be using this API. Properties This interface doesn't inherit any properties, as it has no parent interface. Methods This interface doesn't inherit any methods, as it has no parent interface. ...
...ing, you probably shouldn't be using this API. Properties This interface doesn't inherit any properties, as it has no parent interface. Methods This interface doesn't inherit any methods, as it has no parent interface. SubtleCrypto.encrypt
() Returns a Promise that fufills with the encrypted data corresponding to the clear text, algorithm, and key given as parameters. SubtleCrypto.decrypt
() Returns a Promise that fulfills with the clear data corresponding to the encrypted text, algorithm, and key given as parameters. ...
...is interface doesn't inherit any methods, as it has no parent interface. SubtleCrypto.encrypt
() Returns a Promise that fufills with the encrypted data corresponding to the clear text, algorithm, and key given as parameters. SubtleCrypto.decrypt
() Returns a Promise that fulfills with the clear data corresponding to the encrypted text, algorithm, and key given as parameters. SubtleCrypto.sign
() Returns a Promise that fulfills with the signature corresponding to the text, algorithm, and key given as parameters. ...
...And 21 more matches
WebGL2RenderingContext - Web APIs
The WebGL2RenderingContext interface implements all members of the WebGLRenderingContext interface. Some methods of the WebGL 1 context can accept additional values when used in a WebGL 2 context. ...
... WebGLRenderingContext interface. Some methods of the WebGL 1 context can accept additional values when used in a WebGL 2 context. You will find this info noted on the WebGL 1 reference pages. The WebGL tutorial has more information, examples, and resources on how to get started with WebGL. Constants See the WebGL constants page. ...
... when used in a WebGL 2 context. You will find this info noted on the WebGL 1 reference pages. The WebGL tutorial has more information, examples, and resources on how to get started with WebGL. Constants See the WebGL constants page. State information WebGL2RenderingContext.getIndexedParameter
() Returns the indexed value for the given target. Buffers WebGL2RenderingContext.bufferData
() Initializes and creates the buffer object's data store. WebGL2RenderingContext.bufferSubData
() Updates a subset of a buffer object's data store. WebGL2RenderingContext.copyBufferSubData
() Copies part of the data of a buffer to another buffer. WebGL2RenderingContext.getBufferSubData
() Reads data from a buffer and writes them to an ArrayBuffer or SharedArrayBuffer. Framebuffers WebGL2Re...
...And 21 more matches
platform/xpcom - Archive of obsolete content
ll topic notifications: var { Class } = require('sdk/core/heritage'); var { Unknown } = require('sdk/platform/xpcom'); var { Cc, Ci } = require('chrome') var observerService = Cc['@mozilla.org/observer-service;1']. ...
...equire('sdk/platform/xpcom'); var { Cc, Ci } = require('chrome') var observerService = Cc['@mozilla.org/observer-service;1']. getService(Ci.nsIObserverService); var StarObserver = Class({ extends: Unknown, interfaces: [ 'nsIObserver' ], topic: '*', register: function register
() { observerService.addObserver(this, this.topic, false); }, unregister: function
() { observerService.removeObserver(this, this.topic); }, observe: function observe(subject, topic, data) { console.log('star observer:', subject, topic, data); } }); var starobserver = StarObserver
(); starobserver.register
(); Implementing XPCOM Factories The xpcom module exports a class called Factory which implements the nsIFactory interface. You can use this class to register fac...
...y, so we use the technique documented under the "Using wrappedJSObject" section of How to Build an XPCOM Component in JavaScript. ...
...And 20 more matches
Third-party APIs - Learn web development
t once, in which case you can then just search the repo for the example files you need in each section. They are found on third-party servers Browser APIs are built into the browser -- you can access them from JavaScript immediately. For example, the Web Audio API we saw in the Introductory article is accessed using the native AudioContext object. For example: const audioCtx = new AudioContext
(); ... const audioElement = document.querySelector('audio'); ... const audioSource = audioCtx.createMediaElementSource(audioElement); // etc. Third party APIs, on the other hand, are located on third party servers. To access them from JavaScript you first need to connect to the API functionality and make it available on your page. This typically involves first linking to a JavaScript library a...
...s" rel="stylesheet" href="https://api.mqcdn.com/sdk/mapquest-js/v1.3.2/mapquest.css"/> You can then start using the objects available in that library. For example: let map = L.mapquest.map('map', { center: [53.480759, -2.242631], layers: L.mapquest.tileLayer('map'), zoom: 12 }); Here we are creating a variable to store the map information in, then creating a new map using the mapquest.map
() method, which takes as its parameters the ID of a <div> element you want to display the map in ('map'), and an options object containing the details of the particular map we want to display. In this case we specify the coordinates of the center of the map, a map layer of type map to show (created using the mapquest.tileLayer
() method), and the default zoom level. This is all the information the ...
...s: L.mapquest.tileLayer('map') Try changing 'map' to 'hybrid' to show a hybrid-style map. Try some other values too. The tileLayer reference page shows the different available options, plus a lot more information. Adding different controls The map has a number of different controls available; by default it just shows a zoom control. You can expand the controls available using the map.addControl
() method; add this to your code, inside the window.onload handler: map.addControl(L.mapquest.control
()); The mapquest.control
() method just creates a simple full-featured control set, and it is placed in the top-right hand corner by default. You can adjust the position by specifying an options object as a parameter for the control containing a position property, the value of which is a string spe...
...And 20 more matches
Examples
ise = OS.File.exists(path); let newPromise = promise.then(function onFulfill(aExists) { if (aExists) { console.log("You have file.txt in your temporary directory."); } else { throw new Error("You don't have file.txt in your temporary directory."); } }); // Unexpected errors should always be reported at the end of a promise chain. let lastPromise = newPromise.then(function onFulfill
(){ }) .catch(function onReject(aRejectReason) { console.warn('newPromise failed with reason: ', aRejectReason); }); Using a promise returned by a function (verbose) This example uses a verbose syntax, showing all the involved promises. Components.utils.import("resource://gre/modules/osfile.jsm") let path = OS.Path.join(OS.Constants.Path.tmpDir, "file.txt"); let promise = OS.File.exists(p...
....txt in your temporary directory." : "You don't have file.txt in your temporary directory."); }).then(null, Components.utils.reportError); Chaining promises The promise returned by then eventually assumes the state of the promise returned by the callback. ...
... what if we want to run multiple promises and then return when all are done? This is accomplished by using Promise.all, this feature requires Promise.jsm. ...
...And 20 more matches
mozIStorageStatement
atements on a mozIStorageConnection. Inherits from: mozIStorageValueArray Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) For an introduction on how to use this interface, see the Storage overview document. ...
...Inherits from: mozIStorageValueArray Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) For an introduction on how to use this interface, see the Storage overview document. ...
...UTF8String aSQLStatement); Obsolete since Gecko 1.9.1 void finalize
(); mozIStorageStatement clone
(); AUTF8String getParameterName(in unsigned long aParamIndex); unsigned long getParameterIndex(in AUTF8String aName); AUTF8String getColumnName(in unsigned long aColumnIndex); unsigned long getColumnIndex(in AUTF8String aName); void reset
(); AString escapeStringForLIKE(in AString aValue, in wchar aEscapeChar); void bindParameters(in mozIStorageBindingParamsArray aParameters); mozIStorageBindingParamsArray newBindingParamsArray
(); void bindUTF8StringParameter(in unsigned long aParamIndex, in AUTF8String aValue); void bindStringParameter(in unsigned long aParamIndex, in AString aValue); ...
...And 20 more matches
nsISessionStore
void deleteTabValue(in nsIDOMNode aTab, in AString aKey); void deleteWindowValue(in nsIDOMWindow aWindow, in AString aKey); nsIDOMNode duplicateTab(in nsIDOMWindow aWindow, in nsIDOMNode aTab); nsIDOMNode forgetClosedTab(in nsIDOMWindow aWindow, in unsigned long aIndex); nsIDOMNode forgetClosedWindow(in unsigned long aIndex); AString getBrowserState
(); unsigned long getClosedTabCount(in nsIDOMWindow aWindow); AString getClosedTabData(in nsIDOMWindow aWindow); unsigned long getClosedWindowCount
(); AString getClosedWindowData
(); AString getTabState(in nsIDOMNode aTab); AString getTabValue(in nsIDOMNode aTab, in AString aKey); AString getWindowState(in nsIDOMWindow aWindow); ...
...osedWindowData
(); AString getTabState(in nsIDOMNode aTab); AString getTabValue(in nsIDOMNode aTab, in AString aKey); AString getWindowState(in nsIDOMWindow aWindow); AString getWindowValue(in nsIDOMWindow aWindow, in AString aKey); void init(in nsIDOMWindow aWindow); void persistTabAttribute(in AString aName); void restoreLastSession
(); void setBrowserState(in AString aState); void setTabState(in nsIDOMNode aTab, in AString aState); void setTabValue(in nsIDOMNode aTab, in AString aKey, in AString aStringValue); void setWindowState(in nsIDOMWindow aWindow, in AString aState, in boolean aOverwrite); void setWindowValue(in nsIDOMWindow aWindow, in AString aKey, in AString aStringValue...
...StringValue); nsIDOMNode undoCloseTab(in nsIDOMWindow aWindow, in unsigned long aIndex); nsIDOMWindow undoCloseWindow(in unsigned long aIndex); Attributes Attribute Type Description canRestoreLastSession boolean Is it possible to restore the previous session. Will always be false when in Private Browsing mode. Methods deleteTabValue
() Deletes a value from a specified tab. void deleteTabValue( in nsIDOMNode aTab, in AString aKey ); Parameters aTab The tab for which to delete the value. aKey The key whose value is to be deleted. Exceptions thrown This method throws a NS_ERROR_ILLEGAL_VALUE exception if the key doesn't exist. deleteWindowValue
() Deletes a value from a specified window. void deleteWindowValue( ...
...And 20 more matches
nsIWindowsRegKey
indowsRegKey.idlScriptable This interface is designed to provide scriptable access to the Windows registry system. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) The interface represents a single key in the registry. This interface is highly Win32 specific. ...
...hod overview void close
(); void create(in unsigned long rootKey, in AString relPath, in unsigned long mode); nsIWindowsRegKey createChild(in AString relPath, in unsigned long mode); AString getChildName(in unsigned long index); AString getValueName(in unsigned long index); unsigned long getValueType(in AString name); boolean hasChanged
(); boolean hasChild(in AString name); boolean hasValue(in AString name); boolean isWatching
(); void open(in unsigned long rootKey, in AString relPath, in unsigned long mode); nsIWindowsRegKey openChild(in AString relPath, in unsigned long mode); ACString readBinaryValue(in AString name); unsigned long long readInt64Value(in AString name...
...ned long mode); ACString readBinaryValue(in AString name); unsigned long long readInt64Value(in AString name); unsigned long readIntValue(in AString name); AString readStringValue(in AString name); void removeChild(in AString relPath); void removeValue(in AString name); void startWatching(in boolean recurse); void stopWatching
(); void writeBinaryValue(in AString name, in ACString data); void writeInt64Value(in AString name, in unsigned long long data); void writeIntValue(in AString name, in unsigned long data); void writeStringValue(in AString name, in AString data); Attributes Attribute Type Description childCount unsigned long This attribute return...
...And 20 more matches
WebGL best practices - Web APIs
nly releases the handle that refers to the actual object. (conceptually releasing the handle's ref-pointer to the object) Only once the object is unused in the implementation is it actually freed. For example, if you never want to access your shader objects directly again, just delete their handles after attaching them to a program object. Eagerly lose contexts too WEBGL_lose_context.loseContext
() can be used to release a WebGL context and its resources eagerly. Use this if you are finished with any contexts, such as probe contexts, or if you hit a fallback case. Flush when expecting results (like queries or rendering frame completion) Flush tells the implementation to push all pending commands out for execution, flushing them out of the queue, instead of waiting for more commands to enq...
...hem out of the queue, instead of waiting for more commands to enqueue before sending for execution. For example, it is possible for the following to never complete without context loss: sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); glClientWaitSync(sync, 0, GL_TIMEOUT_IGNORED); WebGL doesn't have a SwapBuffers call by default, so a flush can help fill the gap, as well. Use webgl.flush
() when not using requestAnimationFrame When not using RAF, (such as when using RPAF; see below) use webgl.flush
() to encourage eager execution of enqueued commands. Because RAF is directly followed by the frame boundary, an explicit webgl.flush
() isn't really needed with RAF. Avoid blocking API calls in production (e.g. getError, getParameter) Certain WebGL entry points cause synchronous stalls...
...lowed by the frame boundary, an explicit webgl.flush
() isn't really needed with RAF. Avoid blocking API calls in production (e.g. getError, getParameter) Certain WebGL entry points cause synchronous stalls on the calling thread. Even basic requests can take as long as 1ms, but they can take even longer if they need to wait for all graphics work to be completed (with an effect similar to glFinish
() in native OpenGL). In production code, avoid such entry points, especially on the browser main thread where they can cause the entire page to jank (often including scrolling or even the whole browser). getError
(): causes a flush + round-trip to fetch errors from the GPU process). For example, within Firefox, the only time glGetError is checked is after allocations (bufferData, *texImage...
...And 20 more matches
Proxy Auto-Configuration (PAC) file - HTTP
a HTML file or any other file. The examples at the end of this document are complete. There is no additional syntax needed to save it into a file and use it. ...
...ny other file. The examples at the end of this document are complete. There is no additional syntax needed to save it into a file and use it. ...
...les at the end of this document are complete. There is no additional syntax needed to save it into a file and use it. ...
...And 20 more matches
ui/button/toggle - Archive of obsolete content
ole.log("You changed '" + state.label + "'"); button.removeListener("change", firstChange); button.on("change", subsequentChanges); } function subsequentChanges(state) { console.log("You changed '" + state.label + "' again"); } The listener is passed a state object that contains all the button's properties. ...
... function subsequentChanges(state) { console.log("You changed '" + state.label + "' again"); } The listener is passed a state object that contains all the button's properties. You can generate click and change events programmatically with the button's click
() method. ...
...A disabled button will not generate click or change events and its icon will appear disabled: Updating state You can update all the button's properties, except for its id. Depending on your application, you might want a button to have different state in di...
...And 19 more matches
Creating Event Targets - Archive of obsolete content
Modules as Event Targets We can adapt this code into a separate module that exposes the SDK's standard event interface. To do this we'll use the even...
... Modules as Event Targets We can adapt this code into a separate module that exposes the SDK's standard event interface. To do this we'll use the event/core module. Create a new file in "lib" called "bookmarks.js", and add the following code...
...okmarkObserver]) }; bookmarkService.addObserver(bookmarkObserver, false); exports.on = on.bind(null, exports); exports.once = once.bind(null, exports); exports.removeListener = function removeListener(type, listener) { off(exports, type, listener); }; This code implements a module which can emit added and visited events. ...
...And 19 more matches
Adding preferences to an extension - Archive of obsolete content
other period, then a preference name, as seen in the example above. The JavaScript code In order to monitor changes to our preferences, we need to install an observer using the nsIPrefBranch2 interface. To do that, we need to reimplement our code into an object. That involves turning each function into a member of the StockWatcher class. Let's take a look at each function in the class. startup
() The StockWatcher.startup
() function is called when our extension is first loaded. Its job is to start up the observer to watch for changes to our preferences, instantiate an object to use to manage our preferences, and install an interval routine to update the stock information periodically. var StockWatcher = { prefs: null, tickerSymbol: "", // Initialize the extension startup: f...
...tockWatcher.startup
() function is called when our extension is first loaded. Its job is to start up the observer to watch for changes to our preferences, instantiate an object to use to manage our preferences, and install an interval routine to update the stock information periodically. ...
...nsion startup: function
() { // Register to receive notifications of preference changes this.prefs = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService) .getBranch("extensions.stockwatcher2."); this.prefs.addObserver("", this, false); this.tickerSymbol = this.prefs.getCharPref("symbol").toUpperCase
(); this.refreshInformation
(); window.setInterval(this.refreshInformation, 10*60*1000); } }, Our object has two member variables. prefs is configured by startup
() to reference our extension's preferences, while tickerSymbol indicates the stock symbol to monitor. The first thing the startup
() function does is to get a reference to the preferences for our extension. This is done in t...
...And 19 more matches
Desktop gamepad controls - Game development
"Gamepad: " + controller.id; } The second line in the gamepadHandler function shows up on the screen when the device is connected: We can also show the id of the device -- in the case above we're using the XBox 360 wireless controller. To update the state of the gamepad's currently pressed buttons we will need a function that will do exactly that on every frame: function gamepadUpdateHandler
() { buttonsPressed = []; if(controller.buttons) { for(var b=0; b<controller.buttons.length; b++) { if(controller.buttons[b].pressed) { buttonsPressed.push(b); } } } } We first reset the buttonsPressed array to get it ready to store the latest info we'll write to it from the current frame. Then, if the buttons are available we loop...
... buttonsPressed.push(b); } } } } We first reset the buttonsPressed array to get it ready to store the latest info we'll write to it from the current frame. Then, if the buttons are available we loop through them; if the pressed property is set to true, then we add them to the buttonsPressed array for later processing. ...
...for(var i=0; i<buttonsPressed.length; i++) { if(buttonsPressed[i] == button) { press = true; } } return press; } The function takes a button as a parameter; in the loop it checks if the given button's number is among the currently pressed buttons available in the buttonsPressed array. If it is, then the function returns true; false otherwise. ...
...And 19 more matches
Useful string methods - Learn web development
Type[browserType.length-1]; The length of "mozilla" is 7, but because the count starts at 0, the character position is 6; using length-1 gets us the last character. Finding a substring inside a string and extracting it Sometimes you'll want to find if a smaller string is present inside a larger one (we generally say if a substring is present inside a string). This can be done using the indexOf
() method, which takes a single parameter -- the substring you want to search for. If the substring is found inside the main string, it returns a number representing the index position of the substring -- which character number of the main string the substring starts at. If the substring is not found inside the main string, it returns a value of -1. Try this: browserType.indexOf('zilla'); Th...
...main string. You could use this to find all instances of strings that don't contain the substring 'mozilla', or do, if you use the negation operator, as shown below. You could do something like this: if(browserType.indexOf('mozilla') !== -1) { // do stuff with the string } When you know where a substring starts inside a string, and you know at which character you want it to end, slice
() can be used to extract it. Try the following: browserType.slice(0,3); This returns "moz" -- the first parameter is the character position to start extracting at, and the second parameter is the character position after the last one to be extracted. So the slice happens from the first position, up to, but not including, the last position. In this example, since the starting index is 0, the sec...
...lude the character position from where you want to extract the remaining characters in a string. Try the following: browserType.slice(2); This returns "zilla" -- this is because the character position of 2 is the letter z, and because you didn't include a second parameter, the substring that was returned was all of the remaining characters in the string. Note: The second parameter of slice
() is optional: if you don't include it, the slice ends at the end of the original string. There are other options too; study the slice
() page to see what else you can find out. Changing case The string methods toLowerCase
() and toUpperCase
() take a string and convert all the characters to lower- or uppercase, respectively. This can be useful for example if you want to normalize all user-entered ...
...And 19 more matches
IME handling guide
s) on each platform. This capsules the logic to dispatch WidgetCompositionEvent and WidgetKeyboardEvent for making the behavior on each platform exactly same. For example, if WidgetKeyboardEvent should be dispatched when there is a composition is managed by this class in XP level. First of use, native IME handlers get the rights to use TextEventDispatcher with a call of BeginNativeInputTransaction
(). Then, StartComposition
(), SetPendingComposition
(), FlushPendingComposition
(), CommitComposition
(), etc. are available if BeginNativeInputTransaction
() return true. These methods automatically manage composition state and dispatch WidgetCompositionEvent properly. This is also used by mozilla::TextInputProcessor which can emulates (or implements) IME with chrome script. So, native IME handlers us...
...ifies widget of IME getting focus. When the editor or windowless plugin loses focus, it notifies widget of IME losing focus, stops observing everything and is released. This class observes selection changes (caret position changes), text changes of a focused editor and layout changes (by reflow or scroll) of everything in the document. It depends on the result of nsIWidget::GetIMEUpdatePreference
() what is observed. When this notifies something of widget and/or IME, it needs to be safe to run script because notifying something may cause dispatching one or more DOM events and/or new reflow. Therefore, IMEContentObserver only stores which notification should be sent to widget and/or IME. Then, mozilla::IMEContentObserver::IMENotificationSender tries to send the pending notifications when it ...
...ething may cause dispatching one or more DOM events and/or new reflow. Therefore, IMEContentObserver only stores which notification should be sent to widget and/or IME. Then, mozilla::IMEContentObserver::IMENotificationSender tries to send the pending notifications when it might become safe to do that. Currently, it's tried: after a native event is dispatched from PresShell::HandleEventInternal
() at changing focus from a windowless plugin when new focused editor receives DOM "focus" event The 3rd timing may not be safe actually, but it causes a lot of oranges of automated tests. See also Notifications to IME section for the detail of sending notifications. Currently, WidgetQueryContentEvent is handled via IMEContentObserver because if it has a cache of selection, it can set reply ...
...And 19 more matches
XPCOMUtils.jsm
to your JavaScript scope: Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); Using XPCOMUtils Exposing a JavaScript class as a component using these utility methods requires four key steps: Import XPCOMUtils.jsm, as explained previously. Declare the class (or multiple classes) implementing the component(s). Create an array of component constructors. ...
...t scope: Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); Using XPCOMUtils Exposing a JavaScript class as a component using these utility methods requires four key steps: Import XPCOMUtils.jsm, as explained previously. Declare the class (or multiple classes) implementing the component(s). Create an array of component constructors. Define the NSGetFactory
() or NSGetModule
() entry point. Pseudocode This section provides some pseudocode that demonstrates how to put together a JavaScript class based on the steps listed above. Constructor The constructor is a simple method that handles any required initialization tasks. function MyComponent
() { // initialize the component here } Class declaration Declare the class prototype, using a form similar to this. MyC...
.... MyComponent.prototype = { // properties required for XPCOM registration: classDescription: "unique text description", classID: Components.ID("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractID: "@example.com/xxx;1", // [optional] custom factory (an object implementing nsIFactory). If not // provided, the default factory is used, which returns // |(new MyComponent
()).QueryInterface(iid)| in its createInstance
(). _xpcom_factory: { ... }, // [optional] an array of categories to register this component in. _xpcom_categories: [{ // Each object in the array specifies the parameters to pass to // nsICategoryManager.addCategoryEntry
(). 'true' is passed for // both aPersist and aReplace params. category: "some-category", // optional, defau...
...And 19 more matches
Hacking Tips
he shell with their description. Note that some functions have been moved under an 'os' object, and help(os) will give brief help on just the members of that "namespace". Getting the bytecode of a function (from JS shell) The shell has a small function named dis to dump the bytecode of a function with its source notes. Without arguments, it will dump the bytecode of its caller. ...
....., construct=js::NO_CONSTRUCT) at js/src/vm/Interpreter.cpp:476 #3 0x000000000069bdcf in js::jit::DoCallFallback(JSContext*, js::jit::BaselineFrame*, js::jit::ICCall_Fallback*, uint32_t, JS::Value*, JS::MutableHandleValue) (cx=0x14f2640, frame=0x7fffffff6ad8, stub_=0x1798838, argc=1, vp=0x7fffffff6a88, res=JSVAL_VOID) at js/src/jit/BaselineIC.cpp:6113 #4 0x00007ffff7f41395 in <<JitFrame_Exit>>
() #5 0x00007ffff7f42223 in <<JitFrame_BaselineStub>>
() #6 0x00007ffff7f4423d in <<JitFrame_BaselineJS>>
() #7 0x00007ffff7f4222e in <<JitFrame_BaselineStub>>
() #8 0x00007ffff7f4326a in <<JitFrame_BaselineJS>>
() #9 0x00007ffff7f38d5f in <<JitFrame_Entry>>
() #10 0x00000000006a86de in EnterBaseline(JSContext*, js::jit::EnterJitData&) (cx=0x14f2640, data=...) at js/src/jit/BaselineJIT.cpp:150 ...
... Setting a breakpoint in the generated code (from gdb, x86 / x86-64, arm) To set a breakpoint the generated code of a specific JSScript compiled with IonMonkey. Set a breakpoint on the instruction you are interested in. If you have no precise idea which function you are looking at, you can set a breakpoint on the js::ion::CodeGenerator::visitStart function. ...
...And 19 more matches
nsIContentViewer
Inherits from: nsISupports Last changed in Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7) Implemented by: ?????????????????????????????????????. ...
...underbird 10.0 / SeaMonkey 2.7) Implemented by: ?????????????????????????????????????. ...
...???????????????. ...
...And 19 more matches
nsIDownloadManager
erview nsIDownload addDownload(in short aDownloadType, in nsIURI aSource, in nsIURI aTarget, in AString aDisplayName, in nsIMIMEInfo aMIMEInfo, in PRTime aStartTime, in nsILocalFile aTempFile, in nsICancelable aCancelable, in boolean aIsPrivate); void addListener(in nsIDownloadProgressListener aListener); void cancelDownload(in unsigned long aID); void cleanUp
(); void endBatchUpdate
(); Obsolete since Gecko 1.9.1 void flush
(); Obsolete since Gecko 1.8 nsIDownload getDownload(in unsigned long aID); void onClose
(); Obsolete since Gecko 1.9.1 void open(in nsIDOMWindow aParent, in nsIDownload aDownload); Obsolete since Gecko 1.9.1 void openProgressDialogFor(in nsIDownload aDownload, in nsIDOMWindow aParen...
...Read only. activeDownloads nsISimpleEnumerator An enumeration of active nsIDownloads. Read only. canCleanUp boolean Whether or not th...
...Read only. activeDownloads nsISimpleEnumerator An enumeration of active nsIDownloads. Read only. canCleanUp boolean Whether or not there are downloads that can be cleaned up (removed) that is ...
...And 19 more matches
nsIMessenger
is defined as messenger via the createMessenger function in mailWindow.js. ...
... the createMessenger function in mailWindow.js. ...
...Method overview void setDisplayCharset(in ACString aCharset); void setWindow(in nsIDOMWindow ptr, in nsIMsgWindow msgWindow); void openURL(in ACString aURL); void loadURL(in nsIDOMWindow ptr, in ACString aURL); void launchExternalURL(in ACString aURL); boolean canUndo
(); boolean canRedo
(); unsigned long getUndoTransactionType
(); unsigned long getRedoTransactionType
(); void undo(in nsIMsgWindow msgWindow); void redo(in nsIMsgWindow msgWindow); void sendUnsentMessages(in nsIMsgIdentity aIdentity, in nsIMsgWindow aMsgWindow); void setDocumentCharset(in ACString characterSet); void saveAs(in ACString aURI, in boolean aAsFile, in nsIMsgIdentity aIdentity, in AString aMsgF...
...And 19 more matches
nsITreeBoxObject
ul/base/src/tree/public/nsITreeBoxObject.idlScriptable Please add a summary to this article. ...
...bject.idlScriptable Please add a summary to this article. ...
...d a summary to this article. ...
...And 19 more matches
Storage
ension is treated specially by Windows as a known extension for an 'Application Compatibility Database' and changes are backed up by the system automatically as part of system restore functionality. This can result in significantly higher overhead file operation. Closing a connection To close a connection on which only synchronous transactions were performed, use the mozIStorageConnection.close
() method. If you performed any asynchronous transactions, you should instead use the mozIStorageConnection.asyncClose
() method. The latter will allow all ongoing transactions to complete before closing the connection, and will optionally notify you via callback when the connection is closed. Statements This section demonstrates how you can execute SQL statements on your database. For a complete r...
...losed. Statements This section demonstrates how you can execute SQL statements on your database. For a complete reference see mozIStorageStatement. Creating a Statement There are actually two ways to execute a statement. You should choose the right one based on your needs. ...
...Similarly, the C++ looks like this: nsCOMPtr<mozIStorageStatement> statement; rv = dbConn->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM table_name WHERE...
...And 19 more matches
Using Performance Timeline - Web APIs
ce events occur. Together, these interfaces can be used to help identify an application's performance bottlenecks. Performance extensions Performance Timeline extends the Performance object with three methods that provide different mechanisms to get a set of performance records (metrics), depending on the specified filter criteria. ...
...ether, these interfaces can be used to help identify an application's performance bottlenecks. Performance extensions Performance Timeline extends the Performance object with three methods that provide different mechanisms to get a set of performance records (metrics), depending on the specified filter criteria. ...
... can be used to help identify an application's performance bottlenecks. Performance extensions Performance Timeline extends the Performance object with three methods that provide different mechanisms to get a set of performance records (metrics), depending on the specified filter criteria. The following example show the usage of these methods getEntries
(), getEntriesByName
() and getEntriesByType
(). ...
...And 19 more matches
Background audio processing using AudioWorklet - Web APIs
ran on the main thread, thus blocking everything else going on until it completed execution. This was far less than ideal, especially for something that can be as computationally expensive as audio processing. Enter AudioWorklet. An audio context's audio worklet is a Worklet which runs off the main thread, executing audio processing code added to it by calling the context's audioWorklet.addModule
() method. Calling addModule
() loads the specified JavaScript file, which should contain the implementation of the audio processor. With the processor registered, you can create a new AudioWorkletNode which passes the audio through the processor's code when the node is linked into the chain of audio nodes along with any other audio nodes. The process of creating an audio processor using JavaScript,...
...level overview of what's involved. Create module that defines a audio worklet processor class, based on AudioWorkletProcessor which takes audio from one or more incoming sources, performs its operation on the data, and outputs the resulting audio data. Access the audio context's AudioWorklet through its audioWorklet property, and call the audio worklet's domxref("Worklet.addModule", "addModule
()")}} method to install the audio worklet processor module. As needed, create audio processing nodes by passing the processor's name (which is defined by the module) to the AudioWorkletNode
() constructor. Set up any audio parameters the AudioWorkletNode needs, or that you wish to configure. These are defined in the audio worklet processor module. Connect the created AudioWorkletNodes into your a...
...wice as long) is implemented using a JavaScript module that defines and installs the custom audio processor class. Structure of an audio worklet processor An audio worklet processor is a JavaScript module which consists of the following: A JavaScript class which defines the audio processor. This class extends the AudioWorkletProcessor class. The audio processor class must implement a process
() method, which receives incoming audio data and writes back out the data as manipulated by the processor. The module installs the new audio worklet processor class by calling registerProcessor
(), specifying a name for the audio processor and the class that defines the processor. A single audio worklet processor module may define multiple processor classes, registering each of them with individu...
...And 19 more matches
filter - CSS: Cascading Style Sheets
for any function is invalid, the function returns none. Except where noted, the functions that take a value expressed with a percent sign (as in 34%) also accept the value expressed as decimal (as in 0.34). When a single filter property has two or more functions it's results will be different from when two or more filter properties are separately applied with the same functions. SVG filter url
() Takes an URI pointing to an SVG filter, which may be embedded in an external XML file. filter: url(resources.svg#c1) Filter functions blur
() The blur
() fucntion applies a Gaussian blur to the input image. The value of radius defines 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. T...
...A value of 0% will create an image that is completely black. A value of 100% leaves the input unchanged. Other values are linear multipliers on the effect. Values of an amount over 100% are allowed, providing brighter results. The lacuna value for interpolation is 1. filter: brightnes...
...A value of 0% will create an image that is completely black. A value of 100% leaves the input unchanged. Other values are linear multipliers on the effect. Values of an amount over 100% are allowed, providing brighter results. The lacuna value for interpolation is 1. filter: brightness(2) <svg style="...
...And 19 more matches
Functions - JavaScript
]([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 anonymous function expression (the name is not used): var myFunction = function
() { statements } It is also possible to provide a name inside the definition in order to create a named function expression: var myFunction = function namedFunction
(){ statements } One of the benefits of creating a named function expression is that in case we encountered an error, the stack trace will contain the name of the function, making it easier to find the origin of the error. A...
...untered an error, the stack trace will contain the name of the function, making it easier to find the origin of the error. As we can see, both examples do not start with the function keyword. Statements involving functions which do not start with function are function expressions. When functions are used only once, a common pattern is an IIFE (Immediately Invoked Function Expression). (function
() { statements })
(); IIFE are function expressions that are invoked as soon as the function is declared. The generator function declaration (function* statement) There is a special syntax for generator function declarations (see function* statement for details): function* name([param[, param[, ... param]]]) { statements } name The function name. param The name of an argument to...
...rgument to be passed to the function. statements The statements comprising the body of the function. The arrow function expression (=>) An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details): ([param[, param]]) => { statements } param => expression param The name of an argument. Zero arguments need to be indicated with
(). For only one argument, the parentheses are not required. (like foo => 1) statements or expression Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function. The Function constructor Note: Using the Function constructor to create functions is not recommended since it needs the function bod...
...And 19 more matches
Function.name - JavaScript
s Warning: Be careful when using Function.name and source code transformations, such as those carried out by JavaScript compressors (minifiers) or obfuscators. These tools are often used as part of a JavaScript build pipeline to reduce the size of a program prior to deploying it to production. Such transformations often change a function's name at build-time. ...
...when using Function.name and source code transformations, such as those carried out by JavaScript compressors (minifiers) or obfuscators. These tools are often used as part of a JavaScript build pipeline to reduce the size of a program prior to deploying it to production. Such transformations often change a function's name at build-time. ...
...sed as part of a JavaScript build pipeline to reduce the size of a program prior to deploying it to production. Such transformations often change a function's name at build-time. Source code such as: function Foo
() {}; let foo = new Foo
(); if (foo.constructor.name === 'Foo') { console.log("'foo' is an instance of 'Foo'"); } else { console.log('Oops!'); } may be compressed to: function a
() {}; let b = new a
(); if (b.constructor.name === 'Foo') { console.log("'foo' is an instance of 'Foo'"); } else { console.log('Oops!'); } In the uncompressed version, the program runs into the truthy-branch and logs "'foo' is an instance of 'Foo'". Whereas, in the compressed version it behaves differently, and runs into the else-branch. If you rely on Function.name, like in the example above,...
...And 19 more matches
yield* - JavaScript
Syntax yield* expression; expression The expression which returns an iterable object. Description The yield* expression iterates over the operand and yields each value returned by it. The value of yield* expression itself is the value returned by that iterator when it's closed (i.e., when done is true). ...
...ion; expression The expression which returns an iterable object. Description The yield* expression iterates over the operand and yields each value returned by it. The value of yield* expression itself is the value returned by that iterator when it's closed (i.e., when done is true). ...
... an iterable object. Description The yield* expression iterates over the operand and yields each value returned by it. The value of yield* expression itself is the value returned by that iterator when it's closed (i.e., when done is true). Examples Delegating to another generator In following code, values yielded by g1
() are returned from next
() calls just like those which are yielded by g2
(). ...
...And 19 more matches
context-menu - Archive of obsolete content
or while a selection exists. Declarative contexts You can specify some simple, declarative contexts when you create a menu item by setting the context property of the options object passed to its constructor, like this: var cm = require("sdk/context-menu"); cm.Item({ label: "My Menu Item", context: cm.URLContext("*.mozilla.org") }); Constructor Description PageContext
() The page context. SelectionContext
() This context occurs when the menu is invoked on a page in which the user has made a selection. SelectorContext(selector) This context occurs when the menu is invoked on a node that either matches selector, a CSS selector, or has an ancestor that matches. selector may include multiple selectors separated by commas, e.g., "a[href], ...
...Note that when you have a hierarchy of menu items the click event will be sent to the content script of the item clicked and all ancestors so be sure to verify that the data value passed matches the...
... label, but you can change its label later using a couple of methods. The simplest method is to set the menu item's label property. This example updates the item's label based on the number of times it's been clicked: var numClicks = 0; var myItem = require("sdk/context-menu").Item({ label: "Click Me: " + numClicks, contentScript: 'self.on("click", self.postMessage);', onMessage: function
() { numClicks++; this.label = "Click Me: " + numClicks; // Setting myItem.label is equivalent. } }); Sometimes you might want to update the label based on the context. For instance, if your item performs a search with the user's selected text, it would be nice to display the text in the item to provide feedback to the user. In these cases you can use the second method. Recall that yo...
...And 18 more matches
ui/sidebar - Archive of obsolete content
reate sidebars. A sidebar is a vertical strip of user interface real estate for your add-on that's attached to the left-hand side of the browser window. You specify its content using HTML, CSS, and JavaScript, and the user can show or hide it in the same way they can show or hide the built-in sidebars. Usage Creating, showing, and hiding sidebars You construct a Sidebar object using the Sidebar
() constructor. Once you've done that, you can show the sidebar by calling the Sidebar's show
() method. If a new window is opened from a window that has a sidebar visible, the new window gets a sidebar, too. You can hide the sidebar by calling its hide
() method. Called with no arguments, show
() and hide
() will operate on the currently active window. From Firefox 33 onwards you can pass a BrowserW...
...you can pass a BrowserWindow into these methods, and they will then operate on the specified window. Alternatively, the View->Sidebar submenu in Firefox will contain a new item which the user can use to show or hide the sidebar: The sidebar generates a show event when it is shown and a hide event when it is hidden. Once you've finished using the sidebar you can destroy it by calling its dispose
() method. To show what a sidebar looks like, here's a sidebar that displays the results of running the W3C Validator on the current page: Specifying sidebar content The content of a sidebar is specified using HTML, which is loaded from the URL supplied in the url option to the sidebar's constructor. Unlike modules such as panel, the content must be local, typically loaded from the add-on's dat...
... sidebar that displays the results of running the W3C Validator on the current page: Specifying sidebar content The content of a sidebar is specified using HTML, which is loaded from the URL supplied in the url option to the sidebar's constructor. Unlike modules such as panel, the content must be local, typically loaded from the add-on's data directory via a URL constructed using self.data.url
(): var sidebar = require("sdk/ui/sidebar").Sidebar({ id: 'my-sidebar', title: 'My sidebar', url: require("sdk/self").data.url("sidebar.html") }); From Firefox 34, you can use "./sidebar.html" as an alias for self.data.url("sidebar.html"). So you can rewrite the above code like this: var sidebar = require("sdk/ui/sidebar").Sidebar({ id: 'my-sidebar', title: 'My sidebar', url: "./side...
...And 18 more matches
listbox - Archive of obsolete content
s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
...lect attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
... tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...And 18 more matches
prefwindow - Archive of obsolete content
e safely omitted in XULrunner-based applications but you can override the default behavior (true for Mac OS X and false for other platforms) setting it. For animateFadeIn to work properly, contents of prefpanes should be put into overlays. Note for Mac OS X: a common way of opening modal windows on Mac OS X that are not attached as a sheet to the main window is to use nsIWindowWatcher.openWindow
() with a null parentWindow. This does not work with prefwindows, breaking the general behavior of the window and in particular the list of prefpanes. Prefer the classical window.openDialog
() with the following window features: "chrome,titlebar,toolbar,centerscreen,dialog=yes". Attributes buttonalign, buttondir, buttonorient, buttonpack, buttons, defaultButton, lastSelected, onbeforeaccept, ondi...
...at.) lastSelected Type: string Set this to the id of the last selected pane. It will be opened by default the next time the preferences dialog is opened. preferencePanes Type: DOM NodeList Holds a list of all the prefpane elements in the window. type Type: string Gets and sets the value of the type attribute. ...
...Selected Type: string Set this to the id of the last selected pane. It will be opened by default the next time the preferences dialog is opened. preferencePanes Type: DOM NodeList Holds a list of all the prefpane elements in the window. type Type: string Gets and sets the value of the type attribute. ...
...And 18 more matches
richlistbox - Archive of obsolete content
s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
...ct attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
... tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...And 18 more matches
tabbrowser - Archive of obsolete content
ost of its methods are callable directly on the element itself, such as goBack and goForward. It also contains the load constants used by reloadWithFlags and loadURIWithFlags. webProgress Type: nsIWebProgress This read-only property contains an nsIWebProgress object which is used to monitor the progress of a document loading. ...
...ods are callable directly on the element itself, such as goBack and goForward. It also contains the load constants used by reloadWithFlags and loadURIWithFlags. webProgress Type: nsIWebProgress This read-only property contains an nsIWebProgress object which is used to monitor the progress of a document loading. ...
...on the element itself, such as goBack and goForward. It also contains the load constants used by reloadWithFlags and loadURIWithFlags. webProgress Type: nsIWebProgress This read-only property contains an nsIWebProgress object which is used to monitor the progress of a document loading. ...
...And 18 more matches
Anatomy of a video game - Game development
of time, every frame, or only after something else happens. Being more specific with the browser about when your function needs to be called allows the browser to optimize when it is called. Also, it will probably make your job easier. ...
...ttach that function to anything other than the browser's redraw schedule? On the Web, window.requestAnimationFrame
() will be the foundation of most well-programmed per-frame main loops. A callback function must be passed in to it when it is called. That callback function will be executed at a suitable time before the next repaint. Here is an example of a simple main loop: window.main = function
() { window.requestAnimationFrame( main ); // Whatever your main loop needs to do }; main
(); // Start the cycle Note: In each of the main
() methods discussed here, we schedule a new requestAnimationFrame before performing our loop contents. That is not by accident and it is considered best practice. Calling the next requestAnimationFrame early ensures the browser receives it on time to plan ...
... a new requestAnimationFrame before performing our loop contents. That is not by accident and it is considered best practice. Calling the next requestAnimationFrame early ensures the browser receives it on time to plan accordingly even if your current frame misses its VSync window. The above chunk of code has two statements. The first statement creates a function as a global variable called main
(). This function does some work and also tells the browser to call itself next frame with window.requestAnimationFrame
(). The second statement calls the main
() function, defined in the first statement. Because main
() is called once in the second statement and every call of it places itself in the queue of things to do next frame, main
() is synchronized to your framerate. Of course this loop is not...
...And 18 more matches
Making decisions in your code — conditionals - Learn web development
to true if the child did the shopping. Note: You can see a more complete version of this example on GitHub (also see it running live.) else if The last example provided us with two choices, or outcomes -- but what if we want more than two? There is a way to chain on extra choices/outcomes to your if...else -- using else if. Each extra choice requires an additional block to put in between if
() { ... } and else { ... } -- check out the following more involved example, which could be part of a simple weather forecast application: <label for="weather">Select the weather type today: </label> <select id="weather"> <option value="">--Make a choice--</option> <option value="sunny">Sunny</option> <option value="rainy">Rainy</option> <option value="snowing">Snowing</option> <option v...
...Wear shorts! Go to the beach, or the park, and get an ice cream.'; } else if (choice === 'rainy') { para.textContent = 'Rain is falling outside; take a rain coat and an umbrella, and don\'t stay out for too long.'; } else if (choice === 'snowing') { para.textConten...
...n any minute, so take a rain coat just in case.'; } else { para.textContent = ''; } } Here we've got an HTML <select> element allowing us to make different weather choices, and a simple paragraph. In the JavaScript, we are storing a reference to both the <select> and <p> elements, and adding an event listener to the <select> element so that when its value is changed, the setWeather
() function is run. When this function is run, we first set a variable called choice to the current value selected in the <select> element. We then use a conditional statement to show different text inside the paragraph depending on what the value of choice is. Notice how all the conditions are tested in else if
() {...} blocks, except for the first one, which is tested in an if
() {...} block. The ...
...And 18 more matches
Adding features to our bouncing balls demo - Learn web development
ve a separate copy of the demo after you get each stage working, so you can refer back to it if you find yourself in trouble later on. Project brief Our bouncy ball demo is fun, but now we want to make it a little bit more interactive by adding a user-controlled evil circle, which will eat the balls if it catches them. We also want to test your object-building skills by creating a generic Shape
() object that our balls and evil circle can inherit from. Finally, we want to add a score counter to track the number of balls left to capture. The following screenshot gives you an idea of what the finished program should look like: To give you more of an idea, have a look at the finished example (no peeking at the source code!) Steps to complete The following sections describe what you n...
...add a score counter to track the number of balls left to capture. The following screenshot gives you an idea of what the finished program should look like: To give you more of an idea, have a look at the finished example (no peeking at the source code!) Steps to complete The following sections describe what you need to do. Creating our new objects First of all, change your existing Ball
() constructor so that it becomes a Shape
() constructor and add a new Ball
() constructor: The Shape
() constructor should define the x, y, velX, and velY properties in the same way as the Ball
() constructor did originally, but not the color and size properties. It should also define a new property called exists, which is used to track whether the balls exist in the program (have not been eaten by...
... Ball
() constructor: The Shape
() constructor should define the x, y, velX, and velY properties in the same way as the Ball
() constructor did originally, but not the color and size properties. It should also define a new property called exists, which is used to track whether the balls exist in the program (have not been eaten by the evil circle). This should be a boolean (true/false). The Ball
() constructor should inherit the x, y, velX, velY, and exists properties from the Shape
() constructor. It should also define a color and a size property, like the original Ball
() constructor did. Remember to set the Ball
() constructor's prototype and constructor appropriately. ...
...And 18 more matches
Object building practice - Learn web development
o set up the <canvas> element and provide a general function that we're going to use. The first part of the script looks like so: const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); const width = canvas.width = window.innerWidth; const height = canvas.height = window.innerHeight; This script gets a reference to the <canvas> element, then calls the getContext
() method on it to give us a context on which we can start to draw. The resulting constant (ctx) is the object that directly represents the drawing area of the canvas and allows us to draw 2D shapes on it. Next, we set constants called width and height, and the width and height of the canvas element (represented by the canvas.width and canvas.height properties) to equal the width and height of the ...
...th and height of the browser viewport (the area that the webpage appears on -- this can be gotten from the Window.innerWidth and Window.innerHeight properties). Note that we are chaining multiple assignments together, to get the variables all set quicker -- this is perfectly OK. The last bit of the initial script looks as follows: function random(min, max) { const num = Math.floor(Math.random
() * (max - min + 1)) + min; return num; } This function takes two numbers as arguments, and returns a random number in the range between the two. Modeling a ball in our program Our program will feature lots of balls bouncing around the screen. Since these balls will all behave in the same way, it makes sense to represent them with an object. Let's start by adding the following constructor to t...
...hese values are regularly added to the x/y coordinate values when we animate the balls, to move them by this much on each frame. color -- each ball gets a color. size -- each ball gets a size -- this is its radius, in pixels. This handles the properties, but what about the methods? We want to get our balls to actually do something in our program. Drawing the ball First add the following draw
() method to the Ball
()'s prototype: Ball.prototype.draw = function
() { ctx.beginPath
(); ctx.fillStyle = this.color; ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI); ctx.fill
(); } Using this function, we can tell the ball to draw itself onto the screen, by calling a series of members of the 2D canvas context we defined earlier (ctx). The context is like the paper, and now we want to com...
...And 18 more matches
NSS API Guidelines
e "bottom layer" API, or BLAPI. Within PKCS #11, wraps Crypto lib/freebl blapi.h, blapit.h jar Provides support for reading and writing data in Java Archive (jar) format, including zlib compression. Port lib/jar jar-ds.h, jar.h, jarfile.h nss Provides high-level initialiazation and shutdown of security services. Specifically, this library provides NSS_Init
() for establishing default certificate, key, module databases, and initializing a default random number generator. NSS_Shutdown
() closes these databases, to prevent further access by an application. Above High Cert, High Key lib/nss nss.h pk11wrap Provides access to PKCS #11 modules, through a unified interface. The pkcs11wrap library provides functions for selecting/finding PK...
... accomplish these tasks, it makes it easier for the developer to learn how to use our functions. This section of the document should grow as we develop our API. First some general rules. These rules are derived from existing coding practices inside the security library, since consistency is more important than debates about what might look nice. Public functions should have the form LAYER_Body
(), where LAYER is an all caps prefix for what layer the function lives in, and Body is concatenated English words, where the beginning letter of each word is capitalized (also known as CamelCase). For Example: LAYER_CapitalizedEnglishWords
() or CERT_DestroyCertificate
(). Data types and typdefs should have the Form LAYERBody, with the same definitions for LAYER as public functions, and Body in came...
...uld have the Form LAYERBody, with the same definitions for LAYER as public functions, and Body in camel case English words. For example: LAYERCapitalizedEnglishWords or SECKEYPrivateKey. Structures should have the same name as their typedefs, with the string Str added to the end. For example LAYERCapitalizedEnglishWordsStr or SECKEYPrivateKeyStr. ...
...And 18 more matches
nsIContentPrefService2
extracts the full domain from the URL, so if you specify "http://foo.bar.example.com/baz", the domain is taken to be "foo.bar.example.com", not "example.com". Private-Browsing Context Parameters Many methods also accept a "context" parameter. This parameter relates to private browsing and determines the kind of storage that a method uses, either the usual permanent storage or temporary storage set
() aside for private browsing sessions. Pass null to unconditionally use permanent storage. Pass an nsILoadContext to use storage appropriate to the context's usePrivateBrowsing attribute: if usePrivateBrowsing is true, temporary private-browsing storage is used, and otherwise permanent storage is used. A context can be obtained from the window or channel whose content pertains to the preferences be...
...The service holds a strong reference to the observer, so the observer must be removed later to avoid leaking it. void addObserverForName( in AString ...
...ng domain, in AString name, in nsIVariant value, in nsILoadContext context, [optional] in nsIContentPrefCallback2 callback); void setGlobal(in AString name, in nsIVariant value, in nsILoadContext context, [optional] in nsIContentPrefCallback2 callback); Methods addObserverForName
() Registers an observer that will be notified whenever a preference with the given name is set
() or removed. When a set
() or remove method is called, observers are notified after the set
() or removal completes but before method's callback is called. The service holds a strong reference to the observer, so the observer must be removed later to avoid leaking it. void addObserverForName( in AString name, in nsIContentPrefObserver observer ); Parameters name The name of the p...
...And 18 more matches
Compositing example - Web APIs
Everything else is made transparent.', 'The new shape is drawn where it doesn\'t overlap the existing canvas content.', 'The new shape is only drawn where it overlaps the existing canvas content.', 'Ne...
..., 'Preserves the luma and chroma of the bottom layer, while adopting the hue of the top layer.', 'Preserves the luma and hue of the bottom layer, while adopting the chroma of the top layer.', 'Preserves the luma of the bottom layer, while adopting the hue and chroma of the top layer.', 'Preserves the hue and chroma of the bottom layer, while adopting the luma of the top layer.' ].reverse
(); var width = 320; var height = 340; Main program When the page loads, this code runs to set up and run the example: window.onload = function
() { // lum in sRGB var lum = { r: 0.33, g: 0.33, b: 0.33 }; // resize canvas canvas1.width = width; canvas1.height = height; canvas2.width = width; canvas2.height = height; lightMix
() colorS...
... width = 320; var height = 340; Main program When the page loads, this code runs to set up and run the example: window.onload = function
() { // lum in sRGB var lum = { r: 0.33, g: 0.33, b: 0.33 }; // resize canvas canvas1.width = width; canvas1.height = height; canvas2.width = width; canvas2.height = height; lightMix
() colorSphere
(); runComposite
(); return; }; And this code, runComposite
(), handles the bulk of the work, relying on a number of utility functions to do the hard parts. ...
...And 18 more matches
Using writable streams - Web APIs
ive also). This takes a given message and writes it into a writable stream, displaying each chunk on the UI as it is written to the stream and also displaying the whole message on the UI when writing has finished. How writable streams work Let's look at how the writable stream functionality in our demo works. Constructing a writable stream To create a writable stream, we use the WritableStream
() constructor; the syntax looks complex at first, but actually isn't too bad. The syntax skeleton looks like this: const stream = new WritableStream({ start(controller) { }, write(chunk,controller) { }, close(controller) { }, abort(reason) { } }, { highWaterMark, size
() }); The constructor takes two objects as parameters. The first object is required, and creates a model ...
...This is called whe...
...This is called when each chunk is actually...
...And 18 more matches
Window - Web APIs
re documented in the JavaScript Reference and the DOM Reference. In a tabbed browser, each tab is represented by its own Window object; the global window seen by JavaScript code running within a given tab always represents the tab in which the code is running. That said, even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such as resizeTo
() and innerHeight. Generally, anything that can't reasonably pertain to a tab pertains to the window instead. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio=...
... a:hover text { fill: #0095DD; pointer-events: all;} Constructors See also the DOM Interfaces. DOMParser DOMParser can parse XML or HTML source stored in a string into a DOM Document. DOMParser is specified in DOM Parsing and Serialization. Image Used for creating an HTMLImageElement. 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...
...the content element in the current window. Since Firefox 57 (initially Nightly-only), both versions are only available from chrome (privileged) code, and not available to the web anymore. Window.defaultStatus Gets/sets the status bar text for the given window. Window.dialogArguments Read only Gets the arguments passed to the window (if it's a dialog box) at the time window.showModalDialog
() was called. This is an nsIArray. Window.directories Synonym of window.personalbar Window.globalStorage Multiple storage objects that were used for storing data across multiple pages. Window.mozAnimationStartTime The time in milliseconds since epoch at which the current animation cycle began. Use Animation.startTime instead. Window.mozPaintCount Returns the number of times th...
...And 18 more matches
Object - JavaScript
Description Nearly all objects in JavaScript are instances of Object; a typical object inherits properties (including methods) from Object.prototype, although these properties may be shadowed (a.k.a. overridden). However, an Object may be deliberately created for which this is not true (e.g. by Object.create(null)), or it may be altered so that this is no longer true (e.g. ...
... object behavior. The Object constructor creates an object wrapper for the given value. If the value is null or undefined, it will create and return an empty object. Otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value. When called in a non-constructor context, Object behaves identically to new Object
(). ...
...urn an object of a Type that corresponds to the given value. If the value is an object already, it will return the value. When called in a non-constructor context, Object behaves identically to new Object
(). See also the object initializer / literal syntax. Deleting a property from an object There isn't any method in an Object itself to delete its own properties (such as Map.prototype.delete
()). To do so, one must use the delete operator. Constructor Object
() Creates a new Object object. It is a wrapper for the given value. ...
...And 18 more matches
Communicating using "port" - Archive of obsolete content
This page is now obsolete, and its content has been incorporated into the main page on content scripts. To enable add-on scripts and content scripts to communicate with each other, each end of the conversation has access to a port object. to send messages from one side to the other, use port.emit
() to receive messages sent from the other side, use port.on
() Messages are asynchronous: that is, the sender does not wait for a reply from the recipient but just emits the message and continues processing. Here's a simple add-on that sends a message to a content script using port: var tabs = require("sdk/tabs"); var alertContentScript = "self.port.on('alert', function(message) {" + " window.alert(message);" + "})"; tabs.on("ready", ...
... Accessing port Accessing port in the Content Script Note that the global self object is completely different from the self module, which provides an API for an add-on to access its data files and ID. In the content script the port object is a...
...('alert', function(message) {" + " window.alert(message);" + "})"; tabs.on("ready", function(tab) { worker = tab.attach({ contentScript: alertContentScript }); worker.port.emit("alert", "Message from the add-on"); }); tabs.open("http://www.mozilla.org"); In total, the port object defines four functions: emit
(): emit a message. on
(): listen to a message. removeListener
(): stop listening to a message. once
(): listen to only the first occurrence of a message. Accessing port Accessing port in the Content Script Note that the global self object is completely different from the self module, which provides an API for an add-on to access its data files and ID. In the content script the port object is available as a property ...
...And 17 more matches
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
t code. Add-on authors are strongly encouraged to update their code to eliminate all instances of eval, no matter if the add-on is to be hosted in the Mozilla Add-ons Gallery or not. In order to host your add-on with Mozilla it is crucial to minimize or completely eliminate eval use in order to receive a positive review and have your add-on made public. If it cannot be easily proven that an eval
() call is benign and necessary because there are no viable alternatives, a Mozilla Add-ons Gallery reviewer will generally reject the submission! Parsing JSON Mozilla provides native JSON support since Firefox 3. There is simply no need to parse JSON using eval. Additionally, parsing JSON retrieved from a remote location becomes a security vulnerability when parsed with the eval function. Basica...
...might be possible to execute any retrieved JSONP code in an unprivileged Sandbox (which is complicated!), but if you have a choice, just avoid JSONP altogether! Passing around functions/code as strings Often you'll want to pass functions or code to other functions, most notoriously setTimeout and addEventListener. Often this is done passing around strings. ...
...ode in an unprivileged Sandbox (which is complicated!), but if you have a choice, just avoid JSONP altogether! Passing around functions/code as strings Often you'll want to pass functions or code to other functions, most notoriously setTimeout and addEventListener. Often this is done passing around strings. ...
...And 17 more matches
Menu - Archive of obsolete content
reading through some examples. Because it is still under development, the API currently lives in the future and must be imported before it is used: jetpack.future.import("menu"); Menus All menus in Jetpack are jetpack.Menu objects, including both built-in Firefox menus and menus that features create. To create a new menu, use one of the jetpack.Menu constructors below. Constructors jetpack.Menu
() Creates an empty menu. jetpack.Menu(menuitems) Creates a menu with the given items. Parameters menuitems An array of menuitems. jetpack.Menu(properties) Creates a menu with specific properties. Parameters properties An object defining any of the properties below. The items property may be used to define an array of menuitems. Properties Property ...
... the context in which the menu was shown. beforeShow may modify the menu, and when the menu is shown, it will reflect the changes. isShowing boolean True if the menu is currently visible and false otherwise. Read-only. items array An array of menuitems in the menu. Read-only. Methods add(items) clear
() contextOn(node) hide
() insertBefore(newItems, target) item(target) popupOn(node) remove(target) replace(target, newItems) reset
() set(items) show(anchorNode) add(items) Adds items to the menu. The position at which the ...
... insertBefore(newItems, target) item(target) popupOn(node) remove(target) replace(target, newItems) reset
() set(items) show(anchorNode) add(items) Adds items to the menu. The position at which the items are added is at Jetpack's discretion. This method and set
() are the recommended methods of adding items to a menu. Parameters items A single menuitem or an array of menuitems. clear
() Removes all items from the menu, even items not added by the feature. contextOn(node) Binds the menu to a given node as its context menu. Parameters node The menu is attached to this node, which may be either a raw DOM node or a DOM node wrapp...
...And 17 more matches
Adding a new todo form: Vue events, methods, and models - Learn web development
ubmit event that will add the new todo to the ToDoItem data list defined inside App. To do that, we'll need to add a method to the component instance. ...
... the same place as data
(), props, etc. The methods property holds any methods we might need to call in our component. When referenced, methods are fully run, so it's not a good idea to use them to display information inside the template. For displaying data that comes from calculations, you should use a computed property, which we'll cover later. In this component, we need to add an onSubmit
() method to a methods property inside the ToDoForm component object. We'll use this to handle the submit action. Add this like so: export default { methods: { onSubmit
() { console.log('form submitted') } } } Next we need to bind the method to our <form> element's submit event handler. Much like how Vue uses the v-bind syntax for binding attributes, Vue has...
...submit="onSubmit"> When you run this, the app still posts the data to the server, causing a refresh. Since we're doing all of our processing on the client, there's no server to handle the postback. We also lose all local state on page refresh. To prevent the browser from posting to the server, we need to stop the event's default action from bubbling up through the page (Event.preventDefault
(), in vanilla JavaScript). Vue has a special syntax called event modifiers that can handle this for us right in our template. Modifiers are appended to the end of an event with a dot like so: @event.modifier. Here is a list of event modifiers: .stop: Stops the event from propagating. Equivalent to Event.stopPropagation
() in regular JavaScript events. .prevent: Prevents the event's defa...
...And 17 more matches
nsIEditorSpellCheck
refox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) Implemented by: @mozilla.org/editor/editorspellchecker;1. ...
....6) Implemented by: @mozilla.org/editor/editorspellchecker;1. ...
..."] .createInstance(Components.interfaces.nsIEditorSpellCheck); Method overview void AddWordToDictionary(in wstring word); boolean canSpellCheck
(); void checkCurrentDictionary
(); boolean CheckCurrentWord(in wstring suggestedWord); boolean CheckCurrentWordNoSuggest(in wstring suggestedWord); AString GetCurrentDictionary
(); void GetDictionaryList([array, size_is(count)] out wstring dictionaryList, out PRUint32 count); wstring GetNextMisspelledWord
(); void GetPersonalDictionary
(); wstring GetPersonalDictionaryWord
(); wstring GetSuggestedWord
(); void IgnoreWordAllOccurrences(in wstring word); void InitSpellChecker(in nsIEditor editor, in boolean enableSel...
...And 17 more matches
nsIFaviconService
22.0 (Firefox 22.0 / Thunderbird 22.0 / SeaMonkey 2.19) Implemented by: @mozilla.org/browser/favicon-service;1. ...
... void setFaviconDataFromDataURL(in nsIURI aFaviconURI, in AString aDataURL, in PRTime aExpiration); Obsolete since Gecko 22.0 void setFaviconUrlForPage(in nsIURI aPageURI, in nsIURI aFaviconURI); Obsolete since Gecko 22.0 Attributes Attribute Type Description defaultFavicon nsIURI The default favicon URI. Read only. Methods addFailedFavicon
() This method adds a given favicon's URI to the failed favicon cache. The lifespan of the favicon cache is up to the caching system. This cache will also be written to if you use setAndLoadFaviconForPage
() method and it encounters an error while fetching an icon. void addFailedFavicon( in nsIURI aFaviconURI ); Parameters aFaviconURI The URI of an icon in the favicon service. Can be null...
...given favicon's URI to the failed favicon cache. The lifespan of the favicon cache is up to the caching system. This cache will also be written to if you use setAndLoadFaviconForPage
() method and it encounters an error while fetching an icon. void addFailedFavicon( in nsIURI aFaviconURI ); Parameters aFaviconURI The URI of an icon in the favicon service. Can be null. expireAllFavicons
() Expires all known favicons, removing them from the database. Note: This is an asynchronous operation; when it completes, a "places-favicons-expired" notification is dispatched through the observer's service. ...
...And 17 more matches
nsIHttpChannel
] .getService(Components.interfaces.nsIIOService); var ch = ios.newChannel("https://www.example.com/", null, null); Method overview void getOriginalResponseHeader(in ACString aHeader, in nsIHttpHeaderVisitor aVisitor); ACString getRequestHeader(in ACString aHeader); ACString getResponseHeader(in ACString header); boolean isNoCacheResponse
(); boolean isNoStoreResponse
(); void redirectTo(in nsIURI aNewURI); void setEmptyRequestHeader(in ACString aHeader); void setReferrerWithPolicy(in nsIURI referrer, in unsigned long referrerPolicy); void setRequestHeader(in ACString aHeader, in ACString aValue, in boolean aMerge); void setResponseHeader(in ACString header, in ACString value, i...
...ass certain security checks (e.g., a "https://" URL will never be sent as the referrer for a plaintext HTTP request). The implementation is not required to throw an exception when the referrer URI is rejected. Exceptions thrown NS_ERROR_IN_PROGRESS If set after the channel has been opened. NS_ERROR_FAILURE If used for setting referrer during visitRequestHeaders
(). Getting the value will not throw. requestMethod ACString Set or get the HTTP request method (default is "GET"). Setter is case insensitive; getter returns an uppercase string. This attribute may only be set before the channel is opened. Note: The data for a "POST" or "PUT" request can be configured via nsIUploadChannel. However, after setting the uploa...
..., after setting the upload data, it may be necessary to set the request method explicitly. The documentation for nsIUploadChannel has further details. Exceptions thrown NS_ERROR_IN_PROGRESS If set after the channel has been opened. requestSucceeded boolean Returns true if the HTTP response code indicates success. The value of nsIRequest.status
() will be NS_OK even when processing a 404 File Not Found response because such a response may include a message body that (in some cases) should be shown to the user. Use this attribute to distinguish server error pages from normal pages, instead of comparing the response status manually against the set of valid response codes, if that is required by your application. Read only. Exceptions th...
...And 17 more matches
nsIMsgDBView
ethod overview void open(in nsIMsgFolder folder, in nsMsgViewSortTypeValue sortType, in nsMsgViewSortOrderValue sortOrder, in nsMsgViewFlagsTypeValue viewFlags, out long count); void openWithHdrs(in nsISimpleEnumerator aHeaders, in nsMsgViewSortTypeValue aSortType, in nsMsgViewSortOrderValue aSortOrder, in nsMsgViewFlagsTypeValue aViewFlags, out long aCount); void close
(); void init(in nsIMessenger aMessengerInstance, in nsIMsgWindow aMsgWindow, in nsIMsgDBViewCommandUpdater aCommandUpdater); void sort(in nsMsgViewSortTypeValue sortType, in nsMsgViewSortOrderValue sortOrder); void doCommand(in nsMsgViewCommandTypeValue command); void doCommandWithFolder(in nsMsgViewCommandTypeValue command, in nsIMsgFolder destFolder); ...
...id getURIsForSelection([array, size_is(count)] out string uris, out unsigned long count); void getIndicesForSelection([array, size_is(count)] out nsMsgViewIndex indices, out unsigned long count); void loadMessageByMsgKey(in nsMsgKey aMsgKey); void loadMessageByViewIndex(in nsMsgViewIndex aIndex); void loadMessageByUrl(in string aUrl); void reloadMessage
(); void reloadMessageWithAllParts
(); void selectMsgByKey(in nsMsgKey key); void selectFolderMsgByKey(in nsIMsgFolder aFolder, in nsMsgKey aKey); void onDeleteCompleted(in boolean succeeded); nsMsgViewIndex findIndexFromKey(in nsMsgKey aMsgKey, in boolean aExpand); void ExpandAndSelectThreadByIndex(in nsMsgViewIndex aIndex, in boolean aAugment); ...
... nsIMsgDatabase Readonly: The current database of messages. supportsThreading boolean Readonly: Does the current database support threading? searchSession nsIMsgSearchSession The current search session. removeRowOnMoveOrDelete boolean Readonly: usingLines boolean Readonly: Use lines for size. If false kB are used. Methods open
() Opens a folder in the database. void open(in nsIMsgFolder folder, in nsMsgViewSortTypeValue sortType, in nsMsgViewSortOrderValue sortOrder, in nsMsgViewFlagsTypeValue viewFlags, out long count); Parameters folder The nsIMsgFolder to open. sortType A nsMsgViewSortTypeValue designating the sort type used for the folder. Defined in the interface...
...And 17 more matches
nsIVariant
nt and JS types. We mark the interface [scriptable] so that JS can use methods that refer to this interface. But we mark all the methods and attributes [noscript] since any nsIVariant object will be automatically converted to a JS type anyway. ...
...ically converted to a JS type anyway. ...
...s Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview ACString getAsACString
(); Native code only! nsresult getAsArray(out PRUint16 type, out nsIID iid, out PRUint32 count, out voidPtr ptr); Violates the XPCOM interface guidelines AString getAsAString
(); Native code only! AUTF8String getAsAUTF8String
(); Native code only! PRBool getAsBool
(); Native code only! char getAsChar
(); Native code only! DOMString getAsDOMString
(); Native code only! double getAsDouble
(); Native code only! float getAsFloat
(); Native code only! nsresult getAsID(out nsID retval); Violates the XPCOM interface guidelines ...
...And 17 more matches
nsIXULTemplateQueryProcessor
lder and a query processor. The template builder creates the query processor, and there is no other means to retrieve it. A template query is the contents inside a <query> element within the template. The actual syntax is opaque to the template builder and defined by a query processor. The query is expected to consist of either text or DOM nodes that, when executed by a call to the generateResults
() method, will allow the generation of a list of results. The template builder will supply two variables, the reference variable and the member variable to further indicate what part of the datasource is to be examined in addition to the query itself. The reference is always a placeholder for the starting point and the member is always a placeholder for the end points (the results). The reference p...
... = ?start This query might generate a result for each bookmark within a given folder. The variable ?start would be the reference variable, while the variable ?id would be the member variable, since it is the unique value that identifies a result. ...
...r each bookmark within a given folder. The variable ?start would be the reference variable, while the variable ?id would be the member variable, since it is the unique value that identifies a result. Each result will have the four variables referred to defined for it and the values may be retrieved using the result's nsIXULTemplateResult.getBindingFor
() and nsIXULTemplateResult.getBindingObjectFor
() methods. ...
...And 17 more matches
Document - Web APIs
ointer-events: all;} The Document interface describes the common properties and methods for any kind of document. Depending on the document's type (e.g. HTML, XML, SVG, ...), a larger API is available: HTML documents, served with the "text/html" content type, also implement the HTMLDocument interface, whereas XML and SVG documents implement the XMLDocument interface. Constructor Document
() Creates a new Document object. Properties This interface also inherits from the Node and EventTarget interfaces. Document.anchorsRead only Returns a list of all of the anchors in the document. Document.body Returns the <body> or <frameset> node of the current document. Document.characterSetRead only Returns the character set being used by the document. Document.compatMode Read onl...
... true if the XML declaration specifies the document to be standalone (e.g., An external part of the DTD affects the document's content), else false. Document.xmlVersion Obsolete since Gecko 10 Returns the version number as specified in the XML declaration or "1.0" if the declaration is absent. Methods This interface also inherits from the Node and EventTarget interfaces. Document.adoptNode
() Adopt node from an external document. Document.captureEvents
() See Window.captureEvents. Document.caretRangeFromPoint
() Gets a Range object for the document fragment under the specified coordinates. Document.createAttribute
() Creates a new Attr object and returns it. Document.createAttributeNS
() Creates a new attribute node in a given namespace and returns it. Document.createCDATASe...
...pt node from an external document. Document.captureEvents
() See Window.captureEvents. Document.caretRangeFromPoint
() Gets a Range object for the document fragment under the specified coordinates. Document.createAttribute
() Creates a new Attr object and returns it. Document.createAttributeNS
() Creates a new attribute node in a given namespace and returns it. Document.createCDATASection
() Creates a new CDATA node and returns it. Document.createComment
() Creates a new comment node and returns it. Document.createDocumentFragment
() Creates a new document fragment. Document.createElement
() Creates a new element with the given tag name. ...
...And 17 more matches
Intersection Observer API - Web APIs
as you scroll, so that the user doesn't have to flip through pages. Reporting of visibility of advertisements in order to calculate ad revenues. Deciding whether or not to perform tasks or animation processes based on whether or not the user will see the result. Implementing intersection detection in the past involved event handlers and loops calling methods like Element.getBoundingClientRect
() to build up the needed information for every element affected. Since all this code runs on the main thread, even one of these can cause performance problems. When a site is loaded with these tests, things can get downright ugly. Consider a web page that uses infinite scrolling. It uses a vendor-provided library to manage the advertisements placed periodically throughout the page, has animated gr...
...other: let options = { root: document.querySelector('#scrollArea'), rootMargin: '0px', threshold: 1.0 } let observer = new IntersectionObserver(callback, options); A threshold of 1.0 means that when 100% of the target is visible within the element specified by the root option, the callback is invoked. Intersection observer options The options object passed into the IntersectionObserver
() constructor let you control the circumstances under which the observer's callback is invoked. It has the following fields: root The element that is used as the viewport for checking visibility of the target. Must be the ancestor of the target. Defaults to the browser viewport if not specified or if null. rootMargin Margin around the root. Can have values similar to the CSS margin property, ...
...ack includes one entry for each target which reporting a change in its intersection status. Check the value of the isIntersecting property to see if the entry represents an element that currently intersects with the root. Be aware that your callback is executed on the main thread. It should operate as quickly as possible; if anything time-consuming needs to be done, use Window.requestIdleCallback
(). Also, note that if you specified the root option, the target must be a descendant of the root element. How intersection is calculated All areas considered by the Intersection Observer API are rectangles; elements which are irregularly shaped are considered as occupying the smallest rectangle which encloses all of the element's parts. Similarly, if the visible portion of an element is not rect...
...And 17 more matches
Touch events - Web APIs
ger" when describing the contact with the surface, but it could, of course, also be a stylus or other contact method. Create a canvas <canvas id="canvas" width="600" height="600" style="border:solid black 1px;"> Your browser does not support canvas element. ...
... could, of course, also be a stylus or other contact method. Create a canvas <canvas id="canvas" width="600" height="600" style="border:solid black 1px;"> Your browser does not support canvas element. </canvas> <br> Log: <pre id="log" style="border: 1px solid #ccc;"></pre> Setting up the event handlers When the page loads, the startup
() function shown below will be called. ...
..., handleMove, false); } document.addEventListener("DOMContentLoaded", startup); This simply sets up all the event listeners for our <canvas> element so we can handle the touch events as they occur. Tracking new touches We'll keep track of the touches in-progress. ...
...And 17 more matches
Taking still photos with WebRTC - Web APIs
est is just some page layout fluff and a bit of text offering a link back to this page. The JavaScript code Now let's take a look at the JavaScript code. We'll break it up into a few bite-sized pieces to make it easier to explain. Initialization We start by wrapping the whole script in an anonymous function to avoid global variables, then setting up various variables we'll be using. (function
() { var width = 320; // We will scale the photo width to this var height = 0; // This will be computed based on the input stream var streaming = false; var video = null; var canvas = null; var photo = null; var startbutton = null; Those variables are: width Whatever size the incoming video is, we're going to scale the resulting image to be 320 pixels wide. height The o...
...e a reference to the <video> element after the page is done loading. canvas This will be a reference to the <canvas> element after the page is done loading. photo This will be a reference to the <img> element after the page is done loading. startbutton This will be a reference to the <button> element that's used to trigger capture. We'll get that after the page is done loading. The startup
() function The startup
() function is run when the page has finished loading, courtesy of window.addEventListener
(). This function's job is to request access to the user's webcam, initialize the output <img> to a default state, and to establish the event listeners needed to receive each frame of video from the camera and react when the button is clicked to capture an image. Getting element referen...
...ntListener
(). This function's job is to request access to the user's webcam, initialize the output <img> to a default state, and to establish the event listeners needed to receive each frame of video from the camera and react when the button is clicked to capture an image. Getting element references First, we grab references to the major elements we need to be able to access. ...
...And 17 more matches
shape-outside - CSS: Cascading Style Sheets
ve 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. ...
...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. ...
...he shape enclosed by the outside padding edge. The shape follows the normal border radius shaping rules for the inside of the border. content-box Defines the shape enclosed by the outside content edge. Each corner radius of this box is the larger of 0 or border-radius - border-width - padding. <basic-shape> The float area is computed based on the shape created by of one of inset
(), circle
(), ellipse
(), polygon
(), or as added in the level 2 specification path
(). If a <shape-box> is also supplied, it defines the reference box for the <basic-shape> function. Otherwise, the reference box defaults to margin-box. <image> The float area is extracted and computed based on the alpha channel of the specified <image> as defined by shape-image-threshold. Note: User agents must u...
...And 17 more matches
Audio and video manipulation - Developer guides
ue" width="480" height="270" crossorigin="anonymous"> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type="video/webm"> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <canvas id="my-canvas" width="480" height="270"></canvas> JavaScript This code handles altering the frames. ...
...com/samples/5b/8cd6da9c65.webm" type="video/webm"> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <canvas id="my-canvas" width="480" height="270"></canvas> JavaScript This code handles altering the frames. ...
...> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <canvas id="my-canvas" width="480" height="270"></canvas> JavaScript This code handles altering the frames. ...
...And 17 more matches
Iterators and generators - JavaScript
<< PreviousNext >> Processing each of the items in a collection is a very common operation. JavaScript provides a number of ways of iterating over a collection, from simple for loops to map
() and filter
(). Iterators and Generators bring the concept of iteration directly into the core language and provide a mechanism for customizing the behavior of for...of loops. ...
...e and provide a mechanism for customizing the behavior of for...of loops. For details, see also: Iteration_protocols for...of function* and Generator yield and yield* Iterators In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination. Specifically, an iterator is any object which implements the Iterator protocol by having a next
() method that returns an object with two properties: value The next value in the iteration sequence. done This is true if the last value in the sequence has already been consumed. If value is present alongside done, it is the iterator's return value. Once created, an iterator object can be iterated explicitly by repeatedly calling next
(). Iterating over an iterator is said to consume the it...
... The most common iterator in JavaScript is the Array iterator, which simply returns each value in the associated array in sequence. ...
...And 17 more matches
/loader - Archive of obsolete content
oader'); What is it good for ? Create somewhat standardized JS environments that people doing non-browser JS are familiar with. Provide an environment for loading CommonJS style modules, which makes it possible to consume lots of interesting code that has already been developed. ...
...ible to consume lots of interesting code that has already been developed. Secure each module in an isolated JS sandbox and makes any capability imports explicit via calls to the require
() function. create task specific loaders with restricted module access. Provide unload hooks that may be used to undo changes made by anything loaded into it. Instantiation The loader module provides a Loader
() function that may be used to instantiate new loader instances: let loader = Loader(options); Configuration Loader
() may be provided with a set of configuration options: paths: describes where the loader should find the modules it is asked to load. Mandatory. modules: provides a set of module exports. Optional. globals: provides a set of globals shared across modules loaded via this loader...
...ndatory. modules: provides a set of module exports. Optional. globals: provides a set of globals shared across modules loaded via this loader. Optional. resolve: provide customized module resolution logic. Optional. id: provide add-on id to attach to loaded modules. Optional. paths The loader needs to be provided with a set of locations to indicate where to find modules loaded using require
(). This is provided by a mandatory options.paths hash that represents the mapping between module ID prefixes and locations. There are lots of different possibilities, but the most common setup looks like this: let { Loader } = require('toolkit/loader'); let loader = Loader({ paths: { // Resolve all modules starting with `toolkit/` as follows: // toolkit/foo -> resource://gre/module...
...And 16 more matches
browser - Archive of obsolete content
st of its methods are callable directly on the element itself, such as goBack and goForward. It also contains the load constants used by reloadWithFlags and loadURIWithFlags. webProgress Type: nsIWebProgress This read-only property contains an nsIWebProgress object which is used to monitor the progress of a document loading. ...
...ds are callable directly on the element itself, such as goBack and goForward. It also contains the load constants used by reloadWithFlags and loadURIWithFlags. webProgress Type: nsIWebProgress This read-only property contains an nsIWebProgress object which is used to monitor the progress of a document loading. ...
...n the element itself, such as goBack and goForward. It also contains the load constants used by reloadWithFlags and loadURIWithFlags. webProgress Type: nsIWebProgress This read-only property contains an nsIWebProgress object which is used to monitor the progress of a document loading. ...
...And 16 more matches
tree - Archive of obsolete content
assign an object which implements nsITreeView to this property. Trees built from RDF or those which use treeitems directly will already have a view. Functions available in the view allow one to retrieve the data within the cells, and determine which rows are nested within others. For a complete list of view functions, see the nsITreeView interface. ...
...t which implements nsITreeView to this property. Trees built from RDF or those which use treeitems directly will already have a view. Functions available in the view allow one to retrieve the data within the cells, and determine which rows are nested within others. For a complete list of view functions, see the nsITreeView interface. ...
...View to this property. Trees built from RDF or those which use treeitems directly will already have a view. Functions available in the view allow one to retrieve the data within the cells, and determine which rows are nested within others. For a complete list of view functions, see the nsITreeView interface. ...
...And 16 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
Listing 1 - Querying a mySQL database from Rhino // import the java sql packages importPackage( java.sql ); // load the mySQL driver java.lang.Class.forName( "com.mysql.jdbc.Driver" ); // create connection to the database var conn = DriverManager.getConnection( "jdbc:mysql://localhost/rhino", "uRhino", "pRhino" ); // create a statement handle var stmt = conn.createStatement
(); // get a resultset var rs = stmt.executeQuery( "select * from employee" ); // get the metadata from the resultset var meta = rs.getMetaData
(); // loop over the records, dump out column names and values while( rs.next
() ) { for( var i = 1; i <= meta.getColumnCount
(); i++ ) { print( meta.getColumnName( i ) + ": " + rs.getObject( i ) + "\n" ); } print( "----------\n" ); } // cleanup rs.cl...
...Here, we're including all the classes in the java.sql namespace in the script. ...
...Here, we're including all the classes in the java.sql namespace in the script. ...
...And 16 more matches
Looping code - Learn web development
/canvas> <script> const btn = document.querySelector('button'); const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); let WIDTH = document.documentElement.clientWidth; let HEIGHT = document.documentElement.clientHeight; canvas.width = WIDTH; canvas.height = HEIGHT; function random(number) { return Math.floor(Math.random
()*number); } function draw
() { ctx.clearRect(0,0,WIDTH,HEIGHT); for (let i = 0; i < 100; i++) { ctx.beginPath
(); ctx.fillStyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI); ctx.fill
(); } } btn.addEventListener('click',draw); </script> </body> </html> You don't have to underst...
...tx.fillStyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI); ctx.fill
(); } } btn.addEventListener('click',draw); </script> </body> </html> You don't have to understand all the code for now, but let's look at the part of the code that actually draws the 100 circles: for (let i = 0; i < 100; i++) { ctx.beginPath
(); ctx.fillStyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI); ctx.fill
(); } random(x), defined earlier in the code, returns a whole number between 0 and x-1. WIDTH and HEIGHT are the width and height of the inner browser window. You should get the basic idea -- we are using a loop to run 100 iterations of this code, each one of which draws ...
...ld get the basic idea -- we are using a loop to run 100 iterations of this code, each one of which draws a circle in a random position on the page. The amount of code needed would be the same whether we were drawing 100 circles, 1000, or 10,000. Only one number has to change. If we weren't using a loop here, we'd have to repeat the following code for every circle we wanted to draw: ctx.beginPath
(); ctx.fillStyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI); ctx.fill
(); This would get very boring and difficult to maintain very quickly. Loops really are the best. The standard for loop Let's start exploring some specific loop constructs. The first, which you'll use most of the time, is the for loop -- this has the following syntax: for (initial...
...And 16 more matches
Object-oriented JavaScript for beginners - Learn web development
g object instances from them in JavaScript. First of all, we'd like you to make a new local copy of the oojs.html file we saw in our first Objects article. A simple example Let's start by looking at how you could define a person with a normal function. ...
... this function within the script element: function createNewPerson(name) { const obj = {}; obj.name = name; obj.greeting = function
() { alert('Hi! I\'m ' + obj.name + '.'); }; return obj; } You can now create a new person by calling this function -- try the following lines in your browser's JavaScript console: const salva = createNewPerson('Salva'); salva.name; salva.greeting
(); This works well enough, but it is a bit long-winded; if we know we want to create an object, why do we need to explicitly create a new empty object and return it? Fortunately, JavaScript provides us with a handy shortcut, in the form of constructor functions -- let's make one now! Replace your previous function with the following: function Person(name) { this.name = name; this.greeting ...
...Notice that it has all the features you'd expect in a function, although it doesn't return anything or explicitly create an object -- it basically just defines properties and methods. Notice also the this keyword being used here as well -- it is basically saying that whenever one of...
...And 16 more matches
Componentizing our Svelte app - Learn web development
ponents/FilterButton.svelte. Inside this file we will declare a filter prop, and then copy the relevant markup over to it from Todos.svelte. ...
... stack-exception"> <button class="btn toggle-btn" class:btn__primary={filter === 'all'} aria-pressed={filter === 'all'} on:click={
()=> filter = 'all'} > <span class="visually-hidden">Show</span> <span>All</span> <span class="visually-hidden">tasks</span> </button> <button class="btn toggle-btn" class:btn__primary={filter === 'active'} aria-pressed={filter === 'active'} on:click={
()=> filter = 'active'} > <span class="visually-hidden">Show</span> <span>Active</span> <span class="visually-hidden">tasks</span> </button> <button class="btn toggle-btn" class:btn__primary={filter === 'completed'} aria-pressed={filter === 'completed'} on:click={
()=> filter = 'completed'} > <span class="visually-hidden">Show</span> <span>Completed</span> <span class="vis...
...om the Todos component. Just for now, we'll replace the call to removeTodo with an alert. We'll add that functionality back in later on. Create a new component file -- components/Todo.svelte. ...
...And 16 more matches
Focus management with Vue refs - Learn web development
a ref to our "Edit" Button in ToDoItem.vue. Update it like this: <button type="button" class="btn" ref="editButton" @click="toggleToItemEditForm"> Edit <span class="visually-hidden">{{label}}</span> </button> To access the value associated with our ref, we use the $refs property provided on our component instance. To see the value of the ref when we click our "Edit" button, add a console.log
() to our toggleToItemEditForm
() method, like so: toggleToItemEditForm
() { console.log(this.$refs.editButton); this.isEditing = true; } If you activate the "Edit" Button at this point, you should see an HTML <button> element referenced in your console. Vue's $nextTick
() method We want to set focus on the "Edit" Button when a user saves or cancels their edit. To do that, we need to handle foc...
...ke so: toggleToItemEditForm
() { console.log(this.$refs.editButton); this.isEditing = true; } If you activate the "Edit" Button at this point, you should see an HTML <button> element referenced in your console. Vue's $nextTick
() method We want to set focus on the "Edit" Button when a user saves or cancels their edit. To do that, we need to handle focus in the ToDoItem component's itemEdited
() and editCancelled
() methods. For convenience, create a new method which takes no arguments called focusOnEditButton
(). Inside it, assign your ref to a variable, and then call the focus
() method on the ref. ...
...Tick
() method We want to set focus on the "Edit" Button when a user saves or cancels their edit. To do that, we need to handle focus in the ToDoItem component's itemEdited
() and editCancelled
() methods. For convenience, create a new method which takes no arguments called focusOnEditButton
(). Inside it, assign your ref to a variable, and then call the focus
() method on the ref. ...
...And 16 more matches
Mozilla accessibility architecture
similar. The problem is, what happens if there are DOM nodes that the assistive technology vendors wants to know about, which are not exposed? Also, what if they want to get DOM information, like CSS rules, tag names and attributes, that MSAA's IAccessible does not provide? On Windows, we solve this by supporting an additional interface beyond MSAA's IAccesible, for every DOM node. QueryInterface
() can be used to switch between the two interfaces. If there is no MSAA node for a DOM node, pAccessible->QueryInterface(IID_IAccessible) will return null. In addition, some vendors had asked us to provide information and support for pieces of text smaller than a text node (i.e. a word), and Mozilla supports ISimpleDOMText for this purpose. On ATK there is no such interface to get actual DOM inform...
...wever, because this would have caused a lot of difficulty when implementing the accessibility cache, the code was moved in to the "Wrap" classes in a source directory specific to each toolkit. Classes with "Wrap" in the name, such as nsTextAccessibleWrap and nsDocAccessibleWrap, inherit from cross-platform classes of similar name without "Wrap" in them. They may override some methods, such as Init
() and Shutdown
(), and add other methods to support interfaces needed only by the given toolkit. For example, nsAccessibleWrap implements the methods in IAccessible, but because it is also an nsAccessible, it only needs to call the nsIAccessible methods in "this" to get at the information it needs. Class Inheritence Diagram View the Class Inheritence Diagram. 3. Accessible Tree Construction and Trav...
...t the accessible at a given point on the screen. No matter how the assistive technology client requests the data, the accessible for a given node is only created once. We use the accessibility cache to retrieve accessibles that have already been created for a given dom node. This tree traversal is accomplished via toolkit-specific calls which end up as calls into nsIAccessible methods GetAccParent
(), GetAccNextSibling
(), GetAccPreviousSibling
(), GetAccFirstChild
(), GetAccLastChild
(), GetAccChildCount
() and GetChildAt(childNum). The ATK has more convenience methods than MSAA does for traversal - for example it is possible to go straight to the accessible for a specific row and column of a table, using nsIAccessibleTable::CellRefAt
(). The algorithm used to calculate the number of accessible ch...
...And 16 more matches
AddonManager
nFile(in nsIFile aFile, in string aPath) Properties Overview Attribute Type Description addonTypes dictionary A dictionary that maps type ID to AddonType. autoUpdateDefault boolean Whether add-ons should auto-update by default (overrideable per add-on). Corresponds to the extensions.autoUpdateDefault preference. ...
...pdateDefault boolean Whether add-ons should auto-update by default (overrideable per add-on). Corresponds to the extensions.autoUpdateDefault preference. Callbacks InstallCallback
() A callback that is passed a single AddonInstall void InstallCallback( in AddonInstall install ) Parameters install The AddonInstall passed back from the asynchronous request InstallListCallback
() A callback that is passed an array of AddonInstalls void InstallListCallback( in AddonInstall installs[] ) Parameters installs The array of AddonInstalls passed back from the asynchronous request AddonCallback
() A callback that is passed a single Addon void AddonCallback( in Addon addon ) Parameters addon The Addon passed back from the asynchronous request. If an error occurre...
...ddonInstall installs[] ) Parameters installs The array of AddonInstalls passed back from the asynchronous request AddonCallback
() A callback that is passed a single Addon void AddonCallback( in Addon addon ) Parameters addon The Addon passed back from the asynchronous request. If an error occurred (such as an add-on not being found), null is passed back instead. AddonListCallback
() A callback that is passed an array of Addons void AddonListCallback( in Addon addons[] ) Parameters addons The array of Addons passed back from the asynchronous request Constants AddonInstall states Constant Description STATE_AVAILABLE An install that is waiting to be started. STATE_DOWNLOADING An install that is in the process of being downloaded.
...And 16 more matches
nsIDOMEvent
efox 16.0 / Thunderbird 16.0 / SeaMonkey 2.13) Note: As of Gecko 16.0, the nsIPrivateDOMEvent interface was merged into this interface. Everything marked as Gecko 16.0 was previously available in that interface. See bug 761613. ...
...Gecko 16.0, the nsIPrivateDOMEvent interface was merged into this interface. Everything marked as Gecko 16.0 was previously available in that interface. See bug 761613. ...
...erything marked as Gecko 16.0 was previously available in that interface. See bug 761613. ...
...And 16 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
(). ...
...stance, 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
(). ...
...e = value; searchTerm.op = searchSession.BooleanOR; searchTerm.booleanAnd = false; searchSession.appendTerm(searchTerm); searchSession.search(null); Inherits from: nsISupports Method overview void addSearchTerm(in nsMsgSearchAttribValue attrib, in nsMsgSearchOpValue op, in nsIMsgSearchValue value, in boolean BooleanAND, in string arbitraryHeader); nsIMsgSearchTerm createTerm
(); void appendTerm(in nsIMsgSearchTerm term); void registerListener(in nsIMsgSearchNotify listener); void unregisterListener(in nsIMsgSearchNotify listener); void getNthSearchTerm(in long whichTerm, in nsMsgSearchAttribValue attrib, in nsMsgSearchOpValue op, in nsIMsgSearchValue value); long countSearchScopes
(); void getNthSearchScope(in long wh...
...And 16 more matches
nsIZipWriter
er.idlScriptable This interface provides an easy way for scripts to archive data in the Zip file format. Operations on the archive can be performed one by one, or queued for later execution. 1.0 66 Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) Once all the operations you wish to perform are added to the queue, a call to processQueue
() will perform the operations in the order they were added to the queue. Operations performed on the queue throw any errors that occur out to the observer. Attempting to perform a synchronous operation on the interface while the background queue is in progress will throw an NS_ERROR_IN_PROGRESS exception. File and directory names should use slashes ("/") as separators and should not begin with a ...
...in boolean aQueue); void addEntryDirectory(in AUTF8String aZipEntry, in PRTime aModTime, in boolean aQueue); void addEntryFile(in AUTF8String aZipEntry, in PRInt32 aCompression, in nsIFile aFile, in boolean aQueue); void addEntryStream(in AUTF8String aZipEntry, in PRTime aModTime, in PRInt32 aCompression, in nsIInputStream aStream, in boolean aQueue); void close
(); nsIZipEntry getEntry(in AUTF8String aZipEntry); boolean hasEntry(in AUTF8String aZipEntry); void open(in nsIFile aFile, in PRInt32 aIoFlags); void processQueue(in nsIRequestObserver aObserver, in nsISupports aContext); void removeEntry(in AUTF8String aZipEntry, in boolean aQueue); Attributes Attribute Type Description c...
...PRESSION_NONE 0 Do not compress the file. COMPRESSION_FASTEST 1 Use the fastest compression method when adding the file to the archive. COMPRESSION_DEFAULT 6 Use the default compression method when adding the file to the archive. COMPRESSION_BEST 9 Use the best compression method when adding the file to the archive. Methods addEntryChannel
() Adds data from a channel to the Zip file. If the operation is performed on the queue then the channel will be opened asynchronously, otherwise the channel must support being opened synchronously. void addEntryChannel( in AUTF8String aZipEntry, in PRTime aModTime, in PRInt32 aCompression, in nsIChannel aChannel, in boolean aQueue ); Parameters aZipEntry The path of the file entry...
...And 16 more matches
Xray vision
ss content objects can be a security risk for chrome code. JavaScript's a highly malleable language. Scripts running in web pages can add extra properties to DOM objects (also known as expando properties) and even redefine standard DOM objects to do something unexpected. If chrome code relies on such modified objects, it can be tricked into doing things it shouldn't. For example: window.confirm
() is a DOM API that's supposed to ask the user to confirm an action, and return a boolean depending on whether they clicked "OK" or "Cancel". A web page could redefine it to return true: window.confirm = function
() { return true; } Any privileged code calling this function and expecting its result to represent user confirmation would be deceived. This would be very naive, of course, but there a...
...curity problems. This is the problem that Xray vision is designed to solve. When a script accesses an object using Xray vision it sees only the native version of the object. Any expandos are invisible, and if any properties of the object have been redefined, it sees the original implementation, not the redefined version. So in the example above, chrome code calling the content's window.confirm
() would get the original version of confirm
(), not the redefined version. It's worth emphasizing that even if content tricks chrome into running some unexpected code, that code does not run with chrome privileges. So this is not a straightforward privilege escalation attack, although it might lead to one if the chrome code is sufficiently confused. How you get Xray vision Privileged code autom...
...de is sufficiently confused. How you get Xray vision Privileged code automatically gets Xray vision whenever it accesses objects belonging to less-privileged code. So when chrome code accesses content objects, it sees them with Xray vision: // chrome code var transfer = gBrowser.contentWindow.confirm("Transfer all my money?"); // calls the native implementation Note that using window.confirm
() would be a terrible way to implement a security policy, and is only shown here to illustrate how Xray vision works. Waiving Xray vision Xray vision is a kind of security heuristic, designed to make most common operations on untrusted objects simple and safe. However, there are some operations for which they are too restrictive: for example, if you need to see expandos on DOM objects. In cases ...
...And 16 more matches
Starting up and shutting down a WebXR session - Web APIs
ion is the WebXR polyfill, provided by the Immersive Web Working Group that's in charge of the WebXR standardization process. The polyfill brings support for WebXR to browsers that don't have native WebXR support, and smooths out the inconsistencies among implementations in the browsers that do have it, so it can sometimes also be useful even if WebXR is natively available. ...
.... Here we define a getXR
() function, which returns the XRSystem object after optionally installing the polyfill, assuming that the polyfill has been included or loaded using a prior <script> tag. ...
...ill, assuming that the polyfill has been included or loaded using a prior <script> tag. ...
...And 16 more matches
Example and tutorial: Simple synth keyboard - Web APIs
span, .left input { vertical-align: middle; } .right { width: 50%; position: absolute; right: 0; display: table-cell; vertical-align: middle; } .right span { vertical-align: middle; } .right input { vertical-align: baseline; } JavaScript The JavaScript code begins by initializing a number of variables. let audioContext = new (window.AudioContext || window.webkitAudioContext)
(); let oscList = []; let masterGainNode = null; audioContext is set to reference the global AudioContext object (or webkitAudioContext if necessary). oscList is set up to be ready to contain a list of all currently-playing oscillators. It starts off empty, since there are none playing yet. masterGainNode is set to null; during the setup process, it will be configured to contain a GainNode whi...
... each is the frequency, in Hertz, of the note's tone. customWaveform will be set up as a PeriodicWave describing the waveform to use when the user selects "Custom" from the waveform picker. sineTerms and cosineTerms will be used to store the data for generating the waveform; each will contain an array that's generated when the user chooses "Custom". ...
...the user chooses "Custom". Creating the note table The createNoteTable
() function builds the array noteFreq to contain an array of objects representing each octave. Each octave, in turn, has one named property for each note in that octave; the property's name is the note's name (such as "C#" to represent C-sharp), and the value is the frequency, in Hertz, of that note. ...
...And 16 more matches
Border-radius generator - CSS: Cascading Style Sheets
radius: 3px; } #output { width: 500px; padding: 10px 0; margin: 10px 0; color: #555; text-align: center; border: 1px dashed #999; border-radius: 3px; -moz-user-select: text; -webkit-user-select: text; -ms-user-select: text; user-select: text; float: right; } JavaScript Content 'use strict'; /** * UI-InputSliderManager */ var InputSliderManager = (function InputSliderManager
() { var subscribers = {}; var sliders = []; var InputComponent = function InputComponent(obj) { var input = document.createElement('input'); input.setAttribute('type', 'text'); input.addEventListener('click', function(e) { this.select
(); }); input.addEventListener('change', function(e) { var value = parseInt(e.target.value); if (isNaN(value) === true) setValue(obj.top...
...e = function getNode(topic) { return sliders[topic].node; } var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexOf(callback); subscribers[topic].splice(index, 1); } var notify = function notify
() { for (var i in subscribers[this.topic]) { subscribers[this.topic][i](this.value); } } var init = function init
() { var elem = document.querySelectorAll('.ui-input-slider'); var size = elem.length; for (var i = 0; i < size; i++) new InputSlider(elem[i]); } return { init : init, setMax : setMax, setMin : setMin, setUnit : setUnit, getNode : getNode, setValue : set...
...topic][i](this.value); } } var init = function init
() { var elem = document.querySelectorAll('.ui-input-slider'); var size = elem.length; for (var i = 0; i < size; i++) new InputSlider(elem[i]); } return { init : init, setMax : setMax, setMin : setMin, setUnit : setUnit, getNode : getNode, setValue : setValue, subscribe : subscribe, unsubscribe : unsubscribe } })
(); /** * UI-ButtonManager */ var ButtonManager = (function CheckBoxManager
() { var subscribers = []; var buttons = []; var CheckBox = function CheckBox(node) { var topic = node.getAttribute('data-topic'); var state = node.getAttribute('data-state'); var name = node.getAttribute('data-label'); var align = node.getAttribute('data-text-on'); state = (state === "true"); var check...
...And 16 more matches
Meta programming - JavaScript
in unchanged when implementing custom operations are called invariants. If you violate the invariants of a handler, a TypeError will be thrown. Handlers and traps The following table summarizes the available traps available to Proxy objects. See the reference pages for detailed explanations and examples. ...
...ing custom operations are called invariants. If you violate the invariants of a handler, a TypeError will be thrown. Handlers and traps The following table summarizes the available traps available to Proxy objects. See the reference pages for detailed explanations and examples. ...
...led invariants. If you violate the invariants of a handler, a TypeError will be thrown. Handlers and traps The following table summarizes the available traps available to Proxy objects. See the reference pages for detailed explanations and examples. ...
...And 16 more matches
Working with objects - JavaScript
access the properties of an object with a simple dot-notation: objectName.propertyName Like all JavaScript variables, both the object name (which could be a normal variable) and property name are case sensitive. You can define a property by assigning it a value. ...
...rty name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime). ...
...tarts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime). ...
...And 16 more matches
Using the WebAssembly JavaScript API - WebAssembly
ed into the wasm module. Create a <script></script> element in your HTML file, and add the following code to it: var importObject = { imports: { imported_func: arg => console.log(arg) } }; Streaming the WebAssembly module New in Firefox 58 is the ability to compile and instantiate WebAssembly modules directly from underlying sources. ...
...pt></script> element in your HTML file, and add the following code to it: var importObject = { imports: { imported_func: arg => console.log(arg) } }; Streaming the WebAssembly module New in Firefox 58 is the ability to compile and instantiate WebAssembly modules directly from underlying sources. This is achieved using the WebAssembly.compileStreaming
() and WebAssembly.instantiateStreaming
() methods. ...
...Streaming
() and WebAssembly.instantiateStreaming
() methods. These methods are easier than their non-streaming counterparts, because they can turn the byte code directly into Module/Instance instances, cutting out the need to separately put the Response into an ArrayBuffer. This example (see our instantiate-streaming.html demo on GitHub, and view it live also) shows how to use instantiateStreaming
() to fetch a wasm module, import a JavaScript function into it, compile and instantiate it, and access its exported function -- all in one step. ...
...And 16 more matches
core/promise - Archive of obsolete content
unction blackbox(a, b) { var c = assemble(a); return combine(b, c); } We're forced into continuation passing style, involving lots of machinery: function sphagetti(a, b, callback) { assemble(a, function continueWith(error, c) { if (error) callback(error); else combine(b, c, callback); }); } This style also makes doing things in sequence hard: widget.on('click', function onClick
() { promptUserForTwitterHandle(function continueWith(error, handle) { if (error) return ui.displayError(error); twitter.getTweetsFor(handle, funtion continueWith(error, tweets) { if (error) return ui.displayError(error); ui.showTweets(tweets); }); }); }); Doing things in parallel is even harder: var tweets, answers, checkins; twitter.getTweetsFor(user, function continu...
...error, handle) { if (error) return ui.displayError(error); twitter.getTweetsFor(handle, funtion continueWith(error, tweets) { if (error) return ui.displayError(error); ui.showTweets(tweets); }); }); }); Doing things in parallel is even harder: var tweets, answers, checkins; twitter.getTweetsFor(user, function continueWith(result) { tweets = result; somethingFinished
(); }); stackOverflow.getAnswersFor(question, function continueWith(result) { answers = result; somethingFinished
(); }); fourSquare.getCheckinsBy(user, function continueWith(result) { checkins=result; somethingFinished
(); }); var finished = 0; function somethingFinished
() { if (++finished === 3) ui.show(tweets, answers, checkins); } This also makes error handling quite an adventure...
...e either its fulfillment or rejection. If the promise is rejected and the rejection is not explicitly observed, any derived promises will be implicitly rejected for the same reason. In the Add-on SDK we follow CommonJS Promises/A specification and model a promise as an object with a then method, which can be used to get the eventual return (fulfillment) value or thrown exception (rejection): foo
().then(function success(value) { // ... }, function failure(reason) { // ... }); If foo returns a promise that gets fulfilled with the value, success callback (the value handler) will be called with that value. However, if the returned promise gets rejected, the failure callback (the error handler) will be called with the reason of an error. Propagation The then method of a promise returns a...
...And 15 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
...value of the type attribute. userAction Type: string Gets and sets the value of the userAction attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...pe attribute. userAction Type: string Gets and sets the value of the userAction attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...And 15 more matches
Using the Editor from XUL - Archive of obsolete content
et's trace through the process of editor creation when bringing up the composer window. You can find the relevant XUL parts in editor.xul, the JavaScript parts in editor.js, and the XBL binding for the editor element in editor.xml. Something, somewhere, tells Mozilla to open the composer window. editor.xul is loaded. In editor.xul, the <window> tag has an onload handler: onload="EditorOnLoad
()". That causes the EditorOnLoad
() JavaScript function to get executed when the XUL is done loading. The XUL contains an <editor> tag, e.g.: <editor type="content-primary" id="content-frame" src="about:blank" flex="1"/> The attribute type="content-primary" identifies this as the window content element, i.e. that which you get from window._content. Having an id attribute, id="content-frame"...
...editor> tag, e.g.: <editor type="content-primary" id="content-frame" src="about:blank" flex="1"/> The attribute type="content-primary" identifies this as the window content element, i.e. that which you get from window._content. Having an id attribute, id="content-frame", allows us to find this element with document.getElementById("content-frame"), and to style it from CSS. EditorOnLoad
() is called. It does some getting of window.arguments (which is a way callers can pass parameters to new windows -- we use this to get the URL to be loaded), then it calls EditorStartup
(), where the real work happens. It passes two parameters; the first indicates whether we want a plain text or HTML editor (pass text or html here), and the second is the <iframe> element on which we wish to creat...
...The <editor> tag actually creates an nsEditorBoxObject behind the scenes. The nsEditorBoxObject creates an nsEditorShell, and holds the owning reference to it. ...
...And 15 more matches
notificationbox - Archive of obsolete content
Firefox windows. The notification box is a vertical box which may have children. The notifications appear at the top of the box. The notifications may be placed at the bottom by setting the dir attribute to reverse. Finding the current notification box Within a Firefox extension, you can retrieve the current notification box for a specific tab by calling the global function getNotificationBox
(): notifyBox = chromeWin.getNotificationBox(notifyWindow) notifyBox = getNotificationBox(notifyWindow) // applies to current context's window object Here, chromeWin is the XUL window (usually just window), and notifyWindow is the web content window for the tab you want to find the notification box for. Also it is possible to call function with the same name (they are different) of global object...
...indow) notifyBox = getNotificationBox(notifyWindow) // applies to current context's window object Here, chromeWin is the XUL window (usually just window), and notifyWindow is the web content window for the tab you want to find the notification box for. Also it is possible to call function with the same name (they are different) of global object gBrowser: notifyBox = gBrowser.getNotificationBox
() Examples <notificationbox flex="1"> <browser src="http://www.mozilla.org"/> </notificationbox> There is a more complex code available in the Code Snippets area. Properties currentNotification, allNotifications, notificationsHidden Methods appendNotification, getNotificationWithValue, removeAllNotifications, removeCurrentNotification, removeNotification, removeTransientNot...
...fications Type: nodeList NodeList of all notifications. This property is read-only. notificationsHidden Type: boolean Indicating whether the notification area should be hidden. Events AlertActive Type: Event Fired when a notification element is shown. AlertClose Type: Event Fired when a notification element is closed. ...
...And 15 more matches
wizard - Archive of obsolete content
onLastPage, pageCount, pageIndex, pageStep, title, wizardPages Methods advance, cancel, extra1, extra2, getButton, getPageById, goTo, rewind Examples <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <wizard id="theWizard" title="Secret Code Wizard" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function checkCode
(){ document.getElementById('theWizard').canAdvance = (document.getElementById('secretCode').value == "cabbage"); } </script> <wizardpage onpageshow="checkCode
();"> <label value="Enter the secret code:"/> <textbox id="secretCode" onkeyup="checkCode
();"/> </wizardpage> <wizardpage> <label value="That is the correct secret code."/> </wizardpage> </wizard> Attributes ...
...dex, because pages are not necessarily navigated in order. title Type: string The title that appears at the top of the wizard. This is overridden by the label attribute on the individual pages. wizardPages Type: DOM NodeList of wizardpage elements This property holds the list of wizardpage elements in the wizard. ...
...ges are not necessarily navigated in order. title Type: string The title that appears at the top of the wizard. This is overridden by the label attribute on the individual pages. wizardPages Type: DOM NodeList of wizardpage elements This property holds the list of wizardpage elements in the wizard. ...
...And 15 more matches
ECMAScript 2015 support in Mozilla - Archive of obsolete content
s a standard on June 17, 2015 by the ECMA General Assembly. It will also appear as the international industry standard ISO/IEC 16262:2016. A PDF and HTML version of the standard can be freely downloaded on ecma-international.org. A channel for feedback on ECMAScript standards is es-discuss. ...
...2015 by the ECMA General Assembly. It will also appear as the international industry standard ISO/IEC 16262:2016. A PDF and HTML version of the standard can be freely downloaded on ecma-international.org. A channel for feedback on ECMAScript standards is es-discuss. ...
... will also appear as the international industry standard ISO/IEC 16262:2016. A PDF and HTML version of the standard can be freely downloaded on ecma-international.org. A channel for feedback on ECMAScript standards is es-discuss. ...
...And 15 more matches
Move the ball - Game development
f movement -- just like how movement works with the movies. Defining a drawing loop To keep constantly updating the canvas drawing on each frame, we need to define a drawing function that will run over and over again, with a different set of variable values each time to change sprite positions, etc. ...
... movement works with the movies. Defining a drawing loop To keep constantly updating the canvas drawing on each frame, we need to define a drawing function that will run over and over again, with a different set of variable values each time to change sprite positions, etc. You can run a function over and over again using a JavaScript timing function such as setInterval
() or requestAnimationFrame
(). ...
...ng function that will run over and over again, with a different set of variable values each time to change sprite positions, etc. You can run a function over and over again using a JavaScript timing function such as setInterval
() or requestAnimationFrame
(). Delete all the JavaScript you currently have inside your HTML file except for the first two lines, and add the following below them. ...
...And 15 more matches
Function return values - Learn web development
lues that a function returns when it has completed. You've already met return values a number of times, although you may not have thought about them explicitly. Let's return to a familiar example (from a previous article in this series): let myText = 'The weather is cold'; let newString = myText.replace('cold', 'warm'); console.log(newString); // Should print "The weather is warm" // the replace
() string function takes a string, // replaces one substring with another, and returns // a new string with the replacement made The replace
() function is invoked on the myText string, and is passed two parameters: the substring to find ('cold'). the string to replace it with ('warm'). When the function completes (finishes running), it returns a value, which is a new string with the replaceme...
...ade The replace
() function is invoked on the myText string, and is passed two parameters: the substring to find ('cold'). the string to replace it with ('warm'). When the function completes (finishes running), it returns a value, which is a new string with the replacement made. In the code above, the result of this return value is saved in the variable newString. If you look at the replace
() function MDN reference page, you'll see a section called return value. It is very useful to know and understand what values are returned by functions, so we try to include this information wherever possible. Some functions don't return any value. ...
...It just makes a box appear somewhere on the screen -- that's it! Generally, a return value is used where the function is an intermediate step in a calculation of some kind. ...
...And 15 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
oggling and removing todos Let's add some functionality to toggle the task status. Svelte has the on:eventname directive for listening to DOM events. Let's add a handler to the on:click event of the checkbox input to toggle the completed value. Update the <input type="checkbox"> element inside src/components/Todos.svelte as follows: <input type="checkbox" id="todo-{todo.id}" on:click={
() => todo.completed = !todo.completed} checked={todo.completed} /> Next we'll add a function to remove a todo from our todos array. At the bottom of the Todos.svelte <script> section, add the removeTodo
() function like so: function removeTodo(todo) { todos = todos.filter(t => t.id !== todo.id) } We'll call it via the Delete button. Update it with a click event, like so: <butto...
...o.completed} /> Next we'll add a function to remove a todo from our todos array. At the bottom of the Todos.svelte <script> section, add the removeTodo
() function like so: function removeTodo(todo) { todos = todos.filter(t => t.id !== todo.id) } We'll call it via the Delete button. Update it with a click event, like so: <button type="button" class="btn btn__danger" on:click={
() => removeTodo(todo)} > Delete <span class="visually-hidden">{todo.name}</span> </button> A very common mistake with handlers in Svelte is to pass the result of executing a function as a handler, instead of passing the function. For example, if you specify on:click={removeTodo(todo)}, it will execute removeTodo(todo) and the result will be passed as a handler, which is not what we had in mind...
...sually-hidden">{todo.name}</span> </button> A very common mistake with handlers in Svelte is to pass the result of executing a function as a handler, instead of passing the function. For example, if you specify on:click={removeTodo(todo)}, it will execute removeTodo(todo) and the result will be passed as a handler, which is not what we had in mind. In this case you have to specify on:click={
() => removeTodo(todo)} as the handler. If removeTodo
() received no params, you could use on:event={removeTodo}, but not on:event={removeTodo
()}. This is not some special Svelte syntax -- here we are just using regular JavaScript arrow functions. Again, this is good progress -- at this point, we can now delete tasks. When a todo item's Delete button is pressed, the relevant todo is removed from ...
...And 15 more matches
Browser API
erfaces To support the requirement of a browser <iframe>, the HTMLIFrameElement DOM interface has been extended with new methods that give the <iframe> some super powers. Navigation methods The following navigation methods allow navigation through the browsing history of the <iframe>. They are necessary to be able to implement back, forward, stop, and reload buttons. ...
...ent DOM interface has been extended with new methods that give the <iframe> some super powers. Navigation methods The following navigation methods allow navigation through the browsing history of the <iframe>. They are necessary to be able to implement back, forward, stop, and reload buttons. HTMLIFrameElement.reload
() Allows reloading of the <iframe> element content. HTMLIFrameElement.stop
() Allows stopping of the <iframe>'s content loading. ...
... powers. Navigation methods The following navigation methods allow navigation through the browsing history of the <iframe>. They are necessary to be able to implement back, forward, stop, and reload buttons. HTMLIFrameElement.reload
() Allows reloading of the <iframe> element content. HTMLIFrameElement.stop
() Allows stopping of the <iframe>'s content loading. HTMLIFrameElement.getCanGoBack
() Indicates whether it's possible to navigate backwards. HTMLIFrameElement.goBack
() Changes the location of the <iframe> for the previous location in its browsing history. HTMLIFrameElement.getCanGoForward
() Indicates whether it's possible to navigate forward. HTMLIFrameElement.goForward
() Changes the location of the <iframe> for the next location in its browsing history. Management method...
...And 15 more matches
Sqlite.jsm
ow for API). } catch (error) { // The connection could not be opened. error is an Error describing what went wrong. } Working with Opened Connections Opened connections are what you will interface most with in Sqlite.jsm. The following sections detail the API of an opened connection instance. Connection Management These APIs are used to manage and inspect the state of the connection. close
() Close this database connection. This must be called on every opened connection or else application shutdown will fail due to waiting on the opened connection to close (Gecko doesn't force close connections because it doesn't know that you are really done with them). This function returns a promise that will be resolved when the database has closed. If a transaction is in progress at the time t...
...ld not attempt to use the connection after calling this method as the connection will be unusable. It is possible to automatically close the connection when the browser is closed with the shutdown hook: const conn = await Sqlite.openConnection({ path: "myDatabase.sqlite", sharedMemoryCache: false }); try { Sqlite.shutdown.addBlocker("My connection closing", async
() => await conn.close
()); } catch (e) { // It's too late to block shutdown, just close the connection. await conn.close
(); throw e; } clone(readOnly) This function returns a clone of the current connection-promise. These functions receive the following arguments: readOnly (optional) If true the clone will be read-only, default is false. If the original connection is already read-only...
...e. If the original connection is already read-only, the clone will be, regardless of this option. If the original connection is using the shared cache, this parameter will be ignored and the clone will be as privileged as the original connection. transactionInProgress This boolean property indicates whether a transaction is in progress. This is rarely needed by external callers. shrinkMemory
() This function can be called to shrink the memory usage of the connection. This is a glorified wrapper around the PRAGMA shrink_memory statement, which tells SQLite to shrink its memory usage (by clearing caches, etc). While calling this has the benefit of shrinking memory, it can make your database slower, especially if you will be interacting with it shortly after calling this function. This i...
...And 15 more matches
JSS Provider Notes
wo choices. Use the binary release of JSS from mozilla.org. Apply for your own JCE code-signing certificate following the procedure at How to Implement a Provider for the JavaTM Cryptography Extension. Then you can sign your own JSS JAR file. Installing the Provider In order to use any part of JSS, including the JCA provider, you must first call CryptoManager.initialize
(). By default, the JCA provider will be installed in the list of providers maintained by the java.security.Security class. If you do not wish the provider to be installed, create a CryptoManager.InitializationValues object, set its installJSSProvider field to false, and pass the InitializationValues object to CryptoManager.initialize
(). Specifying the CryptoToken All cryptographic operation...
...ns except MessageDigest on the Internal Key Storage Token, a software token included in JSS/NSS. MessageDigest operations take place by default on the Internal Crypto Token, another internal software token in JSS/NSS. There is no good design reason for this difference, but it is necessitated by a quirk in the NSS implementation. In order to use a different token, use CryptoManager.setThreadToken
(). This sets the token to be used by the JSS JCA provider in the current thread. When you call getInstance
() on a JCA class, the JSS provider checks the current per-thread default token (by calling CryptoManager.getThreadToken
()) and instructs the new object to use that token for cryptographic operations. The per-thread default token setting is only consulted inside getInstance
(). Once a JCA object...
...ion later changes the per-thread default token. Whenever a new thread is created, its token is initialized to the default, the Internal Key Storage Token. Thus, the thread token is not inherited from the parent thread. ...
...And 15 more matches
NSS Sample Code Sample1
the result. // - the application sends or uses the result (possibly // after base64 encoding it. // // Server - an instance of a server that is part of a // cluster of servers that are sharing a common set // of encryption and MACing keys. // class Server { public: // Initializes the server instance. In particular, this // creates the key pair that is used for wrapping keys int Init
(); // Generates keys for encryption (AES) and MACing. The // wrapped keys are stored in data files. int GenerateKeys
(); // Gets the server's public key (wrapping key) to // send to another server. This becomes the input to // the ExportKeys method on the remote server. int ExportPublicKey(SECItem **pubKeyData); // Export the encryption and key using the key // provided. The key...
... // send to another server. This becomes the input to // the ExportKeys method on the remote server. int ExportPublicKey(SECItem **pubKeyData); // Export the encryption and key using the key // provided. The key should come from another server // in the cluster. (The admin should verify this.) // // In this example, the server must be started to perform // this function (see Start
()) int ExportKeys(SECItem *pubKey, SECItem **wrappedEncKey, SECItem **wrappedMacKey); // Import the keys received from another server in the // cluster. The admin should make sure the keys actually // came from the correct source. int ImportKeys(SECItem *wrappedEncKey, SECItem *wrappedMacKey); // Start the server, loading the encryption and MACing keys // from files ...
...portKeys(SECItem *pubKey, SECItem **wrappedEncKey, SECItem **wrappedMacKey); // Import the keys received from another server in the // cluster. The admin should make sure the keys actually // came from the correct source. int ImportKeys(SECItem *wrappedEncKey, SECItem *wrappedMacKey); // Start the server, loading the encryption and MACing keys // from files int Start
(); // Shut down the server. (For completeness) int Shutdown
(); // Compare keys in two server instances. Use this in the // example to make sure the keys are transferred correctly. // This will not work in real life! // // The servers must be started int CompareKeys(Server *peer); // Create a server - the name distiguish the keys in the // shared database in this example Ser...
...And 15 more matches
XPCOM array guide
other array types by using unsigned indices. nsCOMArray<T> - a C++ class which provides a typesafe, reference-counted container for pointers to a single type of COM object. nsAutoTArray<T, N> - a version of nsTArray which includes N entries of internal storage for the array data. nsTPtrArray<T> and nsAutoTPtrArray<T> - similar to using T* with the above arrays, but also provides a SafeElementAt
() accessor. As of Gecko 8, SafeElementAt
() is now directly available on nsTArray for arrays instantiated with pointer types. Some other arrays: FallibleTArray, AutoFallibleTArray, InfallibleTArray, AutoInfallibleTArray, nsTObserverArray, nsAutoTObserverArray. This handy chart may make it easier to understand the different arrays: Class Data Type Scriptable? Typesafe? Can be...
...ze? If so, just use a native C++ array unless you need the enumeration options on nsTArray<T>. Example: an array of error message static const char* pointers. Are all the things you are storing interface pointers to instances of the same interface? If so, use nsCOMArray. Example: a content node's list of nsIContent children. Otherwise use nsIArray and make liberal use of QueryElementAt
(). The point of nsCOMArray is that it's a template, and all the pointers in it must be pointers to the same type; it's nice to be able to use it because you get type-safety and don't have to spend time and code QIing (like you have to with nsIArray). Array Guidelines Here are a few simple rules which will keep your code clean and your developers happy: Use typesafe arrays like nsCOMArray<T> ...
...ass arrays of COM objects through interfaces or require a scriptable array. It can hold strong or weak references to its container objects. This basic interface only allows querying of existing elements in the array. The methods that modify the array have been broken out into nsIMutableArray. An nsIArray implementation can be created from C++ or JavaScript using nsIComponentManager.createInstance
() and the contract ID "@mozilla.org/array;1". The created array implements nsIMutableArray and nsIArray. Since nsIMutableArray derives from nsIArray, the resulting array can be cast to a read-only array. C++ Example void GetList(nsIArray** aResult) { nsCOMPtr<nsIMutableArray> array = do_CreateInstance(NS_ARRAY_CONTRACTID); // append some elements ... // return it to the caller *aResul...
...And 15 more matches
Starting WebLock
, the observer service implementing nsIObserverService can notify your object of registered events by means of this interface, as in the figure below. The Observer Interfaces The above figure shows the observer service maintaining a list of all registered nsIObserver objects. When the notification is made, the nsIObserverService broadcasts the notification from the caller of the NotifyObserver
() to the nsIObserver object's Observe
() method. This is a very useful decoupling of different objects. The nsIObserver is a generic interface for passing messages between two or more objects without defining a specific frozen interface, and it's one of the ways in which extensibility is built into XPCOM. The implementation of the nsIObserver interface in the WebLock component is similar to the imp...
...for the nsIFactory interface. XXX what is Example 2?Following Example 2, you change the class definition to support the nsIObserver interface and change NS_IMPL_ISUPPORTS1 so that the QueryInterface implementation knows that the component also supports nsIObserver. The WebLock class definition with support for startup observation is below. class WebLock: public nsIObserver { public: WebLock
(); virtual ~WebLock
(); NS_DECL_ISUPPORTS NS_DECL_NSIOBSERVER }; NS_IMPL_ISUPPORTS1(WebLock, nsIObserver); The standard implementation of Observe
() simply compares the aTopic string with the value defined by the event the object is expecting. When there is a match, you can handle the event any way you see fit. If the object has only registered for one notification, then you can ignor...
...NS_FAILED(rv)) return rv; do_QueryInterface The previous code uses the special nsCOMPtr function do_QueryInterface that lets you QueryInterface without having to worry about reference counting, error handling, and other overhead. The do_QueryInterface knows what interface to QI to based on the nsCOMPtr that is being assigned into. We could have just as easily have used the raw QueryInterface
() method, but using nsCOMPtr is much more economical (see Smart Pointers). Once you have a nsIServiceManager reference, you can ask it for the service you are interested in. This process is similar to using CreateInstance from the nsIComponentManager, but there is no aggregation parameter since the object has already been constructed. nsCOMPtr<nsICategoryManager> catman; rv = servman->GetService...
...And 15 more matches
nsIAppShellService
ve code only! ...
...itialHeight, in nsIAppShell aAppShell); nsIWebNav createWindowlessBrowser (in bool aIsChrome) void destroyHiddenWindow
(); void doProfileStartup(in nsICmdLineService aCmdLineService, in boolean canInteract); Obsolete since Gecko 1.8 void ensure1Window(in nsICmdLineService aCmdLineService); Obsolete since Gecko 1.8 void enterLastWindowClosingSurvivalArea
(); Obsolete since Gecko 1.8 void exitLastWindowClosingSurvivalArea
(); Obsolete since Gecko 1.8 void getHiddenWindowAndJSContext(out nsIDOMWindow aHiddenDOMWindow, out JSContext aJSContext); Native code only! ...
....8 void ensure1Window(in nsICmdLineService aCmdLineService); Obsolete since Gecko 1.8 void enterLastWindowClosingSurvivalArea
(); Obsolete since Gecko 1.8 void exitLastWindowClosingSurvivalArea
(); Obsolete since Gecko 1.8 void getHiddenWindowAndJSContext(out nsIDOMWindow aHiddenDOMWindow, out JSContext aJSContext); Native code only! ...
...And 15 more matches
nsINavBookmarkObserver
changes. ...
...Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 21.0 (Firefox 21.0 / Thunderbird 21.0 / SeaMonkey 2.18) Method overview void onBeforeItemRemoved(in long long aItemId, in unsigned short aItemType, in long long aParentId, in ACString aGUID, in ACString aParentGUID); Obsolete since Gecko 21.0 void onBeginUpdateBatch
(); void onEndUpdateBatch
(); void onFolderAdded(in PRInt64 folder, in PRInt64 parent, in PRInt32 index); Obsolete since Gecko 1.9 void onFolderChanged(in PRInt64 folder, in ACString property); Obsolete since Gecko 1.9 void onFolderMoved(in PRInt64 folder, in PRInt64 oldParent, in PRInt32 oldIndex, in PRInt64 newParent, in PRInt32 newIndex); Obsolete since Gecko 1.9 void onFolderRemoved(in...
... This method notifies this observer that an item is about to be removed. It is called before the actual removal takes place. void onBeforeItemRemoved( in long long aItemId, in unsigned short aItemType, in long long aParentId, in...
...And 15 more matches
Battery Status API - Web APIs
tion about the system's battery charge level and lets you be notified by events that are sent when the battery level or charging status change. This can be used to adjust your app's resource usage to reduce battery drain when the battery is low, or to save changes before the battery runs out in order to prevent data loss. The Battery Status API extends window.navigator with a navigator.getBattery
() method returning a battery promise, which is resolved in a BatteryManager object providing also some new events you can handle to monitor the battery status. Example In this example, we watch for changes both to the charging status (whether or not we're plugged in and charging) and for changes to the battery level and timing. This is done by listening for the chargingchange, levelchange, chargi...
...ryManager object providing also some new events you can handle to monitor the battery status. Example In this example, we watch for changes both to the charging status (whether or not we're plugged in and charging) and for changes to the battery level and timing. This is done by listening for the chargingchange, levelchange, chargingtimechange, dischargingtimechange events. ...
...dle to monitor the battery status. Example In this example, we watch for changes both to the charging status (whether or not we're plugged in and charging) and for changes to the battery level and timing. This is done by listening for the chargingchange, levelchange, chargingtimechange, dischargingtimechange events. ...
...And 15 more matches
Using the Gamepad API - Web APIs
de. The Gamepad API is a way for developers and designers to access and use gamepads and other game controllers. The Gamepad API introduces new events on the Window object for reading gamepad and controller (hereby referred to as gamepad) state. In addition to these events, the API also adds a Gamepad object, which you can use to query the state of a connected gamepad, and a navigator.getGamepads
() method which you can use to get a list of gamepads known to the page. Connecting to a gamepad When a new gamepad is connected to the computer, the focused page first receives a gamepadconnected event. If a gamepad is already connected when the page loaded, the gamepadconnected event is dispatched to the focused page when the user presses a button or moves an axis. In Firefox, gamepads are onl...
...onnected: window.addEventListener("gamepaddisconnected", function(e) { console.log("Gamepad disconnected from index %d: %s", e.gamepad.index, e.gamepad.id); }); The gamepad's index property will be unique per-device connected to the system, even if multiple controllers of the same type are used. The index property also functions as the index into the Array returned by Navigator.getGamepads
(). ...
....gamepad.id); }); The gamepad's index property will be unique per-device connected to the system, even if multiple controllers of the same type are used. The index property also functions as the index into the Array returned by Navigator.getGamepads
(). ...
...And 15 more matches
Headers - Web APIs
The Headers interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing headers from the list of the request's headers. A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. You can add to this using methods like append
() (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence. For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names. A Headers object also has an associated guard, which takes a value of immutable, request, request-no-cors, response, or no...
...of this interface, header names are matched by case-insensitive byte sequence. For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names. A Headers object also has an associated guard, which takes a value of immutable, request, request-no-cors, response, or none. ...
...terface, header names are matched by case-insensitive byte sequence. For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names. A Headers object also has an associated guard, which takes a value of immutable, request, request-no-cors, response, or none. ...
...And 15 more matches
Using the Notifications API - Web APIs
't been asked for permission yet, so notifications won't be displayed. granted The user has granted permission to display notifications, after having been asked previously. denied The user has explicitly declined permission to show notifications. ...
...otifications, after having been asked previously. denied The user has explicitly declined permission to show notifications. Getting permission If permission to display notifications hasn't been granted yet, the application needs to use the Notification.requestPermission
() method to request this from the user. In its simplest form, we just include the following: Notification.requestPermission
().then(function(result) { console.log(result); }); This uses the promise-based version of the method. If you want to support older versions, you might have to use the older callback version, which looks like this: Notification.requestPermission
(); The callback version optionally accepts a callback function that is called once the user has responded to the request to display permissions. Examp...
...rmission
(); The callback version optionally accepts a callback function that is called once the user has responded to the request to display permissions. Example In our todo list demo, we include an "Enable notifications" button that, when pressed, requests notification permissions for the app. ...
...And 15 more matches
SVGSVGElement - Web APIs
the translation factor that takes into account user "magnification" corresponding to an outermost <svg> element. The behavior is undefined for <svg> elements that are not at the outermost level. Methods This interface also inherits methods from its parent, SVGGraphicsElement and also implements the ones from SVGZoomAndPan, SVGFitToViewBox, and WindowEventHandlers. ...
... behavior is undefined for <svg> elements that are not at the outermost level. Methods This interface also inherits methods from its parent, SVGGraphicsElement and also implements the ones from SVGZoomAndPan, SVGFitToViewBox, and WindowEventHandlers. SVGSVGElement.suspendRedraw
() Takes a time-out value which indicates that redraw shall not occur until: the corresponding unsuspendRedraw
() call has been made, an unsuspendRedrawAll
() call has been made, or its timer has timed out. In environments that do not support interactivity (e.g., print media), then redraw shall not be suspended. Calls to suspendRedraw
() and unsuspendRedraw
() should, but need not be, made in balanced pairs. To suspend redraw actions as a collection of SVG DOM changes occur, precede the changes to the SVG D...
...draw
() and unsuspendRedraw
() should, but need not be, made in balanced pairs. To suspend redraw actions as a collection of SVG DOM changes occur, precede the changes to the SVG DOM with a method call similar to: const suspendHandleID = suspendRedraw(maxWaitMilliseconds) and follow the changes with a method call similar to: unsuspendRedraw(suspendHandleID) Note that multiple suspendRedraw
() calls can be used at once, and that each such method call is treated independently of the other suspendRedraw
() method calls. SVGSVGElement.unsuspendRedraw
() Cancels a specified suspendRedraw
() by providing a unique suspend handle ID that was returned by a previous suspendRedraw
() call. SVGSVGElement.unsuspendRedrawAll
() Cancels all currently active suspendRedraw
() method calls. This me...
...And 15 more matches
Controlling multiple parameters with ConstantSourceNode - Web APIs
the volume levels for each of the three oscillators. gainNode2 and gainNode3 will be linked together to have the same, adjustable, value using the ConstantSourceNode. constantNode The ConstantSourceNode used to control the values of gainNode2 and gainNode3 together. playing A Boolean that we'll use to keep track of whether or not we're currently playing the tones. ...
...SourceNode. constantNode The ConstantSourceNode used to control the values of gainNode2 and gainNode3 together. playing A Boolean that we'll use to keep track of whether or not we're currently playing the tones. Now let's look at the setup
() function, which is our handler for the window's load event; it handles all the initialization tasks that require the DOM to be in place. ...
...alues of gainNode2 and gainNode3 together. playing A Boolean that we'll use to keep track of whether or not we're currently playing the tones. Now let's look at the setup
() function, which is our handler for the window's load event; it handles all the initialization tasks that require the DOM to be in place. ...
...And 15 more matches
Classes - JavaScript
ngle { constructor(height, width) { this.height = height; this.width = width; } } Hoisting An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. You first need to declare your class and then access it, otherwise code like the following will throw a ReferenceError: const p = new Rectangle
(); // ReferenceError class Rectangle {} Class expressions A class expression is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class's body. (it can be retrieved through the class's (not an instance's) name property, though). // unnamed let Rectangle = class { constructor(height, width) { this.height = ...
...ith the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method. A constructor can use the super keyword to call the constructor of the super class. Prototype methods See also method definitions. class Rectangle { constructor(height, width) { this.height = height; this.width = width; } // Getter get area
() { return this.calcArea
(); } // Method calcArea
() { return this.height * this.width; } } const square = new Rectangle(10, 10); console.log(square.area); // 100 Static methods The static keyword defines a static method for a class. Static methods are called without instantiating their class and cannot be called through a class instance. Static methods are often used to create ut...
...static methods When a static or prototype method is called without a value for this, such as by assigning a variable to the method and then calling it, the this value will be undefined inside the method. This behavior will be the same even if the "use strict" directive isn't present, because code within the class body's syntactic boundary is always executed in strict mode. ...
...And 15 more matches
Creating annotations - Archive of obsolete content
page element that is the current candidate for an annotation. The matched element is highlighted and has a click handler bound to it which sends a message to the main add-on code. The selector page mod can be switched on and off using a message from the main add-on code. It is initially off: var matchedElement = null; var originalBgColor = null; var active = false; function resetMatchedElement
() { if (matchedElement) { (matchedElement).css('background-color', originalBgColor); (matchedElement).unbind('click.annotator'); } } self.on('message', function onMessage(activation) { active = activation; if (!active) { resetMatchedElement
(); } }); This selector listens for occurrences of the jQuery mouseenter event. When a mouseenter event is triggered the selector checks...
...e able to identify annotated elements correctly later on. If the page element is eligible for annotation, then the selector highlights that element and binds a click handler to it. The click handler sends a message called show back to the main add-on code. The show message contains: the URL for the page, the ID attribute value, and the text content of the page element. ...
...or annotation, then the selector highlights that element and binds a click handler to it. The click handler sends a message called show back to the main add-on code. The show message contains: the URL for the page, the ID attribute value, and the text content of the page element. ...
...And 14 more matches
Preferences - Archive of obsolete content
OM interfaces for preferences system Mozilla exposes its preferences system through a few XPCOM interfaces. Look in the Resources section below for the link to a list of preferences-related interfaces. Two used interfaces are nsIPrefService and nsIPrefBranch. The preferences service is instantiated in the same way you instantiate any XPCOM service. To get an nsIPrefBranch, either QueryInterface
() the pref service (that will give you the root branch) or call nsIPrefService.getBranch
() to get a sub-branch. Here are two examples: // Get the root branch var prefs = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefBranch); // Get the "extensions.myext." branch var prefs = Components.classes["@mozilla.org/preferences-servi...
...ses["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService); prefs = prefs.getBranch("extensions.myext."); Simple types There are three types of preferences: string, integer, and boolean. Each entry in the preferences database (prefs.js) has one of those types. There are six methods in nsIPrefBranch that read and write preferences: getBoolPref
(), setBoolPref
(), getCharPref
(), setCharPref
(), getIntPref
(), and setIntPref
(). Using them is as easy as: // Get the "accessibility." branch var prefs = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService).getBranch("accessibility."); // prefs is an nsIPrefBranch. // Look in the above section for examples of getting one. va...
...ing, an integer, or a boolean value. However, there is a concept of complex types, which makes it easier for developers to save and load nsILocalFile and nsISupportsString objects in preferences (as strings -- note that from the preferences system's point of view, complex values have a nsIPrefBranch.PREF_STRING type.) There are two nsIPrefBranch methods implementing the concept -- setComplexValue
() and getComplexValue
(). You can look up their implementations in nsPrefBranch.cpp. Here are the IDL definitions: void getComplexValue(in string aPrefName, in nsIIDRef aType, [iid_is(aType), retval] out nsQIResult aValue); void setComplexValue(in string aPrefName, in nsIIDRef aType, in nsISupports aValue); As you can see, both of them take a parameter, aType, which can have ...
...And 14 more matches
Space Manager Detailed Design - Archive of obsolete content
class, and is not intended to be subclasses . Here is the class declaration, taken from the source file as of 01.08.02 /** * Class for dealing with bands of available space. The space manager * defines a coordinate space with an origin at (0, 0) that grows down * and to the right. */ class nsSpaceManager { public: nsSpaceManager(nsIPresShell* aPresShell, nsIFrame* aFrame); ~nsSpaceManager
(); void* operator new(size_t aSize); void operator delete(void* aPtr, size_t aSize); static void Shutdown
(); /* * Get the frame that's associated with the space manager. This frame * created the space manager, and the world coordinate space is * relative to this frame. * * You can use QueryInterface
() on this frame to get any additional * interfaces. */ nsIFrame* G...
...This * creates a new local coordinate space relative to the current * coordinate space. ...
...; } /** * Translate the current origin by the specified (dx, dy). This * creates a new local coordinate space relative to the current * coordinate space. */ void Translate(nscoord aDx, nscoord aDy) { mX += aDx; mY += aDy; } /** * Returns the current translation from local coordinate space to * world coordinate space. This represents the accumulated calls to * Translate
(). */ void GetTranslation(nscoord& aX, nscoord& aY) const { aX = mX; aY = mY; } /** * Returns the y-most of the bottommost band or 0 if there are no bands. * * @return PR_TRUE if there are bands and PR_FALSE if there are no bands */ PRBool YMost(nscoord& aYMost) const; /** * Returns a band starting at the specified y-offset. The band data * indicates which parts of t...
...And 14 more matches
Working With Directories - Archive of obsolete content
se, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. A reference to a directory may be created in the same way as with a file by using nsIScriptableIO.getFile
(). You can access a subdirectory by supplying a directory name as the second argument, or refer to one of the special directories by supplying a null string for the second argument. The first line below with retrieve the directory corresponding to the user's home directory, while the second will retrieve the directory 'myfiles' on the desktop. var dir1 = IO.getFile("Home", ""); var dir2 = IO.getFil...
...one of the special directories by supplying a null string for the second argument. The first line below with retrieve the directory corresponding to the user's home directory, while the second will retrieve the directory 'myfiles' on the desktop. var dir1 = IO.getFile("Home", ""); var dir2 = IO.getFile("Desktop", "myfiles"); To refer to a subdirectory, rather than using a path, use nsIFile.append
() to build up a path. For instance: var dir2 = IO.getFile("Desktop", "myfiles"); dir2.append("pictures"); dir2.append("vacations"); In this example, a subdirectory several levels down is referenced. Each call to nsIFile.append
() navigates to a further subdirectory. The result is a subdirectory three levels below the desktop directory. These directories do not need to exist yet, but they can be cre...
...instance: var dir2 = IO.getFile("Desktop", "myfiles"); dir2.append("pictures"); dir2.append("vacations"); In this example, a subdirectory several levels down is referenced. Each call to nsIFile.append
() navigates to a further subdirectory. The result is a subdirectory three levels below the desktop directory. These directories do not need to exist yet, but they can be created using nsIFile.create
(). See Creating Directories below for information about this. Note that nsIFile.append
() modifies the file object, rather than returning a new one. Both files and directories are represented using the same kind of object so most of the functions available for nsIFile will work for both. You can check if the object refers to a directory or a file by using nsIFile.isDirectory
(). This method returns t...
...And 14 more matches
textbox (Toolkit autocomplete) - Archive of obsolete content
s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
... the timeout attribute. type Type: string Set to the value autocomplete to have an autocomplete textbox. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...tribute. type Type: string Set to the value autocomplete to have an autocomplete textbox. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...And 14 more matches
XPCOM Interfaces - Archive of obsolete content
contract ID. The syntax of a contract ID is: @<internetdomain>/module[/submodule[...]];<version>[?<name>=<value>[&<name>=<value>[...]]] Other components can be referred to in a similar way. The contract ID of the component can be used to get the component. You can get a component using JavaScript code like that below: var aFile = Components.classes["@mozilla.org/file/local;1"].createInstance
(); The file component is retrieved and stored in the aFile variable. Components in the example above refers to a general object that provides some component related functions. Here, we get a component class from the classes property. The classes property is an array of all of the available components. To get a different component, just replace the contract ID inside the square brackets with the c...
...e refers to a general object that provides some component related functions. Here, we get a component class from the classes property. The classes property is an array of all of the available components. To get a different component, just replace the contract ID inside the square brackets with the contract ID of the component you want to use. Finally, an instance is created with the createInstance
() function. You should check the return value of createInstance
() to ensure that it is not null, which would indicate that the component does not exist. However, at this point, we only have a reference to the file component itself. In order to call the functions of it we need to get one of its interfaces, in this case nsILocalFile. A second line of code needs to be added as follows: var aFile = ...
...This function takes one parameter, the interface that you want to get. The interfaces property of the Components object contains a list of all the interfaces that are available. ...
...And 14 more matches
listitem - Archive of obsolete content
"/> <listitem label="Sapphire" selected="true"/> <listitem label="Diamond"/> </listbox> Attributes accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. checked Type: boolean Indicates whether the element is checked or not. Use hasAttribute
() to determine whether this attribute is set instead of getAttribute
(). For buttons, the type attribute must be set to checkbox or radio for this attribute to have any effect. command Type: id Set to the id of a command element that is being observed by the element. crop Type: one of the values below If the label of the element is too big to fit in its given spac...
...s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
...s in Firefox 3. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...And 14 more matches
menulist - Archive of obsolete content
s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
...ed by the user. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
... tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...And 14 more matches
preference - Archive of obsolete content
cating that the preference does not have a user-set value (hasUserValue == false). In this case the actual value to be displayed in the UI is obtained from the defaultValue property. valueFromPreferences Gets and sets the value stored in the user preference, specified in name. (This always accesses the nsIPrefBranch APIs regardless of the instantApply mode in effect). Methods reset
() Return type: no return value Resets the preference to its default value. For a textbox it also clears the undo transaction list (Gecko 1.9). type getElementValue(in DOMElement element); Retrieves the value that should be written to preferences based on the current state of the supplied element. This function calls onsynctopreference. boolean isElementEditable(in DOMElem...
...preferences based on the current state of the supplied element. This function calls onsynctopreference. boolean isElementEditable(in DOMElement element) Returns true, if the given element is "editable" (see below). void setElementValue(in DOMElement element); Initializes the supplied element from the value stored in the preference. This function calls onsyncfrompreference. ...
...ference. boolean isElementEditable(in DOMElement element) Returns true, if the given element is "editable" (see below). void setElementValue(in DOMElement element); Initializes the supplied element from the value stored in the preference. This function calls onsyncfrompreference. void updateElements
(); Update all elements that observe this preference. ...
...And 14 more matches
scale - Archive of obsolete content
s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
...nt attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
... tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...And 14 more matches
textbox - Archive of obsolete content
string. The current value may be modified by setting this property. valueNumber Type: number In contrast to the value property which holds a string representation, the valueNumber property is a number containing the current value of the number box. wrapAround Type: boolean Gets and sets the value of the wraparound attribute. Methods decrease
() Return type: no return value Decreases the value of the scale or number box by the increment. increase
() Return type: no return value Increases the value of the scale or number box by the increment. reset
() Return type: no return value Resets the preference to its default value. For a textbox it also clears the undo transaction list...
...rn value Decreases the value of the scale or number box by the increment. increase
() Return type: no return value Increases the value of the scale or number box by the increment. reset
() Return type: no return value Resets the preference to its default value. For a textbox it also clears the undo transaction list (Gecko 1.9). select
() Return type: no return value Selects all the text in the textbox. setSelectionRange( start, end ) Return type: no return value Sets the selected portion of the textbox, where the start argument is the index of the first character to select and the end argument is the index of the character after the selection. Set both arguments to the same value to move the cu...
...tionRange( start, end ) Return type: no return value Sets the selected portion of the textbox, where the start argument is the index of the first character to select and the end argument is the index of the character after the selection. Set both arguments to the same value to move the cursor to the corresponding position without selecting text. ...
...And 14 more matches
toolbar - Archive of obsolete content
for external toolbars. These are toolbars that are not children of a toolbox element. You can associate an external toolbar with a toolbox for the purpose of managing your toolbars by setting the toolboxid property on the toolbar. The chromeclass-toolbar class may be used to create a toolbar where its visibility depends on the toolbar flag when opening the window with the window interface's open
() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. If the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open
() method. More information is available in the XUL tutorial. Note: Starting in Gecko 1.9.1, toolbar items are moved from the toolbarpalette and added t...
...r the use of the customize dialog. The id should match an element in the toolbar's toolbarpalette. Some special ids may also be used to create special spacing items: separator: A separator, which is drawn as a vertical bar. spacer: A non-flexible space. spring: A flexible space. The method returns the DOM element for the created item. ...
...e customize dialog. The id should match an element in the toolbar's toolbarpalette. Some special ids may also be used to create special spacing items: separator: A separator, which is drawn as a vertical bar. spacer: A non-flexible space. spring: A flexible space. The method returns the DOM element for the created item. ...
...And 14 more matches
Using workers in extensions - Archive of obsolete content
how workers and main thread code can pass data back and forth. The worker The worker thread's job in this example is to issue the XMLHttpRequest calls that fetch the updated stock information. That's all it does. Every 10 minutes, it calls XMLHttpRequest, and, when the results are received, sends an event back to the main thread with the received data. ...
...ormation. That's all it does. Every 10 minutes, it calls XMLHttpRequest, and, when the results are received, sends an event back to the main thread with the received data. So we need to move the refreshInformation
() method from the stockwatcher2.js file into a separate file that will host the worker thread. ...
...So we need to move the refreshInformation
() method from the stockwatcher2.js file into a separate file that will host the worker thread. ...
...And 14 more matches
Sending forms through JavaScript - Learn web development
the safest and most reliable way to make HTTP requests. To send form data with XMLHttpRequest, prepare the data by URL-encoding it, and obey the specifics of form data requests. Let's look at an example: <button>Click Me!</button> And now the JavaScript: const btn = document.querySelector('button'); function sendData( data ) { console.log( 'Sending data' ); const XHR = new XMLHttpRequest
(); let urlEncodedData = "", urlEncodedDataPairs = [], name; // Turn the data object into an array of URL-encoded key/value pairs. for( name in data ) { urlEncodedDataPairs.push( encodeURIComponent( name ) + '=' + encodeURIComponent( data[name] ) ); } // Combine the pairs into a single string and replace all %-encoded spaces to // the '+' character; matches the behavio...
...error', function(event) { alert( 'Oops! Something went wrong.' ); } ); // Set up our request XHR.open( 'POST', 'https://example.com/cors.php' ); // Add the required HTTP header for form data POST requests XHR.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' ); // Finally, send our data. XHR.send( urlEncodedData ); } btn.addEventListener( 'click', function
() { sendData( {test:'ok'} ); } ) Here's the live result: Note: This use of XMLHttpRequest is subject to the same-origin policy if you want to send data to a third party web site. For cross-origin requests, you'll need CORS and HTTP access control. Using XMLHttpRequest and the FormData object Building an HTTP request by hand can be overwhelming. Fortunately, the XMLHttpRequest specificati...
...nly", which means you can change them, but not retrieve their contents. Using this object is detailed in Using FormData Objects, but here are two examples: Using a standalone FormData object <button>Click Me!</button> You should be familiar with that HTML sample. ...
...And 14 more matches
Handling common JavaScript problems - Learn web development
ch incompatibility problems persisted well into the early 2000s, as old browsers were still being used and still needed supporting. This is one of the main reasons why libraries like jQuery came into existence -- to abstract away differences in browser implementations (e.g. see the code snippet in How to make an HTTP request) so developers only have to write one simple bit of code (see jQuery.ajax
()). jQuery (or whatever library you are using) will then handle the differences in the background, so you don't have to. Things have improved significantly since then; modern browsers do a good job of supporting "classic JavaScript features", and the requirement to use such code has diminished as the requirement to support older browsers has lessened (although bear in mind that they have not gone ...
...= 0; i < heroes.length; i++) { ... So the code falls over as soon as we try to access a property of jsonObj (which as you might expect, is supposed to be a JSON object). This is supposed to be fetched from an external .json file using the following XMLHttpRequest call: let requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; let request = new XMLHttpRequest
(); request.open('GET', requestURL); request.send
(); let superHeroes = request.response; populateHeader(superHeroes); showHeroes(superHeroes); But this fails. The Console API You may already know what is wrong with this code, but let's explore it some more to show how you could investigate this. For a start, there is a Console API that allows JavaScript code to interact with the browser's JavaSc...
...r(superHeroes); showHeroes(superHeroes); But this fails. The Console API You may already know what is wrong with this code, but let's explore it some more to show how you could investigate this. For a start, there is a Console API that allows JavaScript code to interact with the browser's JavaScript console. ...
...And 14 more matches
Performance best practices for Firefox front-end engineers
pond to user events, paint, and generally be responsive to the user. You might want to consider using a Worker if you need to do some computation that can be done off of the main thread. If you need more elevated privileges than a standard worker allows, consider using a ChromeWorker, which is a Firefox-only API which lets you create workers with more elevated privileges. ...
... See also the blog post Collective scheduling with requestIdleCallback. ...
...ribution 3.0, courtesy of this page from our friends at Google, which itself is well worth the read. For a very down-to-earth explanation of the Style, Layout, Paint and Composite steps of the pipeline, this Hacks blog post does a great job of explaining it. To achieve a 60 FPS frame rate, all of the above has to happen in 16 milliseconds or less, every frame. Note that requestAnimationFrame
() lets you queue up JavaScript to run right before the style flush occurs. This allows you to put all of your DOM writes (most importantly, anything that could change the size or position of things in the DOM) just before the style and layout steps of the pipeline, combining all the style and layout calculations into a single batch so it all happens once, in a single frame tick, instead of across m...
...And 14 more matches
Introduction to the JavaScript shell
e SpiderMonkey JavaScript shell, see the SpiderMonkey Build Documentation or download a compiled binary for your platform from the Nightly Builds. For a list of other JavaScript shells, see JavaScript shells. Note: Starting with SpiderMonkey 44 (Firefox 44 / Thunderbird 44 / SeaMonkey 2.41), the standard, Web-compatible JavaScript version is used by default (and not JS1.7+ anymore). The version
() shell builtin is still there for testing legacy features. Running the JavaScript shell The shell offers two modes of operation. You can use it as an interactive shell, in which you type JavaScript code at a prompt and get instant gratification, which is handy for experimenting or testing new features. You can also pass in, on the command line, a JavaScript program file to run, in which case th...
...T=file Redirect stdout to file. JS_STDERR=file Redirect stderr to file. Built-in functions To make the JavaScript shell more useful, there are a number of built-in functions provided that 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 b...
... Added in SpiderMonkey 1.8 Dump the graph of all existing objects (or a specific interesting subgraph) to a file. For more information, see the C/C++ version of this function, JS_DumpHeap. evalcx(string[, object]) Evaluates the JavaScript code in string. If object is specified, the code is executed in that object, treating it as a sandbox. If string is empty and object is not specified, evalcx
() returns a new object with eager standard classes. If string is "lazy" and object is not specified, evalcx
() returns a new object with lazy standard classes. Note: evalcx
() is only useful for people doing deep internal work on the JavaScript engine, for testing evalInSandbox-like environments in the shell. gc
() Runs the garbage collector to free up memory. gcparam(name[, value]) Added in Spi...
...And 14 more matches
JS::Value
d functions), boolean, symbol, null, or undefined. JS::Value is a class whose internal structure is an implementation detail. Embeddings should not rely on observed representation details or upon the size of JS::Value. ...
...an, symbol, null, or undefined. JS::Value is a class whose internal structure is an implementation detail. Embeddings should not rely on observed representation details or upon the size of JS::Value. ...
...efined. JS::Value is a class whose internal structure is an implementation detail. Embeddings should not rely on observed representation details or upon the size of JS::Value. ...
...And 14 more matches
Places Developer Guide
there). Bool getFolderReadonly(aFolderId) Accessing Folder Contents Queries in Places are executed through the main history service. The example below shows how to enumerate a bookmark folder's contents, and how to access the properties of the items themselves. var history = Cc["@mozilla.org/browser/nav-history-service;1"] .getService(Ci.nsINavHistoryService); var query = history.getNewQuery
(); query.setFolders([myFolderId], 1); var result = history.executeQuery(query, history.getNewQueryOptions
()); // The root property of a query result is an object representing the folder you specified above. var folderNode = result.root; // Open the folder, and iterate over its contents. folderNode.containerOpen = true; for (var i=0; i < folderNode.childCount; ++i) { var childNode = folderNode.getC...
...ecuted through the history service. The example below shows how to search through all bookmarks, and to iterate over the results. ...
...var resultContainerNode = result.root; // Open the folder, and iterate over its contents. ...
...And 14 more matches
Component; nsIPrefBranch
e Type Description root string Called to get the root on which this branch is based, such as "browser.startup." Read only. Constants Constant Value Description PREF_INVALID 0 long PREF_STRING 32 long data type. PREF_INT 64 long data type. PREF_BOOL 128 long data type. Methods addObserver
() Adds a preference change observer. On preference changes, the following arguments will be passed to nsIObserver.observe
(): aSubject - The nsIPrefBranch object (this). aTopic - The string defined by NS_PREFBRANCH_PREFCHANGE_TOPIC_ID aData - The name of the preference which has changed, relative to the "root" of the aSubject branch. aSubject.get*Pref(aData) will get the new value of the modifi...
...ure of aObserver is any object with an observe function. See nsIObserver and here is a quick snippet: var myObserver = { observe: function(aSubject, aTopic, aData) { //do stuff here } } aHoldWeak true holds a weak reference to aObserver. The object must implement the nsISupportsWeakReference interface or this will fail. false holds a strong reference to aObserver. clearUserPref
() Called to clear a user set value from a specific preference. This will, in effect, reset the value to the default value. If no default value exists the preference will cease to exist. Note: This method does nothing if the prefbranch it is called on is a default branch. void clearUserPref( in string aPrefName ); Parameters aPrefName The preference to be cleared. Remarks Note: Prior ...
...e: This method does nothing if the prefbranch it is called on is a default branch. void clearUserPref( in string aPrefName ); Parameters aPrefName The preference to be cleared. Remarks Note: Prior to Gecko 6.0, this method would throw an exception if there was no user value set for the specified preference. Now, this method never throws. Instead, it simply does nothing. deleteBranch
() Called to remove all of the preferences referenced by this branch. Note: This method can be called on either a default or user branch but, in effect, always operates on both. void deleteBranch( in string aStartingAt ); Parameters aStartingAt The point on the branch at which to start the deleting preferences. Pass in "" to remove all preferences referenced by this branch. getBoolPref(...
...And 14 more matches
nsISHEntry
y 2.3) Implemented by: @mozilla.org/browser/session-history-entry;1. ...
... @mozilla.org/browser/session-history-entry;1. ...
...m childShellAt(in long index); void clearChildShells
(); nsISHEntry clone
(); void create(in nsIURI URI, in AString title, in nsIInputStream inputStream, in nsILayoutHistoryState layoutHistoryState, in nsISupports cacheKey, in ACString contentType, in nsISupports owner, in unsigned long long docshellID, in boolean dynamicCreation); Native code only! nsDocShellEditorDataPtr forgetEditorData
(); Violates the XPCOM interface guidelines nsIContentViewer getAnyContentViewer(out nsISHEntry ownerEntry); void getScrollPosition(out long x, out long y); void getViewerBounds(in nsIntRect bounds); Native code only! ...
...And 14 more matches
Checking when a deadline is due - Web APIs
ter (7, sunday, sun? 04, 4, April, Apr? 2013, '13, 13?), I decided the best solution was to give them a choice to pick from, which also saves on annoying typing for mobile users. The days are recorded as numerical days of the month, the months are recorded as full month names, and the years are recorded as full four digit year numbers. When the form's submit button is pressed, we run the addData
() function, which starts like this: function addData(e) { e.preventDefault
(); if(title.value == '' || hours.value == null || minutes.value == null || day.value == '' || month.value == '' || year.value == null) { note.innerHTML += '<li>Data not submitted -- form incomplete.</li>'; return; } In this segment, we check to see if the form fields have all been filled in. If not, we drop...
... title.value = ''; hours.value = null; minutes.value = null; day.value = 01; month.value = 'January'; year.value = 2020; }; } This next section creates a log message to say the new item addition is successful, and resets the form so it's ready for the next task to be entered. ...
... hours.value = null; minutes.value = null; day.value = 01; month.value = 'January'; year.value = 2020; }; } This next section creates a log message to say the new item addition is successful, and resets the form so it's ready for the next task to be entered. // update the display of data to show the newly added item, by running displayData
() again. ...
...And 14 more matches
Recording a media element - Web APIs
In this article, we'll look at an example that does just that. HTML content <p>Click the "Start" button to begin video recording for a few seconds. You can stop the video by clicking the creatively-named "Stop" button. ...
...ument.getElementById("log"); let recordingTimeMS = 5000; Most of these are references to elements we need to work with. The last, recordingTimeMS, is set to 5000 milliseconds (5 seconds); this specifies the length of the videos we'll record. Utility functions Next, we create some utility functions that will get used later. function log(msg) { logElement.innerHTML += msg + "\n"; } The log
() function is used to output text strings to a <div> so we can share information with the user. Not very pretty but it gets the job done for our purposes. function wait(delayInMS) { return new Promise(resolve => setTimeout(resolve, delayInMS)); } The wait
() function returns a new Promise which resolves once the specified number of milliseconds have elapsed. It works by using an arrow function ...
...ext strings to a <div> so we can share information with the user. Not very pretty but it gets the job done for our purposes. function wait(delayInMS) { return new Promise(resolve => setTimeout(resolve, delayInMS)); } The wait
() function returns a new Promise which resolves once the specified number of milliseconds have elapsed. It works by using an arrow function which calls window.setTimeout
(), specifying the promise's resolution handler as the timeout handler function. ...
...And 14 more matches
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
the local device. The difference is that remote-outbound-rtp describes statistics about the transmission(s) from the perspective of the remote peer, while inbound-rtp offers statistics about the incoming data from the local peer's perspective. You can examine, try out, and experiment with this example on Glitch. Example In this example, we have a pair of functions: the first, networkTestStart
(), captures an initial report, and the second, networkTestStop
(), captures a second report, then uses the two reports to output some information about the network conditions... XXX ... networkTestStart
() This function simply calls the RTCPeerConnection method getStats
() to request an RTCStatsReport and store it in the variable startReport. let startReport; async function networkTestStart(pc) { ...
...XXX ... ...
...XXX ... ...
...And 14 more matches
Rendering and the WebXR frame animation callback - Web APIs
article covers the process of driving the frames of the XR scene to the device in the rendering loop, using the XRSession to obtain an XRFrame object representing each frame, which is then used to prepare the framebuffer for delivery to the XR device. Before you can render the virtual environment, you need to establish a WebXR session by creating an XRSession using the navigator.xr.requestSession
() method; you also need to associate the session with a framebuffer and perform other setup tasks. These setup tasks are described in the article Setting up and shutting down a WebXR session. Preparing the renderer Once the XR session has been set up, with the WebGL framebuffer connected and WebGL primed with the data it needs in order to render the scene, you can set up the renderer to start run...
...the renderer to start running. This begins with getting the reference space in which you want to draw, with its origin and orientation set at the viewer's starting position and viewing direction. Once that's in hand, you request that the browser call your rendering function the next time it needs a framebuffer to render your scene. This is done by calling the XRSession method requestAnimationFrame
(). Kicking off the renderer thus looks like this: let worldRefSpace; async function runXR(xrSession) { worldRefSpace = await xrSession.requestReferenceSpace("immersive-vr"); if (worldRefSpace) { viewerRefSpace = worldRefSpace.getOffsetReferenceSpace( new XRRigidTransform(viewerStartPosition, viewerStartOrientation)); animationFrameRequestID = xrSession.requestAnimationFrame(...
...ewerStartOrientation)); animationFrameRequestID = xrSession.requestAnimationFrame(myDrawFrame); } } After getting a reference space for the immersive world, this creates an offset reference space representing the position and orientation of the viewer by creating an XRRigidTransform representing that position and orientation, then calling the XRReferenceSpace method getOffsetReferenceSpace
(). ...
...And 14 more matches
Visualizations with Web Audio API - Web APIs
eform, and other data from your audio source, which can then be used to create visualizations. This article explains how, and provides a couple of basic use cases. Note: You can find working examples of all the code snippets in our Voice-change-O-matic demo. ...
... This article explains how, and provides a couple of basic use cases. Note: You can find working examples of all the code snippets in our Voice-change-O-matic demo. ...
... couple of basic use cases. Note: You can find working examples of all the code snippets in our Voice-change-O-matic demo. ...
...And 14 more matches
Using the Web Speech API - Web APIs
ou can have as many terms defined as you want on separate lines following the above structure, and include fairly complex grammar definitions. For this basic demo, we are just keeping things simple. Plugging the grammar into our speech recognition The next thing to do is define a speech recogntion instance to control the recognition for our application. This is done using the SpeechRecognition
() constructor. We also create a new speech grammar list to contain our grammar, using the SpeechGrammarList
() constructor. var recognition = new SpeechRecognition
(); var speechRecognitionList = new SpeechGrammarList
(); We add our grammar to the list using the SpeechGrammarList.addFromString
() method. This accepts as parameters the string we want to add, plus optionally a weight value that specifi...
...ts = false; recognition.maxAlternatives = 1; Starting the speech recognition After grabbing references to the output <div> and the HTML element (so we can output diagnostic messages and update the app background color later on), we implement an onclick handler so that when the screen is tapped/clicked, the speech recognition service will start. This is achieved by calling SpeechRecognition.start
(). The forEach
() method is used to output colored indicators showing what colors to try saying. var diagnostic = document.querySelector('.output'); var bg = document.querySelector('html'); var hints = document.querySelector('.hints'); var colorHTML= ''; colors.forEach(function(v, i, a){ console.log(v, i); colorHTML += '<span style="background-color:' + v + ';"> ' + v + ' </span>'; }); hints.i...
...tput'); var bg = document.querySelector('html'); var hints = document.querySelector('.hints'); var colorHTML= ''; colors.forEach(function(v, i, a){ console.log(v, i); colorHTML += '<span style="background-color:' + v + ';"> ' + v + ' </span>'; }); hints.innerHTML = 'Tap/click then say a color to change the background color of the app. ...
...And 14 more matches
Cross-browser audio basics - Developer guides
's an example of creating an <audio> element, setting the media to play, playing and pausing, and then playing from 5 seconds into the audio: var myAudio = document.createElement('audio'); if (myAudio.canPlayType('audio/mpeg')) { myAudio.setAttribute('src','audiofile.mp3'); } if (myAudio.canPlayType('audio/ogg')) { myAudio.setAttribute('src','audiofile.ogg'); } alert('play'); myAudio.play
(); alert('stop'); myAudio.pause
(); alert('play from 5 seconds in'); myAudio.currentTime = 5; myAudio.play
(); Let's explore the available properties and methods in more detail. play The play
() method is used to tell the audio to play. It takes no parameters. myAudio.play
(); pause The pause
() method is used to tell the audio to pause. It takes no parameters. myAudio.pause
(); Note: There ...
...ethods in more detail. play The play
() method is used to tell the audio to play. It takes no parameters. myAudio.play
(); pause The pause
() method is used to tell the audio to pause. It takes no parameters. myAudio.pause
(); Note: There is no stop method -- to implement a stop function, you'd have to pause the media then set the currentTime property value to 0. canPlayType The canPlayType
() method asks the browser whether a certain audio file type is supported. It takes the mime type of the type to check as a parameter. if (myAudio.canPlayType('audio/mpeg')) { // It's supported. // Do something here! } canPlayType
() returns one of three values: probably maybe "" (an empty string) In practice, we usually check if the result is true or false. Non-empty strings are true. ...
...lse. Non-empty strings are true. Note: A very early spec specified that the browser should return no instead of an empty string, but thankfully the number of people using older browsers that implement this version of the spec are few and far between. currentTime The currentTime property gets or sets the current time the audio should play at. This is useful in many ways, for example since play
() does not take a parameter we need to set the point to play from separately if we don't want it to be 0. The value of currentTime is a number which represents the time in seconds. if (myAudio.currentTime > 5) { myAudio.currentTime = 3; } volume The volume property allows us to set the audio volume, as a number between 0 and 1. // set the volume at 50% myAudio.volume = 0.5; Creating your ow...
...And 14 more matches
Regular expressions - JavaScript
This chapter describes JavaScript regular expressions. ...
...This chapter describes JavaScript regular expressions. ...
...This chapter describes JavaScript regular expressions. ...
...And 14 more matches
Array - JavaScript
using the index position let first = fruits[0] // Apple let last = fruits[fruits.length - 1] // Banana Loop over an Array fruits.forEach(function(item, index, array) { console.log(item, index) }) // Apple 0 // Banana 1 Add an item to the end of an Array let newLength = fruits.push('Orange') // ["Apple", "Banana", "Orange"] Remove an item from the end of an Array let last = fruits.pop
() // remove Orange (from the end) // ["Apple", "Banana"] Remove an item from the beginning of an Array let first = fruits.shift
() // remove Apple from the front // ["Banana"] Add an item to the beginning of an Array let newLength = fruits.unshift('Strawberry') // add to the front // ["Strawberry", "Banana"] Find the index of an item in the Array fruits.push('Mango') // ["Strawberry", "Bana...
... = 2 let removedItems = vegetables.splice(pos, n) // this is how to remove items, n defines the number of items to be removed, // starting at the index position specified by pos and progressing toward the end of array. console.log(vegetables) // ["Cabbage", "Carrot"] (the original array is changed) console.log(removedItems) // ["Turnip", "Radish"] Copy an Array let shallowCopy = fruits.slice
() // this is how to make a copy // ["Strawberry", "Mango"] Accessing array elements JavaScript arrays are zero-indexed. The first element of an array is at index 0, and the last element is at the index value equal to the value of the array's length property minus 1. Using an invalid index number returns undefined. let arr = ['this is the first element', 'this is the second element', 'this is t...
...Nevertheless, trying to access an element of an array as follows throws a syntax error because the property name is not valid: console.log(arr.0) // a syntax error There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a digit cannot be referenced with dot notation and must be accessed using bracket notation. Fo...
...And 14 more matches
BigUint64Array - JavaScript
The BigUint64Array typed array represents an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0n. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ...
... Instance properties BigUint64Array.prototype.buffer Returns the ArrayBuffer referenced by the BigUint64Array. ...
...tatic properties BigUint64Array.BYTES_PER_ELEMENT Returns a number value of the element size. 8 in the case of a BigUint64Array. BigUint64Array.name Returns the string value of the constructor name. In the case of the BigUint64Array type this is "BigUint64Array". Static methods BigUint64Array.from
() Creates a new BigUint64Array from an array-like or iterable object. See also Array.from
(). BigUint64Array.of
() Creates a new BigUint64Array with a variable number of arguments. See also Array.of
(). Instance properties BigUint64Array.prototype.buffer Returns the ArrayBuffer referenced by the BigUint64Array. This is fixed at construction time and thus read only. BigUint64Array.prototype.byteLength Returns the length (in bytes) of the BigUint64Array from the start of its ArrayB...
...And 14 more matches
Spread syntax (...) - JavaScript
rals (new in ECMAScript 2018): let objClone = { ...obj }; Rest syntax (parameters) Rest syntax looks exactly like spread syntax. In a way, rest syntax is the opposite of spread syntax. Spread syntax "expands" an array into its elements, while rest syntax collects multiple elements and "condenses" them into a single element. See rest parameters. Examples Spread in function calls Replace apply
() It is common to use Function.prototype.apply
() in cases where you want to use the elements of an array as arguments to a function. function myFunction(x, y, z) { } const args = [0, 1, 2]; myFunction.apply(null, args); With spread syntax the above can be written as: function myFunction(x, y, z) { } const args = [0, 1, 2]; myFunction(...args); Any argument in the argument list can use spread s...
...s: function myFunction(x, y, z) { } const args = [0, 1, 2]; myFunction(...args); Any argument in the argument list can use spread syntax, and the spread syntax can be used multiple times. ...
...ion myFunction(x, y, z) { } const args = [0, 1, 2]; myFunction(...args); Any argument in the argument list can use spread syntax, and the spread syntax can be used multiple times. ...
...And 14 more matches
Example - SVG: Scalable Vector Graphics
First, each mote tries to move towards the cursor, and second each mote tries to move away from the average mote position. Combined, we get this very natural looking behavior. </...
...Velocity:</label> <input id='max_velocity' value='15'/> <br/> <label>Attraction to cursor:</label> <input id='attract_cursor' value='6'/> <br/> <label>Repulsion from peers:</label> <input id='repel_peer' value='5'/> <br/> </p> </form> <script type='text/javascript'> <![CDATA[ // Array of motes var motes; // Get the display element. ...
...pulsion from peers:</label> <input id='repel_peer' value='5'/> <br/> </p> </form> <script type='text/javascript'> <![CDATA[ // Array of motes var motes; // Get the display element. function Display
() { return document.getElementById('display'); } // Determine dimensions of the display element. ...
...And 14 more matches
ui/button/action - Archive of obsolete content
(state) { console.log("You clicked '" + state.label + "'"); button.removeListener("click", firstClick); button.on("click", subsequentClicks); } function subsequentClicks(state) { console.log("You clicked '" + state.label + "' again"); } The listener is passed a state object that contains all the button's properties. You can generate click events programmatically with the button's click
() method. Disabling buttons You can disable a button by setting its disabled property to true. A disabled button will not generate click events and its icon will appear disabled: Updating state You can update all the button's properties except for its id. By default, the button has global state: that is, its properties are the same across all open windows and tabs, and updating them updates ...
...e click events and its icon will appear disabled: Updating state You can update all the button's properties except for its id. By default, the button has global state: that is, its properties are the same across all open windows and tabs, and updating them updates the button's state across all open windows and tabs. You can set state to be specific to a window or tab using the button's state
() method. To set state like this, call state
() with 2 parameters: the first parameter is a window or tab object or as a shorthand, the string "window" for the currently active window, or the string "tab" for the currently active tab the second parameter is an object containing the state properties you wish to update. Here's an add-on with a button that disables itself when you click it, but o...
...After that, any attempts to access any of its properties or to call any of its methods will throw...
...And 13 more matches
Bookmarks - Archive of obsolete content
Creating a new bookmark var win = myBrowser.contentWindow; // Get the bookmarks service const BMSVC = Components.classes["@mozilla.org/browser/bookmarks-service;1"] .getService(Components.interfaces.nsIBookmarksService); // Create the bookmark BMSVC.createBookmarkInContainer(win.document.title, // bookmark name win.location.href.toString
(), // URI of the bookmark null, // shortcut win.document.title, // description win.document.characterSet, // charset null, // postData bookmarksService.getBookmarksToolbarFolder
(), // bookmark folder 0); // in...
...For example, to create a new folder in the Bookmarks menu: var menuFolder = bmsvc.bookmarksMenuFolder; // Bookmarks menu folder var newFolderId = bmsvc.createFolder(menuFolder, "Folder name here", bmsvc.DEFAULT_INDEX); This code locates the Bookmarks menu's folder, then creates a new folder named "Folder name here" in it. Specifying DEFAULT_INDEX as the index at which to insert the new...
...eates a new folder named "Folder name here" in it. Specifying DEFAULT_INDEX as the index at which to insert the new folder places it at the end of the list. You can easily change this code to insert the new folder into the bookmarks toolbar by changing bookmarksMenuFolder to another folder attribute. Creating a new bookmark To create a new bookmark, use the nsINavBookmarksService.insertBookmark
() method. The URI for the bookmark needs to be specified using an nsIURI object. var ios = Components.classes["@mozilla.org/network/io-service;1"] .getService(Components.interfaces.nsIIOService); var uri = ios.newURI("http://google.com/", null, null); var newBkmkId = bmsvc.insertBookmark(newFolderId, uri, bmsvc.DEFAULT_INDEX, ""); This example instantiates the nsIIOService an...
...And 13 more matches
File I/O - Archive of obsolete content
tWithPath("/home"); Note: The path should be in the "native" form (for example"C:\\Windows"). If you need to use file:// URIs as initializers, see discussion of nsIIOService below. Note: You can still get a file object even if the specified file does not exist, and no exception will be thrown. An exception is thrown only when methods that require the file to exist are called, e.g., isDirectory
(), moveTo
(), and so on. Getting files in special directories Components.utils.import("resource://gre/modules/FileUtils.jsm"); // get the "data.txt" file in the profile directory var file = FileUtils.getFile("ProfD", ["data.txt"]); Or the same without using FileUtils.jsm: // Get profile directory. var file = Components.classes["@mozilla.org/file/directory_service;1"]. getService(Co...
...ile you can use initWithPath("/") on UNIX-like systems (Linux, Mac) to get the root of the file system, there's no such root on Windows. ...
...NIX-like systems (Linux, Mac) to get the root of the file system, there's no such root on Windows. However, you can enumerate available drives using the following code: Components.utils.import("resource://gre/modules/FileUtils.jsm"); var root = new FileUtils.File("\\\\."); var drivesEnum = root.directoryEntries, drives = []; while (drivesEnum.hasMoreElements
()) { drives.push(drivesEnum.getNext
(). QueryInterface(Components.interfaces.nsILocalFile).path); } Creating Folders FileUtils.getDir
() can create a folder automatically if it doesn't exist yet: Components.utils.import("resource://gre/modules/FileUtils.jsm"); var dir = FileUtils.getDir("ProfD", ["DIR"], true); The above example creates a folder called "DIR" in the user's profile folder. You can also create a directory expli...
...And 13 more matches
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
for the best that you don't use any filenames that have whitespace in them. Usage An RPN calculator We're going to implement a simple RPN3 calculator in JavaScript to see how this can be used. On the program side, we'll create a class called RpnCalc. First we'll sketch out a simple interface for it (Listing 1). Save this as a file called calc.js. Listing 1: calc.js (stage 1) function RpnCalc
() { } RpnCalc.prototype = { init: function
() { }, push: function(val) { }, plus: function
() { }, pop: function
() { } } Implement the addition operation Create test case Begin by creating the test case. First, select the menu item Tools:Mozlab:Open MozUnit Runner to bring up the MozUnit window. Select the menu item File:New, and save test_calc.js in the same directory as the file...
...start with testhoge are recognized as tests. MozUnit uses the same kind of notation, but you can also make the string the method name, making the test self-documenting. Pretty clever. ...
...but you can also make the string the method name, making the test self-documenting. Pretty clever. ...
...And 13 more matches
Code snippets - Archive of obsolete content
eItem) .rootTreeItem .QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIDOMWindow); // Obtain a reference to Sync's Tabs "engine." let tabsEngine = Weave.Service.engineManager.get("tabs"); // Iterate over each client having data. for each (let client in tabsEngine.getAllClients
()) { for each (let tab in client.tabs) { let url = tab.urlHistory[0]; // Load the tab via the tabbed browser API. mainWindow.gBrowser.addTab(url); } } Partially corrupt a server Components.utils.import("resource://services-sync/main.js"); Components.utils.import("resource://services-sync/resource.js"); function deletePath(path) { let resource = new Resource(Weave.Service.sto...
...ad the tab via the tabbed browser API. ...
...payload.engines[ENGINE].version = 0; // Or any other version number you like. envelope.payload = JSON.stringify(payload); r.put(JSON.stringify(envelope)); Generate new keys // Clients always wipe the server when they generate new key...
...And 13 more matches
button - Archive of obsolete content
have different behavior for how the states are adjusted, set the autoCheck attribute to false and adjust the state with a script. The type attribute must be set to checkbox for buttons with a check state. Constants for the possible values for this attribute are in the nsIDOMXULButtonElement interface. checked Type: boolean Indicates whether the element is checked or not. Use hasAttribute
() to determine whether this attribute is set instead of getAttribute
(). For buttons, the type attribute must be set to checkbox or radio for this attribute to have any effect. command Type: id Set to the id of a command element that is being observed by the element. crop Type: one of the values below If the label of the element is too big to fit in its given sp...
... Type: boolean Gets and sets the value of the open attribute. orient Type: string Gets and sets the value of the orient attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. type Type: string Gets and sets the value of the type attribute. ...
... Gets and sets the value of the open attribute. orient Type: string Gets and sets the value of the orient attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. type Type: string Gets and sets the value of the type attribute. ...
...And 13 more matches
checkbox - Archive of obsolete content
bel="Enable JavaScript" checked="true"/> <checkbox label="Enable Java" checked="false"/> Attributes accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. checked Type: boolean Indicates whether the element is checked or not. Use hasAttribute
() to determine whether this attribute is set instead of getAttribute
(). For buttons, the type attribute must be set to checkbox or radio for this attribute to have any effect. command Type: id Set to the id of a command element that is being observed by the element. crop Type: one of the values below If the label of the element is too big to fit in its given sp...
... disabled Type: boolean Gets and sets the value of the disabled attribute. src Type: URL Gets and sets the value of the src attribute. label Type: string Gets and sets the value of the label attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. ...
... Type: boolean Gets and sets the value of the disabled attribute. src Type: URL Gets and sets the value of the src attribute. label Type: string Gets and sets the value of the label attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. ...
...And 13 more matches
colorpicker - Archive of obsolete content
sets the value of the disabled attribute. open Type: boolean Returns true if the popup for a button-type colorpicker is open. Set this property to true to open the popup or false to close the popup. tabIndex Type: integer Gets and sets the value of the tabindex attribute. ...
... of the disabled attribute. open Type: boolean Returns true if the popup for a button-type colorpicker is open. Set this property to true to open the popup or false to close the popup. tabIndex Type: integer Gets and sets the value of the tabindex attribute. ...
.... open Type: boolean Returns true if the popup for a button-type colorpicker is open. Set this property to true to open the popup or false to close the popup. tabIndex Type: integer Gets and sets the value of the tabindex attribute. ...
...And 13 more matches
description - Archive of obsolete content
s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
...d attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
... tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...And 13 more matches
editor - Archive of obsolete content
editortype, src, type Properties accessibleType, commandManager, contentDocument, contentWindow, docShell, editingSession, editortype, webBrowserFind, webNavigation Methods getEditor, getHTMLEditor, makeEditable Examples This example shows how to made the editor editable by setting the designMode property of the loaded HTML document: <script language="javascript"> function initEditor
(){ // this function is called to set up the editor var editor = document.getElementById("myEditor"); editor.contentDocument.designMode = 'on'; } </script> <editor id="myEditor" editortype="html" src="about:blank" flex="1" type="content-primary"/> Once editable, the document can have special formatting and other HTML pieces added to it using the document.execCommand method: var editor = d...
...LEditor( window ) Return type: nsIHTMLEditor Returns the HTML editing interface for the editor which contains methods for manipulating an HTML document. Pass the editor's contentWindow as the argument. makeEditable( editortype, waitForLoad ) Return type: no return value This function enables editing for an editor. Specify text or html as the editortype. ...
... ) Return type: nsIHTMLEditor Returns the HTML editing interface for the editor which contains methods for manipulating an HTML document. Pass the editor's contentWindow as the argument. makeEditable( editortype, waitForLoad ) Return type: no return value This function enables editing for an editor. Specify text or html as the editortype. ...
...And 13 more matches
menu - Archive of obsolete content
s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
...ot. This property is read only. This property is available for menuitem and menuseparator elements in Firefox 3. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...ty is read only. This property is available for menuitem and menuseparator elements in Firefox 3. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...And 13 more matches
menupopup - Archive of obsolete content
en shown. This state will occur during the popupshowing event. hiding: The popup is about to be hidden. This state will occur during the popuphiding event. triggerNode Type: nsIDOMNode This read-only property holds the DOM node that generated the event triggering the opening of the popup. The value is null if the popup isn't open. ...
...state will occur during the popupshowing event. hiding: The popup is about to be hidden. This state will occur during the popuphiding event. triggerNode Type: nsIDOMNode This read-only property holds the DOM node that generated the event triggering the opening of the popup. The value is null if the popup isn't open. ...
...e popupshowing event. hiding: The popup is about to be hidden. This state will occur during the popuphiding event. triggerNode Type: nsIDOMNode This read-only property holds the DOM node that generated the event triggering the opening of the popup. The value is null if the popup isn't open. ...
...And 13 more matches
menuseparator - Archive of obsolete content
s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
...in Firefox 3. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
... tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...And 13 more matches
notification - Archive of obsolete content
s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
...e priority attribute. type Type: string Gets and sets the value of the type attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...ibute. type Type: string Gets and sets the value of the type attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...And 13 more matches
panel - Archive of obsolete content
closed: The popup is closed and not visible. open: The popup is open and visible on screen. showing: A request has been made to open the popup, but it has not yet been shown. This state will occur during the popupshowing event. hiding: The popup is about to be hidden. This state will occur during the popuphiding event. ...
... popup is closed and not visible. open: The popup is open and visible on screen. showing: A request has been made to open the popup, but it has not yet been shown. This state will occur during the popupshowing event. hiding: The popup is about to be hidden. This state will occur during the popuphiding event. ...
...isible. open: The popup is open and visible on screen. showing: A request has been made to open the popup, but it has not yet been shown. This state will occur during the popupshowing event. hiding: The popup is about to be hidden. This state will occur during the popuphiding event. ...
...And 13 more matches
radio - Archive of obsolete content
s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
...in Firefox 3. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
... tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...And 13 more matches
radiogroup - Archive of obsolete content
s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
... by the user. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
... tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...And 13 more matches
richlistitem - Archive of obsolete content
s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
...in Firefox 3. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
... tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
...And 13 more matches
toolbarbutton - Archive of obsolete content
have different behavior for how the states are adjusted, set the autoCheck attribute to false and adjust the state with a script. The type attribute must be set to checkbox for buttons with a check state. Constants for the possible values for this attribute are in the nsIDOMXULButtonElement interface. checked Type: boolean Indicates whether the element is checked or not. Use hasAttribute
() to determine whether this attribute is set instead of getAttribute
(). For buttons, the type attribute must be set to checkbox or radio for this attribute to have any effect. command Type: id Set to the id of a command element that is being observed by the element. crop Type: one of the values below If the label of the element is too big to fit in its given spac...
... Type: boolean Gets and sets the value of the open attribute. orient Type: string Gets and sets the value of the orient attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. type Type: string Gets and sets the value of the type attribute. ...
...lean Gets and sets the value of the open attribute. orient Type: string Gets and sets the value of the orient attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. type Type: string Gets and sets the value of the type attribute. ...
...And 13 more matches
tooltip - Archive of obsolete content
closed: The popup is closed and not visible. open: The popup is open and visible on screen. showing: A request has been made to open the popup, but it has not yet been shown. This state will occur during the popupshowing event. hiding: The popup is about to be hidden. This state will occur during the popuphiding event. ...
...he popup is closed and not visible. open: The popup is open and visible on screen. showing: A request has been made to open the popup, but it has not yet been shown. This state will occur during the popupshowing event. hiding: The popup is about to be hidden. This state will occur during the popuphiding event. ...
... visible. open: The popup is open and visible on screen. showing: A request has been made to open the popup, but it has not yet been shown. This state will occur during the popupshowing event. hiding: The popup is about to be hidden. This state will occur during the popuphiding event. ...
...And 13 more matches
Animations and tweens - Game development
ns and tweens in our game. Animations In Phaser, animations, involve taking a spritesheet from an external source and displaying the sprites sequentially. As an example, we will make the ball wobble when it hits something. First of all, grab the spritesheet from Github and save it in your /img directory. ...
...e it in your /img directory. Next, we will load the spritesheet -- put the following line at the bottom of your preload
() function: game.load.spritesheet('ball', 'img/wobble.png', 20, 20); Instead of loading a single image of the ball we can load the whole spritesheet -- a collection of different images. We will show the sprites sequentially to create the illusion of animation. The spritesheet
() method's two extra paremeters determine the width and height of each single frame in the given spritesheet file, indicating to the program how to chop it up to get the individual frames. ...
...can load the whole spritesheet -- a collection of different images. We will show the sprites sequentially to create the illusion of animation. The spritesheet
() method's two extra paremeters determine the width and height of each single frame in the given spritesheet file, indicating to the program how to chop it up to get the individual frames. ...
...And 13 more matches
Advanced text formatting - Learn web development
in: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); const output = document.querySelector('.output'); const code = textarea.value; const userEntry = textarea.value; function updateCode
() { output.innerHTML = textarea.value; } reset.addEventListener('click', function
() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode
(); }); solution.addEventListener('click', function
() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; }...
...area.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode
(); }); solution.addEventListener('click', function
() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Show solution'; } updateCode
(); }); const htmlSolution = '<dl>\n <dt>Bacon</dt>\n <dd>The glue that binds the world together.</dd>\n <dt>Eggs</dt>\n <dd>The glue that binds the cake together.</dd>\n <dt>Coffee</dt>\n <dd>The drink that gets the world running in the morning.</dd>\n <dd>A light brown color.</dd>\n</dl>'; const solutionEntry = htmlSolution; textarea.addEventListener('input', updateCode); window.addEventListener...
...k that gets the world running in the morning.</dd>\n <dd>A light brown color.</dd>\n</dl>'; const solutionEntry = htmlSolution; textarea.addEventListener('input', updateCode); window.addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault
(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur
(); } }; function insertAtCaret(text) { const scrollPos = textarea.scrollTop; const caretPos = textarea.selectionStart; const front = (textarea.value).substring(0, caretPos); const back = (textarea.value).substring(textarea.selectionEnd, textarea.value.length); textarea.value = front + text + back; caretPos ...
...And 13 more matches
Nonblocking IO In NSPR
I/O operations that may potentially block. In the nonblocking io model, a file descriptor may be marked as nonblocking. An io function on a nonblocking file descriptor either succeeds immediately or fails immediately with <tt>PR_WOULD_BLOCK_ERROR</tt>. A single thread is sufficient to attend to multiple nonblocking file descriptors simultaneously. Typically, this central thread invokes <tt>PR_Poll
()</tt> on a set of nonblocking file descriptors. (Note: <tt>PR_Poll
()</tt> also works with blocking file descriptors, although it is less useful in the blocking io model.) When <tt>PR_Poll
()</tt> reports that a file descriptor is ready for some io operation, the central thread invokes that io function on the file descriptor. Creating a Nonblocking Socket Only sockets can be made nonblocking. Reg...
...a file descriptor is ready for some io operation, the central thread invokes that io function on the file descriptor. Creating a Nonblocking Socket Only sockets can be made nonblocking. Regular files always operate in blocking mode. This is not a serious constraint as one can assume that disk I/O never blocks. ...
...ng a Nonblocking Socket Only sockets can be made nonblocking. Regular files always operate in blocking mode. This is not a serious constraint as one can assume that disk I/O never blocks. Fundamentally, this constraint is due to the fact that nonblocking I/O and <tt>select
()</tt> are only available to sockets on some platforms (e.g., Winsock). In NSPR, a new socket returned by <tt>PR_NewTCPSocket
()</tt> or <tt>PR_NewUDPSocket
()</tt> is always created in blocking mode. ...
...And 13 more matches
Creating the Component Code
egisterFactoryLocation that are required to implement the module and factory classes in your code. Identifiers in XPCOM The series of nsIID variables initialized here are actually classes created for handing the 128-bit identifiers that XPCOM uses to support contractual relationships between the client and component interfaces. The variable kIFactoryIID, for example, provides methods like Equals
() that can be used to facilitate comparisons in the code, as in the following example from the Mozilla source: Using Class Methods to Handle Identifiers if (aIID.Equals(NS_GET_IID(nsISupports))) { *aInstancePtr = (void*)(nsISupports*)this; NS_ADDREF_THIS
(); return NS_OK; } Finally, SAMPLE_CID is an example of a CID that uniquely identifies the component. All of the 128-bit numbers used in...
...To unregister, all you have to do is pass the CID and the file which is passed into UnregisterSelf. Creating an Instance of Your Component The example above uses a CID, but after the component is registered, anyone that uses XPCOM can access your classes if they know either the contract ID or CID. (Note that RegisterSelf method above do...
... nsISupports* sample; compManager->CreateInstance(kSampleCID, nsnull, kISupportsIID, (void**)&sample); In the above snippet, we assume that the component manager has been initialized. In many cases this value is passed in or easily accessible. If not, it can always be obtained by a call to NS_GetComponentManager
(). A listing of this and other global XPCOM functions is in the XPCOM API Reference. The first parameter of the call to CreateInstance specifies the component the client code is looking for, which is the same value passed to RegisterFactoryLocation. The next parameter is for aggregation, which the WebLock component does not support. The third parameter is the interface used to talk to the componen...
...And 13 more matches
Introduction to XPCOM for the DOM
ften represented by a class), without worrying about the details of the implementation. If you know a class implements an interface, just use the methods in the interface, and you don't have to care if the implementation of the interface (the concrete class) changes. XPCOM pushes this concept to the extreme. Pure virtual methods are declared with the following syntax: virtual nsresult FunctionFoo
() = 0; An interface is thus simply a C++ class where all the member functions are declared as pure virtual functions. An interface can also be defined using XPIDL. This is described in Section 1.E, "How to add an interface". Since an interface doesn't have any implementation, it has to be implemented by a non-abstract class -- a concrete class. If the interface is called nsIFoo and the class is ...
...n nsCOMPtr is used like an usual pointer to an interface in most cases. An usual pointer to an interface nsIFoo is declared as follows: nsIFoo *fooptr; An nsCOMPtr to the same nsIFoo interface is declared as follows: nsCOMPtr<nsIFoo> fooptr; The rest of the use of nsCOMPtr's is described in the next Section. For more information about nsCOMPtr's, please read the User's Guide. QueryInterface
() Consider again the class nsFoo that implements two interfaces, nsIFoo and nsIFoo2: class nsFoo : public nsIFoo, public nsIFoo2 Let's assume an instance of nsFoo was somehow created (this assertion is 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 ...
...he 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 interface assigned to the address of a real object, and you can thus now call methods defined on nsIFoo through ifooptr. Here is some example code. nsCOMPtr<nsIFoo> ifooptr; GetInterfaceIFoo(getter_AddRefs(ifooptr)); ifooptr->FunctionOfnsIFoo
(); The peculiar syntax, getter_AddRefs(pointer), is the nsCOMPtr counterpart to the usual "&" (address-of) C operator. It means that the Getter method will call the AddRef method for you. This is a contract between the caller, who says "I don't add a reference to this object because you have already done it", and the callee who says "I add a reference to this object, so don't do it!". If both the...
...And 13 more matches
IAccessibleTable2
[propget] HRESULT selectedColumns([out, size_is(, nColumns)] long selectedColumns, [out] long nColumns ); [propget] HRESULT selectedRows([out, size_is(, nRows)] long selectedRows, [out] long nRows ); HRESULT selectRow([in] long row ); [propget] HRESULT summary([out] IUnknown accessible ); HRESULT unselectColumn([in] long column ); HRESULT unselectRow([in] long row ); Methods caption
() Returns the caption for the table. The returned object could be an IAccessible or an IAccessible2. [propget] HRESULT caption( [out] IUnknown accessible ); Parameters accessible If the table has a caption then a reference to it is returned, else a null pointer is returned. Return value S_FALSE if there is nothing to return, [out] value is null. S_OK. cellAt
() Returns the accessible object at ...
...d row index for which to retrieve the cell. column The 0 based column index for which to retrieve the cell. cell If both row and column index are valid then the corresponding accessible object is returned that represents the requested cell regardless of whether the cell is currently visible (on the screen). Return value E_INVALIDARG if bad [in] passed, [out] value is null. S_OK. columnDescription
() Returns the description text of the specified column in the table. [propget] HRESULT columnDescription( [in] long column, [out] BSTR description ); Parameters column The 0 based index of the column for which to retrieve the description. description Returns the description text of the specified column in the table if such a description exists. Otherwise a null pointer is returned. Return va...
...scription ); Parameters column The 0 based index of the column for which to retrieve the description. description Returns the description text of the specified column in the table if such a description exists. Otherwise a null pointer is returned. Return value E_INVALIDARG if bad [in] passed, [out] value is null. S_FALSE if there is nothing to return, [out] value is null. S_OK. isColumnSelected
() Returns a boolean value indicating whether the specified column is completely selected. [propget] HRESULT isColumnSelected( [in] long column, [out] boolean isSelected ); Parameters column 0 based index of the column for which to determine whether it is selected. isSelected Returns true if the specified column is selected completely and false otherwise. Return value E_INVALIDARG if bad [in]...
...And 13 more matches
inIDOMUtils
Constant Value Description EXCLUDE_SHORTHANDS (1<<0) INCLUDE_ALIASES (1<<1) Content state flags The content state flags are used in a bitmask. ...
... nsIDOMNodeList getChildrenForNode( in nsIDOMNode aNode, in boolean aShowingAnonymousContent ); Parameters aNode A DOM Node for which to retrieve the style nodes. aShowingAnonymousContent Whether you are interested in the XBL flattened tree. Return value A DOM NodeList of the child nodes. ...
... If you have requested anonymous content, then if the element has an XBL binding then this will be the binding's anonymous nodes, otherwise if the element is itself an anonymous node containing an insertion point then this will be a list combining the element's explicit children from its binding parent's anonymous nodes and any children inserted as a result of the insertion point. ...
...And 13 more matches
nsIMsgMessageService
aCopyListener already knows about the destination folder. void CopyMessage(in string aSrcURI, in nsIStreamListener aCopyListener, in boolean aMoveMessage, in nsIUrlListener aUrlListener, in nsIMsgWindow aMsgWindow, out nsIURI aURL); Parameters ...
...cURI The string url of the message to copy. aCopyListener An nsIStreamListener to be notified of copy events. aMoveMessage Set to true if you want the message to be moved. false leaves it as just a copy. aUrlListener A nsIUrlListener to be notified of url events. aMsgWindow nsIMsgWindow for progress and status feedback Return values aURL The new nsIURI of the message. CopyMessages
() Copy multiple messages at a time. See CopyMessage [noscript] void CopyMessages(in nsMsgKeyArrayPtr keys, in nsIMsgFolder srcFolder, in nsIStreamListener aCopyListener, in boolean aMoveMessage, in nsIUrlListener aUrlListener, in nsIMsgWindow aMsgW...
...eters keys An array of message keys to be copied. srcFolder aCopyListener An nsIStreamListener to be notified of copy events. aMoveMessage Set to true if you want the message to be moved. false leaves it as just a copy. aUrlListener An nsIUrlListener aMsgWindow nsIMsgWindow for progress and status feedback Return values aURL The new nsIURI of the message. (?) DisplayMessage
() When you want a message displayed.... void DisplayMessage(in string aMessageURI, in nsISupports aDisplayConsumer, in nsIMsgWindow aMsgWindow, in nsIUrlListener aUrlListener, in string aCharsetOverride, out nsIURI aURL); Parameters aMessageURI A uri representing the message to display.
...And 13 more matches
nsIWebProgressListener
, in unsigned long aStateFlags, in nsresult aStatus); void onStatusChange(in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage); Constants State transition flags These flags indicate the various states that requests may transition through as they are being loaded. These flags are mutually exclusive. For any given request, onStateChange
() is called once with the STATE_START flag, zero or more times with the STATE_TRANSFERRING flag or once with the STATE_REDIRECTING flag, and then finally once with the STATE_STOP flag. Note: For document requests, a second STATE_STOP is generated (see the description of STATE_IS_WINDOW for more details). Constant Value Description STATE_START 0x00000001 This flag ind...
...EDIRECTING flag, and then finally once with the STATE_STOP flag. Note: For document requests, a second STATE_STOP is generated (see the description of STATE_IS_WINDOW for more details). Constant Value Description STATE_START 0x00000001 This flag indicates the start of a request. This flag is set when a request is initiated. The request is complete when onStateChange
() is called for the same request with the STATE_STOP flag set. STATE_REDIRECTING 0x00000002 This flag indicates that a request is being redirected. The request passed to onStateChange
() is the request that is being redirected. When a redirect occurs, a new request is generated automatically to process the new request. Expect a corresponding STATE_START event for the new request, and ...
...flag indicates that data for a request is being transferred to an end consumer. This flag indicates that the request has been targeted, and that the user may start seeing content corresponding to the request. STATE_NEGOTIATING 0x00000008 This flag is not used. STATE_STOP 0x00000010 This flag indicates the completion of a request. The aStatus parameter to onStateChange
() indicates the final status of the request. State type flags These flags further describe the entity for which the state transition is occurring. These flags are not mutually exclusive (that is an onStateChange
() event may indicate some combination of these flags). Constant Value Description STATE_IS_REQUEST 0x00010000 This flag indicates that the state trans...
...And 13 more matches
nsIZipReader
code pages, such as UTF-8. This can mismatch characters in the nsIZipReader API. Starting in Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7), the nsIZipReader API supports a limited 8 bit code page usage. All functions now pass the filenames (both in and out) as AUTF8String. So you can now read and extract what you wrote with nsIZipWriter. ...
...rd 10.0 / SeaMonkey 2.7), the nsIZipReader API supports a limited 8 bit code page usage. All functions now pass the filenames (both in and out) as AUTF8String. So you can now read and extract what you wrote with nsIZipWriter. If you show filenames from the findEntries
() result in the user interface, the character matching is only fine on UTF-8 ZIP archives. ...
... void test(in AUTF8String aEntryName); void test(in string aEntryName); Obsolete since Gecko 10 Attributes Attribute Type Description file nsIFile The file that represents the zip with which this zip reader was initialized. Read only. manifestEntriesCount PRUint32 The number of entries in the manifest. Read only. ...
...And 13 more matches
Type conversion
Implicit convert In js-ctypes, data could be converted implicitly when passing to or returning from a FunctionType call, or setting pointer content, an array element or a struct field. ...
... Implicit convert In js-ctypes, data could be converted implicitly when passing to or returning from a FunctionType call, or setting pointer content, an array element or a struct field. ...
...lement or a struct field. ...
...And 13 more matches
console - Web APIs
dow.console, and can be referenced as simply console. For example: console.log("Failed to open the specified link") This page documents the Methods available on the console object and gives a few Usage examples. Note: This feature is available in Web Workers. Note: The actual console interface is defined as all lower case (i.e. not Console), for historical reasons. ...
...open the specified link") This page documents the Methods available on the console object and gives a few Usage examples. Note: This feature is available in Web Workers. Note: The actual console interface is defined as all lower case (i.e. not Console), for historical reasons. Methods console.assert
() Log a message and stack trace to console if the first argument is false. console.clear
() Clear the console. console.count
() Log the number of times this line has been called with the given label. console.countReset
() Resets the value of the counter with the given label. console.debug
() Outputs a message to the console with the log level debug. console.dir
() Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosur...
...ine has been called with the given label. console.countReset
() Resets the value of the counter with the given label. console.debug
() Outputs a message to the console with the log level debug. console.dir
() Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects. console.dirxml
() Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not possible. console.error
() Outputs an error message. You may use string substitution and additional arguments with this method. console.exception
() An alias for error
(). console.group
() Creates a new inline group, indenting all following output by another level. To ...
...And 13 more matches
FileHandle API - Web APIs
e (was previously FileHandle.) LockedFile FileRequest It also has connections with the File API, especially the File and Blob interfaces. Basic operations Create a FileHandle Because the intent is to allow the storage of files through IndexedDB, creating a FileHandle instance requires an IndexedDB Database. var IDBReq = indexedDB.open("myFileStorageDataBase"); IDBReq.onsuccess = function
(){ var DB = this.result; var buildHandle = DB.mozCreateFileHandle("test.txt", "plain/text"); buildHandle.onsuccess = function
(){ var myFileHandle = this.result; console.log('handle', myFileHandle); }; }; mozCreateFileHandle
() takes two arguments: a name and an optional type. Both of these are just descriptive and are not used by the database. However, they are important for the ...
... "temporary file" that exists only while you hold the FileHandle instance. If you want a file to survive a page refresh/app relaunch, you need to store the handle in a more permanent location, like the database itself. See File storage below to learn more about this. Perform read and write operations To read or write within a handled file, it is required to get a LockedFile. The FileHandle.open
() method provides such an object which can be readonly or readwrite. Any attempt to perform a write action on a readonly LockedFile object will fail. Writing There are three possible writing operations on a locked file: write : It's an arbitrary writing method which starts writing in the file at the LockedFile.location byte. append : This operation always writes content at the end of the file...
...g in the file at the LockedFile.location byte. append : This operation always writes content at the end of the file. truncate : This operation keeps the nth-first bytes of the file and removes the rest. // Get a LockedFile object from the handle var myFile = myFileHandle.open('readwrite'); // Start a writing operation var writing = myFile.append('Some content'); writing.onsuccess = function
() { console.log('Writing operation successful'); } writing.onerror = function
() { console.log('Something goes wrong in the writing process: ' + this.error); } Reading It's possible to directly write the content of a LockedFile object without using an intermediate File object and a FileReader object. The LockedFile interface provides a readAsText method and a readAsArrayBuffer method. Thos...
...And 13 more matches
Pointer Lock API - Web APIs
ot release the mouse until an explicit API call is made or the user uses a specific release gesture. It is not limited by browser or screen boundaries. It continues to send events regardless of mouse button state. It hides the cursor. Method/properties overview This section provides a brief description of each property and method related to the pointer lock specification. requestPointerLock
() The Pointer lock API, similar to the Fullscreen API, extends DOM elements by adding a new method, requestPointerLock
(). As it has recently unprefixed, you would currently declare it something like this, for example if you wanted to request pointer lock on a canvas element: canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock; canvas.
... API, similar to the Fullscreen API, extends DOM elements by adding a new method, requestPointerLock
(). As it has recently unprefixed, you would currently declare it something like this, for example if you wanted to request pointer lock on a canvas element: canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock; canvas.requestPointerLock
() If a user has exited pointer lock via the default unlock gesture, or pointer lock has not previously been entered for this document, an event generated as a result of an engagement gesture must be received by the document before requestPointerLock will succeed. ...
...estPointerLock
() If a user has exited pointer lock via the default unlock gesture, or pointer lock has not previously been entered for this document, an event generated as a result of an engagement gesture must be received by the document before requestPointerLock will succeed. (from https://w3c.github.io/pointerlock/#extensions-to-the-element-interface) pointerLockElement and exitPointerLock
() The Pointer lock API also extends the Document interface, adding both a new property and a new method. The new property is used for accessing the currently locked element (if any), and is named pointerLockElement and the new method on Document is exitPointerLock
() and, as the name implies, it is used to exit the pointer lock. The pointerLockElement property is useful for determining if any elem...
...And 13 more matches
CSS reference - CSS: Cascading Style Sheets
cript names where they differ from the CSS standard names. ...
...names where they differ from the CSS standard names. ...
...-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-function@annotationannotation
()attr
()B::backdropbackdrop-filterbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-size<basic-shape>::before (:before)bleed (@page)<blend-mode>block-sizeblur
()borderborder-blockborder-block-colorborder-block-endborder-block-end-colorborder-block-end-styleborder-block-end-widthborder-block-startborder-block-start-colorborder-block-start-styleborder-block-start-widthborder-block-styleborder-block-widthborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-e...
...And 13 more matches
content - CSS: Cascading Style Sheets
465, #9198e5); /* alt text for generated content, added in the Level 3 specification */ content: url("http://www.example.com/test.png") / "This is the alt text"; /* values below can only be applied to generated content using ::before and ::after */ /* <string> value */ content: "prefix"; /* <counter> values */ content: counter(chapter_counter); content: counters(section_counter, "."); /* attr
() value linked to the HTML attribute value */ content: attr(value string); /* Language- and position-dependent keywords */ content: open-quote; content: close-quote; content: no-open-quote; content: no-close-quote; /* Except for normal and none, several values can be used simultaneously */ content: open-quote chapter_counter; /* Global values */ content: inherit; content: initial; content: unset...
...s to none for the ::before and ::after pseudo-elements. <string> Specifies the "alt text" for the element. This value can be any number of text characters. Non-Latin characters must be encoded using their Unicode escape sequences: for example, \000A9 represents the copyright symbol. <image> An <image>, denoted by the <url> or <gradient> 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 spe...
...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 indicated style (decimal by default). attr(x) The value of the element's attribute x as a string. ...
...And 13 more matches
Public class fields - JavaScript
formation below. Both static and instance public fields are writable, enumerable, and configurable properties. As such, unlike their private counterparts, they participate in prototype inheritance. Syntax class ClassWithInstanceField { instanceField = 'instance field' } class ClassWithStaticField { static staticField = 'static field' } class ClassWithPublicInstanceMethod { publicMethod
() { return 'hello world' } } Examples Public static fields Public static fields are useful when you want a field to exist only once per class, not on every class instance you create. This is useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances. Public static fields are declared using the static keyword. They are added to the class con...
...Public static fields are useful when you want a field to exist only once per class, not on every class instance you create. This is useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances. Public static fields are declared using the static keyword. They are added to the class constructor at the time of class evaluation using Object.defineProperty
(). They are accessed again from the class constructor. class ClassWithStaticField { static staticField = 'static field' } console.log(ClassWithStaticField.staticField) // expected output: "static field" Fields without initializers are initialized to undefined. class ClassWithStaticField { static staticField } console.assert(ClassWithStaticField.hasOwnProperty('staticField')) console.log(C...
...og(SubClassWithStaticField.baseStaticField) // expected output: "base field" When initializing fields, this refers to the class constructor. You can also reference it by name, and use super to get the superclass constructor (if one exists). ...
...And 13 more matches
BigInt64Array - JavaScript
The BigInt64Array typed array represents an array of 64-bit signed integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0n. Once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ...
... Instance properties BigInt64Array.prototype.buffer Returns the ArrayBuffer referenced by the BigInt64Array. ...
...t. Static properties BigInt64Array.BYTES_PER_ELEMENT Returns a number value of the element size. 8 in the case of a BigInt64Array. BigInt64Array.name Returns the string value of the constructor name. In the case of the BigInt64Array type, this is "BigInt64Array". Static methods BigInt64Array.from
() Creates a new BigInt64Array from an array-like or iterable object. See also Array.from
(). BigInt64Array.of
() Creates a new BigInt64Array with a variable number of arguments. See also Array.of
(). Instance properties BigInt64Array.prototype.buffer Returns the ArrayBuffer referenced by the BigInt64Array. This is fixed at construction time and thus read only. BigInt64Array.prototype.byteLength Returns the length (in bytes) of the BigInt64Array from the start of its ArrayBuffer.
...And 13 more matches
Symbol - JavaScript
A symbol value may be used as an identifier for object properties; this is the data type's primary purpose, although other use-cases exist, such as enabling opaque data types, or serving as an implementation-supported unique identifier in general. ...
... A symbol value may be used as an identifier for object properties; this is the data type's primary purpose, although other use-cases exist, such as enabling opaque data types, or serving as an implementation-supported unique identifier in general. ...
... A symbol value may be used as an identifier for object properties; this is the data type's primary purpose, although other use-cases exist, such as enabling opaque data types, or serving as an implementation-supported unique identifier in general. ...
...And 13 more matches
Introduction to using XPath in JavaScript - XPath
r We create a namespace resolver using the createNSResolver method of the document object. var nsResolver = document.createNSResolver( contextNode.ownerDocument == null ? contextNode.documentElement : contextNode.ownerDocument.documentElement ); Or alternatively by using the <code>createNSResolver</code> method of a <code>XPathEvaluator</code> object. <pre> var xpEvaluator = new XPathEvaluator
(); var nsResolver = xpEvaluator.createNSResolver( contextNode.ownerDocument == null ? contextNode.documentElement : contextNode.ownerDocument.documentElement ); </pre> And then pass document.evaluate, the nsResolver variable as the namespaceResolver parameter. Note: XPath defines QNames without a prefix to match only elements in the null namespace. There is no way in XPath to pick up the default n...
...ameter. Note: XPath defines QNames without a prefix to match only elements in the null namespace. There is no way in XPath to pick up the default namespace as applied to a regular element reference (e.g., p[@id='_myid'] for xmlns='http://www.w3.org/1999/xhtml'). To match default elements in a non-null namespace, you either have to refer to a particular element using a form such as ['namespace-uri
()='http://www.w3.org/1999/xhtml' and name
()='p' and @id='_myid'] (this approach works well for dynamic XPath's where the namespaces might not be known) or use prefixed name tests, and create a namespace resolver mapping the prefix to the namespace. Read more on how to create a user-defined namespace resolver, if you wish to take the latter approach. Notes Adapts any DOM node to resolve namespaces...
... Note however, that if the document is mutated (the document tree is modified) between iterations that will invalidate the iteration and the invalidIteratorState property of XPathResult is set to true, and a NS_ERROR_DOM_INVALID_STATE_ERR exception is thrown. Iterator Examp...
...And 13 more matches
Communicating With Other Scripts - Archive of obsolete content
Content Scripts Content scripts loaded into the same document at the same time using the same method can interact with each other directly as well as with the web content itself. However, content scripts which have been loaded into different documents cannot interact directly with each other. Cont...
... your main.js file, or any other modules in your add-on other content scripts loaded by your add-on page scripts (that is, scripts embedded in the web page or included using <script> tags) main.js Your content scripts can communicate with your add-on's "main.js" (or any other modules you're written for your add-on) by sending it messages, using either the port.emit
() API or the postMessage
() API. See the articles on using postMessage
() and using port for details. Content Scripts Content scripts loaded into the same document at the same time using the same method can interact with each other directly as well as with the web content itself. However, content scripts which have been loaded into different documents cannot interact directly with each other. Content scripts that have bee...
...he same method can interact with each other directly as well as with the web content itself. However, content scripts which have been loaded into different documents cannot interact directly with each other. Content scripts that have been loaded into the same document by different methods, or the same method called more than once, can pass messages directly to each other using the DOM postMessage
() API or a CustomEvent. Any two content scripts can communicate by using the main add-on script to manually relay messages between the content scripts. For example: If an add-on creates a single panel object and loads several content scripts into the panel at the same time, then they can interact with each other. If an add-on creates two panel objects and loads a script into each one, they can...
...And 12 more matches
Miscellaneous - Archive of obsolete content
It also collapses consecutive whitespaces into a single whitespace, and returns at most 150 characters, mak...
...It also collapses consecutive whitespaces into a single whitespace, and returns at most 150 characters, making it idea...
...It also collapses consecutive whitespaces into a single whitespace, and returns at most 150 characters, making it ideal to display text in context me...
...And 12 more matches
Tree Box Objects - Archive of obsolete content
<< PreviousNext >> This section will describe the tree box object used to handle how a tree is displayed. About the Tree Box Object Box objects were described in an earlier section. The tree box object is a specialized box object used specifically for trees. The tree box implements the TreeBoxObject interface. Redrawing the Tree We already saw the rowCountChanged
() function of the tree box object in the previous section. It is used to indicate that one or more rows have been added to the tree or removed from the tree. The tree will redraw the affected area. You don't need to call the rowCountChanged
() function when a row has simply changed in some way, for example if a cell's label changes. In this case, there are other drawing functions that can be used. The simplest is ...
...the previous section. It is used to indicate that one or more rows have been added to the tree or removed from the tree. The tree will redraw the affected area. You don't need to call the rowCountChanged
() function when a row has simply changed in some way, for example if a cell's label changes. In this case, there are other drawing functions that can be used. The simplest is to call invalidateRow
() which will redraw a specific row in the tree. The tree will call the view to get the updated data and update the contents of the tree on screen. Other redrawing functions are invalidateCell
() to redraw only a single cell invalidateColumn
() to redraw a column invalidateRange
() to redraw a range of rows invalidate
() to redraw the entire tree. Note that redrawing does not occur until the ca...
...rface(Components.interfaces.nsITreeBoxObject) as shown in the code examples on this page because: let boxobject = tree.treeBoxObject; Note: is equivalent to: let boxobject = tree.boxObject; boxobject.queryInterface("Components.interfaces.nsITreeBoxObject"); Scrolling the Tree You can also scroll the tree using four different methods, similar to those available for listboxes. ...
...And 12 more matches
toolbox - Archive of obsolete content
array of elements An array of external toolbars; that is, toolbar elements that should be considered to be members of this toolbox, even if they are not actually children of the toolbox. palette Firefox only Type: element The toolbarpalette within the toolbox. toolbarset Firefox only Type: element The toolbarset within the toolbox. ...
...nts An array of external toolbars; that is, toolbar elements that should be considered to be members of this toolbox, even if they are not actually children of the toolbox. palette Firefox only Type: element The toolbarpalette within the toolbox. toolbarset Firefox only Type: element The toolbarset within the toolbox. ...
...oolbars; that is, toolbar elements that should be considered to be members of this toolbox, even if they are not actually children of the toolbox. palette Firefox only Type: element The toolbarpalette within the toolbox. toolbarset Firefox only Type: element The toolbarset within the toolbox. ...
...And 12 more matches
nsIContentPolicy - Archive of obsolete content
42 / Thunderbird 42 / SeaMonkey 2.39) You can observe content that is being loaded into your browser by implementing nsIContentPolicy. This interface can be very useful if you are developing a content-aware plugin (blocking ads or altering the look of content, for example), or if you want to stop or allow user-browsed URLs. Warning: Do not block the caller in your implementations of shouldLoad
() or shouldProcess
() (for example, by launching a dialog to prompt the user for something).") Note: In reality, much of this interface is defined in the nsIContentPolicyBase interface, but for now is documented here until someone has time to split things up. Method overview short shouldLoad(in unsigned long aContentType, in nsIURI aContentLocation, in nsIURI aRequestOrigin, in nsISup...
...r example, <iframe> and <frame> elements). Note: Gecko uses TYPE_INTERNAL_FRAME and TYPE_INTERNAL_IFRAME in order to discern the difference internally. These types are mapped to TYPE_SUBDOCUMENT before being passed into the implementation of the content policy and should not be used outside Gecko code. TYPE_REFRESH 8 Indicates a timed refresh. ...
...erence internally. These types are mapped to TYPE_SUBDOCUMENT before being passed into the implementation of the content policy and should not be used outside Gecko code. TYPE_REFRESH 8 Indicates a timed refresh. shouldLoad
() will never get this, because it does not represent content to be loaded (the actual load triggered by the refresh will go through shouldLoad
() as expected). shouldProcess
() will get this for, for example <meta> Refresh elements and HTTP Refresh headers. TYPE_XBL 9 Indicates an XBL binding request, triggered either by -moz-binding CSS property or the Document.addBinding
() method. TYPE_PING 10 Indicates a ping triggered by a click on an <a> element using the ping attribute. TYPE_XMLHTTPREQUEST ...
...And 12 more matches
Processing XML with E4X - Archive of obsolete content
ects. The syntax is designed to be familiar to JavaScript programmers, but E4X does not provide a direct mapping from XML to native JavaScript objects; just the illusion of one. It is possible to interpolate variables into an XML literal to create an element name (or to create content). var h = 'html'; var text = "Here's some text"; var doc = <{h}><body>{text}</body></{h}>; alert(doc.toXMLString
()); // Gives <html> <body>Here's some text</body> </html> Working with attributes XML literal syntax has a significant advantage over the XML constructor when you need to create markup dynamically. With E4X it is easy to embed dynamic values in markup. Variables and expressions can be used to create attribute values by simply wrapping them with braces ({}) and omitting quotation marks that wou...
...a}>"hi"</foo>; Upon execution the variable is evaluated and quotes are automatically added where appropriate. The preceding example would result in an XML object which looks like this: <foo bar="2">"hi"</foo>. In attribute substitution, quotation marks are escaped as " while apostrophes are handled normally. var b = 'He said "Don\'t go there."'; var el = <foo a={b}/>; alert(el.toXMLString
()); // Gives: <foo a="He said "Don't go there.""/> Less than and ampersand signs are escaped into their entity equivalents. Since a greater than sign is not escaped, it is possible to get an XML error if the CDATA closing sequence (]]>) is included. It is not possible to directly interpolate variables amidst other literal (or variable) attribute content, however (e.g., bar="a{var1}{var...
... once (e.g., <b {a}>.) After executing the above example, the variable languages references an XML object corresponding to the <languages> node in the XML document. ...
...And 12 more matches
Track the score and win - Game development
really cool, but to be even more awesome the game could award points for every brick a user hits, and keep count of the total score. Counting the score If you can see your score throughout the game, eventually you can impress your friends. You need a variable to record the score. ...
...and keep count of the total score. Counting the score If you can see your score throughout the game, eventually you can impress your friends. You need a variable to record the score. Add the following into your JavaScript, after the rest of your variables: var score = 0; You also need a drawScore
() function, to create and update the score display. ...
...e. Counting the score If you can see your score throughout the game, eventually you can impress your friends. You need a variable to record the score. Add the following into your JavaScript, after the rest of your variables: var score = 0; You also need a drawScore
() function, to create and update the score display. ...
...And 12 more matches
Getting started with HTML - Learn web development
el { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode
() { output.innerHTML = textarea.value; } reset.addEventListener('click', function
() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode
(); }); solution.addEventListener('click', function
() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; }...
...area.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode
(); }); solution.addEventListener('click', function
() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Show solution'; } updateCode
(); }); var htmlSolution = '<em>This is my text.</em>'; var solutionEntry = htmlSolution; textarea.addEventListener('input', updateCode); window.addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault
(); insertAtCaret('\t'); } if ...
... my text.</em>'; var solutionEntry = htmlSolution; textarea.addEventListener('input', updateCode); window.addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault
(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur
(); } }; function insertAtCaret(text) { var scrollPos = textarea.scrollTop; var caretPos = textarea.selectionStart; var front = (textarea.value).substring(0, caretPos); var back = (textarea.value).substring(textarea.selectionEnd, textarea.value.length); textarea.value = front + text + back; caretPos = caretPos + text.length; textarea.selectionStart = caretPos; textarea.selectionE...
...And 12 more matches
Vue conditional rendering: editing existing todos - Learn web development
ally-hidden">editing {{label}}</span> </button> <button type="submit" class="btn btn__primary"> Save <span class="visually-hidden">edit for {{label}}</span> </button> </div> </form> </template> <script> export default { props: { label: { type: String, required: true }, id: { type: String, required: true } }, data
() { return { newLabel: this.label }; }, methods: { onSubmit
() { if (this.newLabel && this.newLabel !== this.label) { this.$emit("item-edited", this.newLabel); } }, onCancel
() { this.$emit("edit-cancelled"); } } }; </script> <style scoped> .edit-label { font-family: Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-fo...
... class="visually-hidden">{{label}}</span> </button> </div> </div> </template> We've added a wrapper <div> around the whole template for layout purposes. We've also added "Edit" and "Delete" buttons: The "Edit" button, when clicked, will toggle displaying the ToDoItemEditForm component so we can use it to edit our todo item, via an event handler function called toggleToItemEditForm
(). This handler will set an isEditing flag to true. To do that, we'll need to first define it inside our data
() property. The "Delete" button, when clicked, will delete the todo item via an event handler function called deleteToDo
(). In this handler we'll emit an item-deleted event to our parent component so the list can be updated. Let's define our click handlers, and the necessary isEditing fl...
...we'll need to first define it inside our data
() property. The "Delete" button, when clicked, will delete the todo item via an event handler function called deleteToDo
(). In this handler we'll emit an item-deleted event to our parent component so the list can be updated. Let's define our click handlers, and the necessary isEditing flag. ...
...And 12 more matches
Gecko info for Windows accessibility vendors
please read the MSAA documentation on MSDN if you are unfamiliar with these. in general we abbreviate by removing redundant words. For example, we may say EVENT_ALERT instead of the full EVENT_SYSTEM_ALERT. MSAA tree vs. DOM tree - what's the relation? The MSAA tree and the DOM tree are parallel structures, although the MSAA tree is a subset of the DOM tree. QueryService
() can be used to switch between the interfaces (IAccessible, ISimpleDOMDocument, ISimpleDOMNode and ISimpleDOMText). If there is no MSAA node for a DOM node, or vice-versa, QueryService
() will return null. Anything that is focusable or conveys important information about the structure of the document is exposed in the MSAA tree of IAccessibles. Windows Applications Based on the Gecko Layout...
...that is, to read the entire contents. These roles can occur on content because of the new Accessible DHTML technology which allows the author to specify the type of document or container. Once you know that you have a document, go up the ancestor chain of windows until you see a MozillaContentWindowClass or a MozillaUIWindowClass. ...
...w
() to get the root IAccessible for the content, and begin traversing the tree from there. Gecko also helps determine when to load a new window by firing two EVENT_STATE_CHANGE's on the root ROLE_DOCUMENT accessible -- the first state change indicates the document pane is now busy loading. The second state change indicates the document pane has finished. When handling the event, use get_accState
() to check the STATE_BUSY flag. When the document has finished loading the busy flag will be cleared. MSAA Support: IAccessible Methods To use MSAA with Gecko, you'll need the tools and docs that come with the Active Accessibility 2.0 SDK Tools. The method AccessibleObjectFromWindow
() will get you the root IAccessible corresponding to the top level window. Hold on to this root IAccessible, and ...
...And 12 more matches
Download
A Download object represents a single download, with associated state and actions. This object is transient, though it can be included in a DownloadList so that it can be managed by the user interface and persisted across sessions. A new Download object can be created using the Downloads.createDownload
() function. Method overview Promise start
(); Promise launch
(); Promise showContainingDirectory
(); Promise cancel
(); Promise removePartialData
(); Promise whenSucceeded
(); Promise finalize([optional] boolean aRemovePartialData); Properties Attribute Type Description canceled Read only boolean Indicates that the download has been canceled. This property can become true, then it ca...
...Temporary files or part files may still exist even if they are expected to be deleted, until the stopped property becomes true. ...
...he download is started. To have any effect, this property must be set before starting the download. Resetting this property to false after the download has already started will not remove any partial data. Note: If this property is set to true, care should be taken that partial data is removed before the reference to the download is discarded. ...
...And 12 more matches
JNI.jsm
th 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. Unlike C from js-ctypes, defining constants is not a manual magic number method in JNI, it is declared the same way we define functions, except in JNI they are called fields. Method overview CData GetForThread
(); CData LoadClass(CData aJenv, String aClassFullyQualifiedName, [optional] Object aDeclares); CData NewString(CData aJenv, String aStr); String ReadString(CData aJenv, CData aJavaString); void UnloadClasses
(); Methods GetForThread
() blah blah CData GetForThread
(); Parameters This function does not take any arguments. Return value blah blah LoadCl...
... CData LoadClass(CData aJenv, String aClassFullyQualifiedName, [optional] Object aDeclares); CData NewString(CData aJenv, String aStr); String ReadString(CData aJenv, CData aJavaString); void UnloadClasses
(); Methods GetForThread
() blah blah CData GetForThread
(); Parameters This function does not take any arguments. Return value blah blah LoadClass
() blah blah CData LoadClass( aJenv, aFullyQualifiedName, [optional] Object aDeclares ); Parameters aJenv The return value of GetForThread
(). aFullyQualifiedName A sig of a typed array or the name of the class that would be used in a signature, but without the surrounding L and ;. If it is the sig of a typed array such as '[I' then aDeclares must not be declared. See the section "Wo...
...ckoInterface we would use "org/mozilla/gecko/GeckoAppShell$GeckoInterface". aDeclares optional If this is omitted, then aFullyQualifiedName must be an array type. If this is provided, then aFullyQualifiedName must be a class name. A required object that contains up to five fields of key names: constructors, fields, static_fields, methods, and static_methods. Return value blah blah NewString
() blah blah CData NewString( aJenv, aStr ); Parameters aJenv The return value of GetForThread
(). aStr A Javascript String, use any encoding desired. Return value blah blah ReadString
() blah blah String ReadString( aJenv, aJavaString ); Parameters aJenv The return value of GetForThread
(). aJavaString A CData object that is a Java string. Return Value A Javascript Strin...
...And 12 more matches
Scripting Java
External Packages and Classes External packages and classes can also be used as in Rhino. Make sure your .jar or .class file is on you classpath then you may import them into your JavaScript application. These packages are likely not in the java package, so you'll need to prefix the package name with "Packages." For example, to import the org.mozilla.javascript package you could use importPackage
() as follows: $ java org.mozilla.javascript.tools.shell.Main js> importPackage(Packages.org.mozilla.javascript); js> Context.currentContext; org.mozilla.javascript.Context@bb6ab6 Occasionally, you will see examples that use the fully qualified name of the package instead of importing using the importPackage
() method. This is also acceptable, it just takes more typing. Using a fully qualified nam...
...s more typing. Using a fully qualified name, the above example would look as follows: $ java org.mozilla.javascript.tools.shell.Main js> jsPackage = Packages.org.mozilla.javascript; [JavaPackage org.mozilla.javascript] js> jsPackage.Context.currentContext; org.mozilla.javascript.Context@bb6ab6 Alternatively, if you want to import just one class from a package you can do so using the importClass
() method. The above examples could be expressed as follows: $ java org.mozilla.javascript.tools.shell.Main js> importClass(Packages.org.mozilla.javascript.Context); js> Context.currentContext; org.mozilla.javascript.Context@bb6ab6 Working with Java Now that we can access Java classes, the next logical step is to create an object. This works just as in Java, with the use of the new operator: js...
...xamples could be expressed as follows: $ java org.mozilla.javascript.tools.shell.Main js> importClass(Packages.org.mozilla.javascript.Context); js> Context.currentContext; org.mozilla.javascript.Context@bb6ab6 Working with Java Now that we can access Java classes, the next logical step is to create an object. ...
...And 12 more matches
How to embed the JavaScript engine
// time you're spinning the event loop JS::RootedObject global(cx, JS_NewGlobalObject(cx, &global_class, nullptr)); if (!global) return 1; JS::RootedValue rval(cx); { // Scope for JSAutoCompartment JSAutoCompartment ac(cx, global); JS_InitStandardClasses(cx, global); const char *script = "'hello'+'world, it is '+new Date
()"; const char *filename = "noname"; int lineno = 1; bool ok = JS_EvaluateScript(cx, global, script, strlen(script), filename, lineno, rval.address
()); if (!ok) return 1; } JSString *str = rval.toString
(); printf("%s\n", JS_EncodeString(cx, str)); } JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown
(); return 0...
...e class of the global object. */ static JSClass global_class = { "global", JSCLASS_GLOBAL_FLAGS, JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, nullptr, nullptr, nullptr, nullptr, JS_GlobalObjectTraceHook }; int main(int argc, const char *argv[]) { JS_Init
(); JSRuntime *rt = JS_NewRuntime(8L * 1024 * 1024, JS_USE_HELPER_THREADS); if (!rt) return 1; JSContext *cx = JS_NewContext(rt, 8192); if (!cx) return 1; { // Scope for our various stack objects (JSAutoRequest, RootedObject), so they all go // out of scope before we JS_DestroyContext. JSAutoRequest ar(cx); // In practice, you would want to exit th...
...ou're spinning the event loop JS::RootedObject global(cx, JS_NewGlobalObject(cx, &global_class, nullptr, JS::FireOnNewGlobalHook)); if (!global) return 1; JS::RootedValue rval(cx); { // Scope for JSAutoCompartment JSAutoCompartment ac(cx, global); JS_InitStandardClasses(cx, global); const char *script = "'hello'+'world, it is '+new Date
()"; const char *filename = "noname"; int lineno = 1; bool ok = JS_EvaluateScript(cx, global, script, strlen(script), filename, lineno, &rval); if (!ok) return 1; } JSString *str = rval.toString
(); printf("%s\n", JS_EncodeString(cx, str)); } JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown
(); return 0; } Spi...
...And 12 more matches
Manipulating bookmarks using Places
For example, to create a new folder in the Bookmarks menu: var menuFolder = bmsvc.bookmarksMenuFolder; // Bookmarks menu folder var newFolderId = bmsvc.createFolder(menuFolder, "Folder name here", bmsvc.DEFAULT_INDEX); This code locates the Bookmarks menu's folder, then creates a new folder named "Folder name here" in it. Specifying DEFAULT_INDEX as the index at which to insert the new...
...eates a new folder named "Folder name here" in it. Specifying DEFAULT_INDEX as the index at which to insert the new folder places it at the end of the list. You can easily change this code to insert the new folder into the bookmarks toolbar by changing bookmarksMenuFolder to another folder attribute. Creating a new bookmark To create a new bookmark, use the nsINavBookmarksService.insertBookmark
() method. The URI for the bookmark needs to be specified using an nsIURI object. var ios = Components.classes["@mozilla.org/network/io-service;1"] .getService(Components.interfaces.nsIIOService); var uri = ios.newURI("http://google.com/", null, null); var newBkmkId = bmsvc.insertBookmark(newFolderId, uri, bmsvc.DEFAULT_INDEX, ""); This example instantiates the nsIIOService an...
... var ios = Components.classes["@mozilla.org/network/io-service;1"] .getService(Components.interface...
...And 12 more matches
nsIAppStartup
Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) Implemented by: @mozilla.org/toolkit/app-startup;1. ...
... by: @mozilla.org/toolkit/app-startup;1. ...
...oolean createStartupState(in long aWindowWidth, in long aWindowHeight); Obsolete since Gecko 1.9.1 void destroyHiddenWindow
(); void doProfileStartup(in nsICmdLineService aCmdLineService, in boolean canInteract); Obsolete since Gecko 1.9.1 void ensure1Window(in nsICmdLineService aCmdLineService); Obsolete since Gecko 1.9.1 void enterLastWindowClosingSurvivalArea
(); void exitLastWindowClosingSurvivalArea
(); void getStartupInfo
(); void hideSplashScreen
(); Obsolete since Gecko 1.9.1 void initialize(in nsISupports nativeAppSupportOrSplashScreen); Obsolete since Gecko 1.9.1 void quit(in PRUint32 aMode); void restartInSafeMode(in PRUint32 aQuitMode); void run
(); Attributes Attribute...
...And 12 more matches
nsILocalFile
d appendRelativeNativePath(in ACString relativeFilePath); Native code only! void appendRelativePath(in AString relativeFilePath); ACString getRelativeDescriptor(in nsILocalFile fromFile); void initWithFile(in nsILocalFile aFile); void initWithNativePath(in ACString filePath); Native code only! ...
...CString relativeFilePath); Native code only! void appendRelativePath(in AString relativeFilePath); ACString getRelativeDescriptor(in nsILocalFile fromFile); void initWithFile(in nsILocalFile aFile); void initWithNativePath(in ACString filePath); Native code only! void initWithPath(in AString filePath); void launch
(); PRLibraryStar load
(); Native code only! ...
...Read only. followLinks PRBool Determines whether or not the nsILocalFile will automatically...
...And 12 more matches
nsINavHistoryService
dBookmark(in nsIURI aURI); void markPageAsFollowedLink(in nsIURI aURI); void markPageAsTyped(in nsIURI aURI); boolean canAddURI(in nsIURI aURI); long long addVisit(in nsIURI aURI, in PRTime aTime, in nsIURI aReferringURI, in long aTransitionType, in boolean aIsRedirect, in long long aSessionID); Obsolete since Gecko 22.0 nsINavHistoryQuery getNewQuery
(); nsINavHistoryQueryOptions getNewQueryOptions
(); nsINavHistoryResult executeQuery(in nsINavHistoryQuery aQuery, in nsINavHistoryQueryOptions options); nsINavHistoryResult executeQueries([array,size_is(aQueryCount)] in nsINavHistoryQuery aQueries, in unsigned long aQueryCount, in nsINavHistoryQueryOptions options); void queryStringToQueries(in AUTF8String aQuery...
... permanent redirect. TRANSITION_REDIRECT_TEMPORARY 6 This transition type is set when the transition was a temporary redirect. TRANSITION_DOWNLOAD 7 This transition type is set when the transition is a download. TRANSITION_FRAMED_LINK 8 This transition type is set when the user followed a link that loaded a page in a frame. Methods getPageTitle
() This method retrieves the original title of the page. AString getPageTitle( in nsIURI aURI ); Parameters aURI The page whose title needs to be retrieved. Return value Returns the original title of the page. markPageAsFollowedBookmark
() This method is just like markPageAsTyped (in nsIBrowserHistory, also implemented by the history service), but for bookmarks. It declares that the gi...
... by the history service), but for bookmarks. It declares that the given URI is being opened as a result of following a bookmark. If this URI is loaded soon after this message has been received, that transition will be marked as following a bookmark. void markPageAsFollowedBookmark( in nsIURI aURI ); Parameters aURI The page that is to be marked as followed by a bookmark. markPageAsTyped
() This method designates the URL as having been explicitly typed in by the user, so it can be used as an autocomplete result. It is called by the URL bar when the user types in a URL. This can be and is called before the page is actually added to history, since the page isn't added until it actually starts loading. The typed flag affects the URL bar autocomplete. This will cause the transition typ...
...And 12 more matches
nsIScriptableIO
irefox 3) Inherits from: nsISupports A scriptable IO object can be used in an extension or chrome code by referring to the global IO object. ...
...Files are located by starting at a known directory, specified using a location key string. For example, if the location key is specified as ...
...Files are located by starting at a known directory, specified using a location key string. ...
...And 12 more matches
nsISelection
plemented by: ????????????????????????????????????? ...
...????????????????????"] .createInstance(Components.interfaces.nsISelection); Method overview void addRange(in nsIDOMRange range); void collapse(in nsIDOMNode parentNode, in long offset); [noscript,notxpcom,nostdcall] boolean collapsed
(); void collapseNative(in nsIDOMNode parentNode, in long offset); Native code only! void collapseToEnd
(); void collapseToStart
(); boolean containsNode(in nsIDOMNode node, in boolean partlyContained); void deleteFromDocument
(); void extend(in nsIDOMNode parentNode, in long offset); void extendNative(in nsIDOMNode parentNode, in long offset); Native code only! nsIDOMRange getRangeAt(in long index); void modify(in DOMString alter, in DOMSt...
...Read only. anchorOffset long The offset w...
...And 12 more matches
nsISelectionPrivate
nherits from: nsISupports Last changed in Gecko 35 (Firefox 35 / Thunderbird 35 / SeaMonkey 2.32) Warning: The content of this article may be out of date. This page wasn't updated since the initial import in 2011. See the idl file linked above for up-to-date information. ...
...ate. This page wasn't updated since the initial import in 2011. See the idl file linked above for up-to-date information. ...
... import in 2011. See the idl file linked above for up-to-date information. ...
...And 12 more matches
nsIXULTemplateBuilder
Each query may be accompanied by one or more <rule> elements. These rules are evaluated by the template builder for each result produced by the query. A rule consists of conditions that cause a rule to be either accepted or rejected. The condition syntax allows for common conditional handling; additional filtering may be applied by adding a custom filter to a rule with the builder's addRuleFilter
() method. If a result passes a rule's conditions, this is considered a match, and the content within the rule's <action> body is inserted as a sibling of the <template>, assuming the template builder creates real DOM content. Only one rule will match a result. For a tree builder, for example, the content within the action body is used to create the tree rows instead. A matching result must have its...
...a result passes a rule's conditions, this is considered a match, and the content within the rule's <action> body is inserted as a sibling of the <template>, assuming the template builder creates real DOM content. Only one rule will match a result. For a tree builder, for example, the content within the action body is used to create the tree rows instead. A matching result must have its ruleMatched
() method called. When a result no longer matches, the result's hasBeenRemoved
() method must be called. Optionally, the rule may have a <bindings> section which may be used to define additional variables to be used within an action body. Each of these declared bindings must be supplied to the query processor via its addBinding
() method. The bindings are evaluated after a rule has matched. Templates ...
...The bindings are evaluated after a rule has matched. Templates may generate content recursively, using the previous iteration's results as reference point to invoke the same queries. Since the reference point is different, different output will typically be generated. The reference point nsIXULTemplateResult object for the first iteration is determined by calling the query processor's translateRef
() method using the value of the root node's ref attribute. This object may be retrieved later via the builder's rootResult property. For convenience, each reference point as well as all results implement the nsIXULTemplateResult interface, allowing the result objects from each iteration to be used directly as the reference points for the next iteration. When using multiple queries, each may generat...
...And 12 more matches
Pixel manipulation with canvas - Web APIs
All pixels are preset to transparent black (all zeroes i.e rgba(0,0,0,0)). You can also create a new ImageData object with the same dimensions as the object specified by anotherImageData. The new object's pixels...
...ord, canvasWidth); const [redIndex, greenIndex, blueIndex, alphaIndex] = colorIndices; You may also access the size of the pixel array in bytes by reading the Uint8ClampedArray.length attribute: var numBytes = imageData.data.length; Creating an ImageData object To create a new, blank ImageData object, you should use the createImageData
() method. There are two versions of the createImageData
() method: var myImageData = ctx.createImageData(width, height); This creates a new ImageData object with the specified dimensions. All pixels are preset to transparent black (all zeroes i.e rgba(0,0,0,0)). You can also create a new ImageData object with the same dimensions as the object specified by anotherImageData. The new object's pixels are all preset to transparent black. This does not copy...
...new ImageData object with the same dimensions as the object specified by anotherImageData. The new object's pixels are all preset to transparent black. This does not copy the image data! var myImageData = ctx.createImageData(anotherImageData); Getting the pixel data for a context To obtain an ImageData object containing a copy of the pixel data for a canvas context, you can use the getImageData
() method: var myImageData = ctx.getImageData(left, top, width, height); This method returns an ImageData object representing the pixel data for the area of the canvas whose corners are represented by the points (left,top), (left+width, top), (left, top+height), and (left+width, top+height). The coordinates are specified in canvas coordinate space units. Note: Any pixels outside the canvas are r...
...And 12 more matches
Guide to the Fullscreen API - Web APIs
This article demonstrates how to use the Fullscreen API to place a given element into full-screen mode, as well as how to detect when the browser enters or exits full-screen mode. Activating full-screen mode Given an element that you'd like to present in full-screen mode (such as a <video>, for example), you can present it in full-screen mode by simply calling its requestFullscreen
() method. ...
... Presentation differences It's worth noting a key difference here between the Gecko and WebKit implementations at this time: Gecko automatically adds CSS rules to the element to stretch it to fill the screen: "width: 100%; height: 100%". ...
... Presentation differences It's worth noting a key difference here between the Gecko and WebKit implementations at this time: Gecko automatically adds CSS rules to the element to stretch it to fill the screen: "width: 100%; height: 100%". WebKit doesn't do this; instead, it centers the fullscreen element at the same size in a screen that's otherwise black. ...
...And 12 more matches
Node - Web APIs
Principal Obsolete since Gecko 46 A nsIPrincipal representing the node principal. Node.prefix Read only Is a DOMString representing the namespace prefix of the node, or null if no prefix is specified. Node.rootNode Read only Returns a Node object representing the topmost node in the tree, or the current node if it's the topmost node in the tree. This has been replaced by Node.getRootNode
(). ...
...aced by Node.getRootNode
(). Methods In addition to the properties below, Node inherits methods from its parent, EventTarget. Node.appendChild(childNode) Adds the specified childNode argument as the last child to the current node. If the argument referenced an existing node on the DOM tree, the node will be detached from its current position and attached at the new position. Node.cloneNode
() Clone a Node, and optionally, all of its contents. By default, it clones the content of the node. Node.compareDocumentPosition
() Compares the position of the current node against another node in any other document. Node.contains
() Returns a Boolean value indicating whether or not a node is a descendant of the calling node. ...
... and attached at the new position. Node.cloneNode
() Clone a Node, and optionally, all of its contents. By default, it clones the content of the node. Node.compareDocumentPosition
() Compares the position of the current node against another node in any other document. Node.contains
() Returns a Boolean value indicating whether or not a node is a descendant of the calling node. Node.getBoxQuads
() Returns a list of the node's CSS boxes relative to another node. Node.getRootNode
() Returns the context object's root which optionally includes the shadow root if it is available. Node.hasChildNodes
() Returns a Boolean indicating whether or not the element has any child nodes. Node.insertBefore
() Inserts a Node before the reference node as a child of a specified parent node. Node.isDef...
...And 12 more matches
Using the Resource Timing API - Web APIs
and response (responseStart and responseEnd). This example also calculates the time from the start of the fetch and request start phases (fetchStart and requestStart, respectively), until the response has ended (responseEnd). This timing data provides a detailed profile of the resource loading phases and this data can be used to help identify performance bottlenecks. ...
...dedBodySize property returns the size (in octets) received from the fetch (HTTP or cache), of the payload body, before removing any applied content-codings. decodedBodySize returns the size (in octets) received from the fetch (HTTP or cache) of the message body, after removing any applied content-codings. The following example demonstrates using these three properties. ...
...lay_size_data
(){ // Check for support of the PerformanceResourceTiming.*size properties and print their values // if supported. if (performance === undefined) { console.log("= Display Size Data: performance NOT supported"); return; } var list = performance.getEntriesByType("resource"); if (list === undefined) { console.log("= Display Size Data: performance.getEntriesByType
() is NOT supported"); return; } // For each "resource", display its *Size property values console.log("= Display Size Data"); for (var i=0; i < list.length; i++) { console.log("== Resource[" + i + "] - " + list[i].name); if ("decodedBodySize" in list[i]) console.log("... decodedBodySize[" + i + "] = " + list[i].decodedBodySize); else console.log("... decodedBod...
...And 12 more matches
Selection - Web APIs
A user may make a selection from left to right (in document order) or right to left (reverse of document order). The anchor is where the user began the selection and the focus is where the user ends the selection. If you make a selection with a desktop mouse, the anchor is placed where you pressed the mouse button, and the focus is placed where you released the mouse button. ...
...e number of child nodes of the focusNode preceding the focus. Selection.isCollapsedRead only Returns a Boolean indicating whether the selection's start and end points are at the same position. Selection.rangeCountRead only Returns the number of ranges in the selection. Selection.typeRead only Returns a DOMString describing the type of the current selection. ...
...CollapsedRead only Returns a Boolean indicating whether the selection's start and end points are at the same position. Selection.rangeCountRead only Returns the number of ranges in the selection. Selection.typeRead only Returns a DOMString describing the type of the current selection. Methods Selection.addRange
() A Range object that will be added to the selection. Selection.collapse
() Collapses the current selection to a single point. ...
...And 12 more matches
Inputs and input sources - Web APIs
t from which the target ray is emitted (such as the front tip of the controller, or the end of a gun barrel if the controller is being rendered as a gun, for example), and the space's orientation vector extends outward along the path of the target ray. You can easily obtain the target ray corresponding to the targetRaySpace from within the drawing handler for a given frame using XRFrame's getPose
() method. The returned XRPose's transform is the transform corresponding to the target ray. Thus, for an input controller primaryInput: let targetRayPose = frame.session.getPose(primaryInput.targetRaySpace, viewerRefSpace); let targetRayOrigin = targetRayPose.transform.position; let targetRayVector = targetRayPose.transform.orientation; With this, you now have the point fr...
... that input source is selected as the primary. First-used Another option is to use the first input the user triggers the select action on. The code below starts by assuming the first input source is the primary, then establishes a handler for the select event that records the event's source as the primary input source. Then the select event handler is replaced with the function realSelectHandler
(), which will be used for handling all future select events. Then we pass the event through to realSelectHandler
() to allow the event to be processed as normal. let primaryInputSource = xrSession.inputSources[0]; xrSession.onselect = function(event) { primaryInputSource = event.inputSource; xrSession.onselect = realSelectHandler; return realSelectHandler(event); }; The effect is that we s...
...k up objects in the 3D world and to squeeze a trigger to fire a weapon in a game or simulation. Example This sample code shows a set of squeeze event handlers that implement these events to manage picking up and holding objects from the scene. The code presumes the existence of an avatar object representing the character, as used in several other eamples on this page, as well as the pickUpObject
() and dropObject
() functions, which handle transferring an object from the world to a particular hand and releasing an object from the hand and placing it back into the world. Picking up an object: handling squeezestart events xrSession.addEventListener("squeezestart", event => { const targetRaySpace = event.inputSource.targetRaySpace; const hand = event.inputSource.handedness; let targetR...
...And 12 more matches
Web Authentication API - Web APIs
ds). Many websites already have pages that allow users to register new accounts or sign in to an existing account, and the Web Authentication API acts as a replacement or supplement to those on those existing webpages. Similar to the other forms of the Credential Management API, the Web Authentication API has two basic methods that correspond to register and login: navigator.credentials.create
() - when used with the publicKey option, creates new credentials, either for registering a new account or for associating a new asymmetric key pair credentials with an existing account. navigator.credentials.get
() - when used with the publicKey option, uses an existing set of credentials to authenticate to a service, either logging a user in or as a form of second-factor authentication. Please n...
...h the publicKey option, creates new credentials, either for registering a new account or for associating a new asymmetric key pair credentials with an existing account. navigator.credentials.get
() - when used with the publicKey option, uses an existing set of credentials to authenticate to a service, either logging a user in or as a form of second-factor authentication. Please note: both create
() and get
() require a Secure Context (e.g. - the server is connected by https or is the localhost), and will not be available for use if the browser is not operating in a secure context. In their most basic forms, both create
() and get
() receive a very large random number called a challenge from the server and they return the challenge signed by the private key back to the server. This proves to t...
...cure context. In their most basic forms, both create
() and get
() receive a very large random number called a challenge from the server and they return the challenge signed by the private key back to the server. This proves to the server that a user is in possession of the private key required for authentication without revealing any secrets over the network. In order to understand how the create
() and get
() methods fit into the bigger picture, it is important to understand that they sit between two components that are outside the browser: Server - the Web Authentication API is intended to register new credentials on a server (also referred to as a service or a relying party) and later use those same credentials on that same server to authenticate a user. Authenticator - the credentials...
...And 12 more matches
WritableStream - Web APIs
The WritableStream interface of the the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing. Constructor WritableStream
() Creates a new WritableStream object. Properties WritableStream.locked Read only A boolean indicating whether the WritableStream is locked to a writer. Methods WritableStream.abort
() Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. WritableStream.close
() Closes the stream. WritableStream.getWriter
() Returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. While the stream i...
...new instance of WritableStreamDefaultWriter and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. Examples The following example illustrates several features of this interface. It shows the creation of the WritableStream with a custom sink and an API-supplied queueing strategy. It then calls a function called sendMessage
(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter
() method, which returns an instance of WritableStreamDefaultWriter. A forEach
() call is used to write each chunk of the string to the stream. Finally, write
() and close
() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySelect...
...ter. A forEach
() call is used to write each chunk of the string to the stream. Finally, write
() and close
() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 12 more matches
-webkit-box-reflect - CSS: Cascading Style Sheets
reflect: right; /* Offset value */ -webkit-box-reflect: below 10px; /* Mask value */ -webkit-box-reflect: below 0 linear-gradient(transparent, white); /* Global values */ -webkit-box-reflect: inherit; -webkit-box-reflect: initial; -webkit-box-reflect: unset; Note: This feature is not intended to be used by Web sites. To achieve reflection on the Web, the standard way is to use the CSS element
() function. Syntax Values above, below, right, left Are keywords indicating in which direction the reflection is to happen. <length> Indicates the size of the reflection. <image> Describes the mask to be applied to the reflection. Formal definition Initial valuenoneApplies toall elementsInheritednoComputed valueas specifiedAnimation typediscrete Formal syntax [ above | below | right ...
...re keywords indicating in which direction the reflection is to happen. <length> Indicates the size of the reflection. <image> Describes the mask to be applied to the reflection. ...
...cating in which direction the reflection is to happen. <length> Indicates the size of the reflection. <image> Describes the mask to be applied to the reflection. ...
...And 12 more matches
additive-symbols - CSS: Cascading Style Sheets
"; additive-symbols: 3 "0", 2 url(symbol.png); When the system descriptor is cyclic, numeric, alphabetic, symbolic, or fixed, use the symbols descriptor instead of additive-symbols. ...
...ols: 3 "0", 2 url(symbol.png); When the system descriptor is cyclic, numeric, alphabetic, symbolic, or fixed, use the symbols descriptor instead of additive-symbols. ...
...url(symbol.png); When the system descriptor is cyclic, numeric, alphabetic, symbolic, or fixed, use the symbols descriptor instead of additive-symbols. ...
...And 12 more matches
negative - CSS: Cascading Style Sheets
d counter style itself uses a negative sign. If the negative descriptor is specified for other systems that don't support negative counter values, then the descriptor is ignored. ...
...itself uses a negative sign. If the negative descriptor is specified for other systems that don't support negative counter values, then the descriptor is ignored. ...
...negative sign. If the negative descriptor is specified for other systems that don't support negative counter values, then the descriptor is ignored. ...
...And 12 more matches
pad - CSS: Cascading Style Sheets
for padding as the second parameter. A common usage of the pad descriptor is when you need your list to start numbering from 01 and go through 02, 03 and so on, instead of just 1, 2, 3... ...
...he second parameter. A common usage of the pad descriptor is when you need your list to start numbering from 01 and go through 02, 03 and so on, instead of just 1, 2, 3... ...
...meter. A common usage of the pad descriptor is when you need your list to start numbering from 01 and go through 02, 03 and so on, instead of just 1, 2, 3... ...
...And 12 more matches
prefix - CSS: Cascading Style Sheets
refix: "Page "; prefix: url(bullet.png); Values <symbol> Specifies a <symbol> that is prepended to the marker representation. It may be a <string>, <image>, or <custom-ident>. ...
...prefix: url(bullet.png); Values <symbol> Specifies a <symbol> that is prepended to the marker representation. It may be a <string>, <image>, or <custom-ident>. ...
...llet.png); Values <symbol> Specifies a <symbol> that is prepended to the marker representation. It may be a <string>, <image>, or <custom-ident>. ...
...And 12 more matches
suffix - CSS: Cascading Style Sheets
"; suffix: url(bullet.png); Values <symbol> Specifies a <symbol> that is appended to the marker representation. It may be a <string>, <image>, or <custom-ident>. Formal definition Related at-rule@counter-styleInitial value". ...
...ullet.png); Values <symbol> Specifies a <symbol> that is appended to the marker representation. It may be a <string>, <image>, or <custom-ident>. Formal definition Related at-rule@counter-styleInitial value". ...
...Values <symbol> Specifies a <symbol> that is appended to the marker representation. It may be a <string>, <image>, or <custom-ident>. Formal definition Related at-rule@counter-styleInitial value". ...
...And 12 more matches
symbols - CSS: Cascading Style Sheets
cified when the value of the system descriptor is cyclic, numeric, alphabetic, symbolic, or fixed. When the additive system is used, use the additive-symbols descriptor instead to specify the symbols. ...
...value of the system descriptor is cyclic, numeric, alphabetic, symbolic, or fixed. When the additive system is used, use the additive-symbols descriptor instead to specify the symbols. ...
...ystem descriptor is cyclic, numeric, alphabetic, symbolic, or fixed. When the additive system is used, use the additive-symbols descriptor instead to specify the symbols. ...
...And 12 more matches
background-image - CSS: Cascading Style Sheets
CAG, Guideline 1.1 explanations Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0 Formal definition Initial valuenoneApplies toall elements. ...
....1 explanations Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0 Formal definition Initial valuenoneApplies toall elements. ...
...s Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0 Formal definition Initial valuenoneApplies toall elements. ...
...And 12 more matches
border-image-source - CSS: Cascading Style Sheets
by border-style is displayed instead. <image> Image reference to use for the border. Formal definition Initial valuenoneApplies toall elements, except internal table elements when border-collapse is collapse. ...
...is displayed instead. <image> Image reference to use for the border. Formal definition Initial valuenoneApplies toall elements, except internal table elements when border-collapse is collapse. ...
...nstead. <image> Image reference to use for the border. Formal definition Initial valuenoneApplies toall elements, except internal table elements when border-collapse is collapse. ...
...And 12 more matches
mask-border-source - CSS: Cascading Style Sheets
none No mask border is used. <image> Image reference to use for the mask border. ...
...k border is used. <image> Image reference to use for the mask border. ...
...ed. <image> Image reference to use for the mask border. ...
...And 12 more matches
Control flow and error handling - JavaScript
with the true and false values of the Boolean object! For example: var b = new Boolean(false); if (b) // this condition evaluates to true if (b == true) // this condition evaluates to false Example In the following example, the function checkData returns true if the number of characters in a Text object is three. Otherwise, it displays an alert and returns false. function checkData
() { if (document.form1.threeChar.value.length == 3) { return true; } else { alert( 'Enter exactly three characters. ' + `${document.form1.threeChar.value} is not valid.`); return false; } } switch statement A switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program e...
... throw statement Use the throw statement to throw an exception. A throw statement specifies the value to be thrown: throw expression; You may throw any expression, not just expressions of a specific type. The following code throws several exceptions of varying types: throw 'Error2'; // String type throw 42; // Number type throw true; // Boolean type throw {toString: function
() { return "I'm an object!"; } }; Note: You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. // Create an object type UserException function UserException(message) { this.message = message; this.name = 'UserException'; } // Make the exception convert to a pretty string when used as a string // (e.g., by the error console...
... can specify an object when you throw an exception. You can then reference the object's properties in the catch block. // Create an object type UserException function UserException(message) { this.message = message; this.name = 'UserException'; } // Make the exception convert to a pretty string when used as a string // (e.g., by the error console) UserException.prototype.toString = function
() { return `${this.name}: "${this.message}"`; } // Create an instance of the object type and throw it throw new UserException('Value too high'); try...catch statement The try...catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. If an exception is thrown, the try...catch statement catches it. The try...catch statement consists...
...And 12 more matches
JavaScript modules - JavaScript
n our first example (see basic-modules) we have a file structure as follows: index.html main.js modules/ canvas.js square.js Note: All of the examples in this guide have basically the same structure; the above should start getting pretty familiar. The modules directory's two modules are described below: canvas.js -- contains functions related to setting up the canvas: create
() -- creates a canvas with a specified width and height inside a wrapper <div> with a specified ID, which is itself appended inside a specified parent element. Returns an object containing the canvas's 2D context and the wrapper's ID. createReportList
() -- creates an unordered list appended inside a specified wrapper element, which can be used to output report data into. Returns the list's ID. ...
...ed ID, which is itself appended inside a specified parent element. Returns an object containing the canvas's 2D context and the wrapper's ID. createReportList
() -- creates an unordered list appended inside a specified wrapper element, which can be used to output report data into. Returns the list's ID. square.js -- contains: name -- a constant containing the string 'square'. draw
() -- draws a square on a specified canvas, with a specified size, position, and color. Returns an object containing the square's size, position, and color. reportArea
() -- writes a square's area to a specific report list, given its length. reportPerimeter
() -- writes a square's perimeter to a specific report list, given its length. Aside -- .mjs versus .js Throughout this article, we'...
...s is designed to make it easy to have a default function provided by a module, and also helps JavaScript modules to interoperate with existing CommonJS and AMD module systems (as explained nicely in ES6 In Depth: Modules by Jason Orendorff; search for "Default exports"). Let's look at an example as we explain how it works. In our basic-modules square.js you can find a function called randomSquare
() that creates a square with a random color, size, and position. We want to export this as our default, so at the bottom of the file we write this: export default randomSquare; Note the lack of curly braces. We could instead prepend export default onto the function and define it as an anonymous function, like this: export default function(ctx) { ... } Over in our main.js file, we import the ...
...And 12 more matches
Private class fields - JavaScript
Class properties are public by default and can be examined or modified outside the class. There is however an experimental proposal to allow defining private class fields using a hash # prefix is added. ...
...lo world' } } class ClassWithPrivateStaticField { static #PRIVATE_STATIC_FIELD } Examples Private static fields Private fields are accessible on the class constructor from inside the class declaration itself. The limitation of static variables being called by only static methods still holds. class ClassWithPrivateStaticField { static #PRIVATE_STATIC_FIELD static publicStaticMethod
() { ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD = 42 return ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD } } console.assert(ClassWithPrivateStaticField.publicStaticMethod
() === 42) Private static fields are added to the class constructor at class evaluation time. There is a provenance restriction on private static fields. Only the class which defines the private static field...
...icMethod
() === 42) Private static fields are added to the class constructor at class evaluation time. There is a provenance restriction on private static fields. Only the class which defines the private static field can access the field. This can lead to unexpected behaviour when using this. ...
...And 12 more matches
TypeError: "x" is not a function - JavaScript
Maybe the object you are calling the method on does not have this function? For example, JavaScript Objects have no map function, but the JavaScript Array object does. There are many built-in functions in need of a (callback) function. ...
...e calling the method on does not have this function? For example, JavaScript Objects have no map function, but the JavaScript Array object does. There are many built-in functions in need of a (callback) function. ...
...s not have this function? For example, JavaScript Objects have no map function, but the JavaScript Array object does. There are many built-in functions in need of a (callback) function. ...
...And 12 more matches
Float32Array - JavaScript
resents an array of 32-bit floating point numbers (corresponding to the C float data type) in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ...
...tax (that is, using bracket notation). Constructor Float32Array
() Creates a new Float32Array object. Static properties Float32Array.BYTES_PER_ELEMENT Returns a number value of the element size. 4 in the case of an Float32Array. Float32Array.name Returns the string value of the constructor name. In the case of the Float32Array type: "Float32Array". Static methods Float32Array.from
() Creates a new Float32Array from an array-like or iterable object. See also Array.from
(). Float32Array.of
() Creates a new Float32Array with a variable number of arguments. See also Array.of
(). Instance properties Float32Array.prototype.buffer Returns the ArrayBuffer referenced by the Float32Array Fixed at construction time and thus read only. Float32Array.prototype.byteLength Returns th...
...at construction time and thus read only. Float32Array.prototype.byteOffset Returns the offset (in bytes) of the Float32Array from the start of its ArrayBuffer. Fixed at construction time and thus read only. Float32Array.prototype.length Returns the number of elements hold in the Float32Array. Fixed at construction time and thus read only. Instance methods Float32Array.prototype.copyWithin
() Copies a sequence of array elements within the array. See also Array.prototype.copyWithin
(). Float32Array.prototype.entries
() Returns a new Array Iterator object that contains the key/value pairs for each index in the array. See also Array.prototype.entries
(). Float32Array.prototype.every
() Tests whether all elements in the array pass the test provided by a function. See also Array.prototype...
...And 12 more matches
Float64Array - JavaScript
esents an array of 64-bit floating point numbers (corresponding to the C double data type) in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ...
...tax (that is, using bracket notation). Constructor Float64Array
() Creates a new Float64Array object. Static properties Float64Array.BYTES_PER_ELEMENT Returns a number value of the element size. 8 in the case of an Float64Array. Float64Array.name Returns the string value of the constructor name. In the case of the Float64Array type: "Float64Array". Static methods Float64Array.from
() Creates a new Float64Array from an array-like or iterable object. See also Array.from
(). Float64Array.of
() Creates a new Float64Array with a variable number of arguments. See also Array.of
(). Instance properties Float64Array.prototype.buffer Returns the ArrayBuffer referenced by the Float64Array Fixed at construction time and thus read only. Float64Array.prototype.byteLength Returns th...
...at construction time and thus read only. Float64Array.prototype.byteOffset Returns the offset (in bytes) of the Float64Array from the start of its ArrayBuffer. Fixed at construction time and thus read only. Float64Array.prototype.length Returns the number of elements hold in the Float64Array. Fixed at construction time and thus read only. Instance methods Float64Array.prototype.copyWithin
() Copies a sequence of array elements within the array. See also Array.prototype.copyWithin
(). Float64Array.prototype.entries
() Returns a new Array Iterator object that contains the key/value pairs for each index in the array. See also Array.prototype.entries
(). Float64Array.prototype.every
() Tests whether all elements in the array pass the test provided by a function. See also Array.prototype...
...And 12 more matches
Int16Array - JavaScript
The Int16Array typed array represents an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). Constructor Int16Array
() Creates a new Int16Array object. Static properties Int16Array.BYTES_PER_ELEMENT Returns a number value of the element size. 2 in the case of an Int16Array. Int16Array.name Returns the string value of the constructor name. In the case of the Int16Array type: "Int16Array". Static methods Int16Array.from
() Creates a new Int16Array from an array-like or iterable object. See also Array.fro...
...eates a new Int16Array object. Static properties Int16Array.BYTES_PER_ELEMENT Returns a number value of the element size. 2 in the case of an Int16Array. Int16Array.name Returns the string value of the constructor name. In the case of the Int16Array type: "Int16Array". Static methods Int16Array.from
() Creates a new Int16Array from an array-like or iterable object. See also Array.from
(). Int16Array.of
() Creates a new Int16Array with a variable number of arguments. See also Array.of
(). Instance properties Int16Array.prototype.buffer Returns the ArrayBuffer referenced by the Int16Array Fixed at construction time and thus read only. Int16Array.prototype.byteLength Returns the length (in bytes) of the Int16Array from the start of its ArrayBuffer. Fixed at construction time...
...er. Fixed at construction time and thus read only. Int16Array.prototype.byteOffset Returns the offset (in bytes) of the Int16Array from the start of its ArrayBuffer. Fixed at construction time and thus read only. Int16Array.prototype.length Returns the number of elements hold in the Int16Array. Fixed at construction time and thus read only. Instance methods Int16Array.prototype.copyWithin
() Copies a sequence of array elements within the array. See also Array.prototype.copyWithin
(). Int16Array.prototype.entries
() Returns a new Array Iterator object that contains the key/value pairs for each index in the array. See also Array.prototype.entries
(). Int16Array.prototype.every
() Tests whether all elements in the array pass the test provided by a function. See also Array.prototype.eve...
...And 12 more matches
Int32Array - JavaScript
The Int32Array typed array represents an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). Constructor Int32Array
() Creates a new Int32Array object. Static properties Int32Array.BYTES_PER_ELEMENT Returns a number value of the element size. 4 in the case of an Int32Array. Int32Array.name Returns the string value of the constructor name. In the case of the Int32Array type: "Int32Array". Static methods Int32Array.from
() Creates a new Int32Array from an array-like or iterable object. See also Array.fro...
...eates a new Int32Array object. Static properties Int32Array.BYTES_PER_ELEMENT Returns a number value of the element size. 4 in the case of an Int32Array. Int32Array.name Returns the string value of the constructor name. In the case of the Int32Array type: "Int32Array". Static methods Int32Array.from
() Creates a new Int32Array from an array-like or iterable object. See also Array.from
(). Int32Array.of
() Creates a new Int32Array with a variable number of arguments. See also Array.of
(). Instance properties Int32Array.prototype.buffer Returns the ArrayBuffer referenced by the Int32Array Fixed at construction time and thus read only. Int32Array.prototype.byteLength Returns the length (in bytes) of the Int32Array from the start of its ArrayBuffer. Fixed at construction time...
...er. Fixed at construction time and thus read only. Int32Array.prototype.byteOffset Returns the offset (in bytes) of the Int32Array from the start of its ArrayBuffer. Fixed at construction time and thus read only. Int32Array.prototype.length Returns the number of elements hold in the Int32Array. Fixed at construction time and thus read only. Instance methods Int32Array.prototype.copyWithin
() Copies a sequence of array elements within the array. See also Array.prototype.copyWithin
(). Int32Array.prototype.entries
() Returns a new Array Iterator object that contains the key/value pairs for each index in the array. See also Array.prototype.entries
(). Int32Array.prototype.every
() Tests whether all elements in the array pass the test provided by a function. See also Array.prototype.eve...
...And 12 more matches
Int8Array - JavaScript
The Int8Array typed array represents an array of twos-complement 8-bit signed integers. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). Constructor Int8Array
() Creates a new Int8Array object. Static properties Int8Array.BYTES_PER_ELEMENT Returns a number value of the element size. 1 in the case of an Int8Array. Int8Array.name Returns the string value of the constructor name. In the case of the Int8Array type: "Int8Array". Static methods Int8Array.from
() Creates a new Int8Array from an array-like or iterable object. See also Array.from
(). Int8Array.of
() Creates a new Int8Array with a variable number of arguments. See also Array.
... Instance properties Int8Array.prototype.buffer Returns the ArrayBuffer referenced by the Int8Array Fixed at construction time and thus read only. ...
...yBuffer. Fixed at construction time and thus read only. Int8Array.prototype.byteOffset Returns the offset (in bytes) of the Int8Array from the start of its ArrayBuffer. Fixed at construction time and thus read only. Int8Array.prototype.length Returns the number of elements hold in the Int8Array. Fixed at construction time and thus read only. Instance methods Int8Array.prototype.copyWithin
() Copies a sequence of array elements within the array. See also Array.prototype.copyWithin
(). Int8Array.prototype.entries
() Returns a new Array Iterator object that contains the key/value pairs for each index in the array. See also Array.prototype.entries
(). Int8Array.prototype.every
() Tests whether all elements in the array pass the test provided by a function. See also Array.prototype.every...
...And 12 more matches
Uint16Array - JavaScript
The Uint16Array typed array represents an array of 16-bit unsigned integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ...
...ndex syntax (that is, using bracket notation). Constructor Uint16Array
() Creates a new Uint16Array object. Static properties Uint16Array.BYTES_PER_ELEMENT Returns a number value of the element size. 2 in the case of an Uint16Array. Uint16Array.name Returns the string value of the constructor name. In the case of the Uint16Array type: "Uint16Array". Static methods Uint16Array.from
() Creates a new Uint16Array from an array-like or iterable object. See also Array.from
(). Uint16Array.of
() Creates a new Uint16Array with a variable number of arguments. See also Array.of
(). Instance properties Uint16Array.prototype.buffer Returns the ArrayBuffer referenced by the Uint16Array Fixed at construction time and thus read only. Uint16Array.prototype.byteLength Returns the leng...
...ixed at construction time and thus read only. Uint16Array.prototype.byteOffset Returns the offset (in bytes) of the Uint16Array from the start of its ArrayBuffer. Fixed at construction time and thus read only. Uint16Array.prototype.length Returns the number of elements hold in the Uint16Array. Fixed at construction time and thus read only. Instance methods Uint16Array.prototype.copyWithin
() Copies a sequence of array elements within the array. See also Array.prototype.copyWithin
(). Uint16Array.prototype.entries
() Returns a new Array Iterator object that contains the key/value pairs for each index in the array. See also Array.prototype.entries
(). Uint16Array.prototype.every
() Tests whether all elements in the array pass the test provided by a function. See also Array.prototype.e...
...And 12 more matches
Uint32Array - JavaScript
The Uint32Array typed array represents an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ...
...ndex syntax (that is, using bracket notation). Constructor Uint32Array
() Creates a new Uint32Array object. Static properties Uint32Array.BYTES_PER_ELEMENT Returns a number value of the element size. 4 in the case of an Uint32Array. Uint32Array.name Returns the string value of the constructor name. In the case of the Uint32Array type: "Uint32Array". Static methods Uint32Array.from
() Creates a new Uint32Array from an array-like or iterable object. See also Array.from
(). Uint32Array.of
() Creates a new Uint32Array with a variable number of arguments. See also Array.of
(). Instance properties Uint32Array.prototype.buffer Returns the ArrayBuffer referenced by the Uint32Array Fixed at construction time and thus read only. Uint32Array.prototype.byteLength Returns the leng...
...ixed at construction time and thus read only. Uint32Array.prototype.byteOffset Returns the offset (in bytes) of the Uint32Array from the start of its ArrayBuffer. Fixed at construction time and thus read only. Uint32Array.prototype.length Returns the number of elements hold in the Uint32Array. Fixed at construction time and thus read only. Instance methods Uint32Array.prototype.copyWithin
() Copies a sequence of array elements within the array. See also Array.prototype.copyWithin
(). Uint32Array.prototype.entries
() Returns a new Array Iterator object that contains the key/value pairs for each index in the array. See also Array.prototype.entries
(). Uint32Array.prototype.every
() Tests whether all elements in the array pass the test provided by a function. See also Array.prototype.e...
...And 12 more matches
Uint8Array - JavaScript
The Uint8Array typed array represents an array of 8-bit unsigned integers. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). Constructor Uint8Array
() Creates a new Uint8Array object. Static properties Uint8Array.BYTES_PER_ELEMENT Returns a number value of the element size. 1 in the case of an Uint8Array. Uint8Array.name Returns the string value of the constructor name. In the case of the Uint8Array type: "Uint8Array". Static methods Uint8Array.from
() Creates a new Uint8Array from an array-like or iterable object. See also Array.from
(). Uint8Array.of
() Creates a new Uint8Array with a variable number of arguments. See also Array.of...
... Instance properties Uint8Array.prototype.buffer Returns the ArrayBuffer referenced by the Uint8Array Fixed at construction time and thus read only. ...
...ay. Fixed at construction time and thus read only. Uint8Array.prototype.byteOffset Returns the offset (in bytes) of the Uint8Array from the start of its ArrayBuffer. Fixed at construction time and thus read only. Uint8Array.prototype.length Returns the number of elements held in the Uint8Array. Fixed at construction time and thus read only. Instance methods Uint8Array.prototype.copyWithin
() Copies a sequence of array elements within the array. See also Array.prototype.copyWithin
(). Uint8Array.prototype.entries
() Returns a new Array Iterator object that contains the key/value pairs for each index in the array. See also Array.prototype.entries
(). Uint8Array.prototype.every
() Tests whether all elements in the array pass the test provided by a function. See also Array.prototype.eve...
...And 12 more matches
Uint8ClampedArray - JavaScript
clamped to 0-255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ...
...Constructor Uint8ClampedArray
() Creates a new Uint8ClampedArray object. Static properties Uint8ClampedArray.BYTES_PER_ELEMENT Returns a number value of the element size. 1 in the case of an Uint8ClampedArray. Uint8ClampedArray.name Returns the string value of the constructor name. In the case of the Uint8ClampedArray type: "Uint8ClampedArray". Static methods Uint8ClampedArray.from
() Creates a new Uint8ClampedArray from an array-like or iterable object. See also Array.from
(). Uint8ClampedArray.of
() Creates a new Uint8ClampedArray from a variable number of arguments. See also Array.of
(). Instance properties Uint8ClampedArray.prototype.buffer Returns the ArrayBuffer referenced by the Uint8ClampedArray Fixed at construction time and thus read only. Uint8ClampedArray.pr...
...thus read only. Uint8ClampedArray.prototype.byteOffset Returns the offset (in bytes) of the Uint8ClampedArray from the start of its ArrayBuffer. Fixed at construction time and thus read only. Uint8ClampedArray.prototype.length Returns the number of elements hold in the UintClamped8Array. Fixed at construction time and thus read only. Instance methods Uint8ClampedArray.prototype.copyWithin
() Copies a sequence of array elements within the array. See also Array.prototype.copyWithin
(). Uint8ClampedArray.prototype.entries
() Returns a new Array Iterator object that contains the key/value pairs for each index in the array. See also Array.prototype.entries
(). Uint8ClampedArray.prototype.every
() Tests whether all elements in the array pass the test provided by a function. See also Array...
...And 12 more matches
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
lot of changes regarding the last stable version SVG 1.1. Those changes are listed below including their support status within Mozilla applications. ...
...s regarding the last stable version SVG 1.1. Those changes are listed below including their support status within Mozilla applications. ...
... last stable version SVG 1.1. Those changes are listed below including their support status within Mozilla applications. ...
...And 12 more matches
Using custom elements - Web Components
d Edge (76). Opera and Safari so far support only autonomous custom elements. High-level view The controller of custom elements on a web document is the CustomElementRegistry object -- this object allows you to register a custom element on the page, return information on what custom elements are registered, etc. To register a custom element on the page, you use the CustomElementRegistry.define
() method. This takes as its arguments: A DOMString representing the name you are giving to the element. Note that custom element names require a dash to be used in them (kebab-case); they can't be single words. A class object that defines the behaviour of the element. Optionally, an options object containing an extends property, which specifies the built-in element your element inherits from, ...
... define a custom word-count element like this: customElements.define('word-count', WordCount, { extends: 'p' }); The element is called word-count, its class object is WordCount, and it extends the <p> element. A custom element's class object is written using standard ES 2015 class syntax. For example, WordCount is structured like so: class WordCount extends HTMLParagraphElement { constructor
() { // Always call super first in constructor super
(); // Element functionality written in here ... } } This is just a simple example, but there is more you can do here. It is possible to define specific lifecycle callbacks inside the class, which run at specific points in the element's lifecycle. For example, connectedCallback is invoked each time the custom element is appende...
...pup-info-box> (see a live example). This takes an image icon and a text string, and embeds the icon into the page. When the icon is focused, it displays the text in a pop up information box to provide further in-context information. To begin with, the JavaScript file defines a class called PopUpInfo, which extends the generic HTMLElement class. class PopUpInfo extends HTMLElement { constructor
() { // Always call super first in constructor super
(); // write element functionality in here ... } } The preceding code snippet contains the constructor
() definition for the class, which always starts by calling super
() so that the correct prototype chain is established. Inside the constructor, we define all the functionality the element will have when an instance of it is in...
...And 12 more matches
Content Scripts - Archive of obsolete content
ent.body.innerHTML = "<h1>this page has been eaten</h1>";' tabs.activeTab.attach({ contentScript: contentScriptString }); The following high-level SDK modules can use content scripts to modify web pages: page-mod: enables you to attach content scripts to web pages that match a specific URL pattern. tabs: exports a Tab object for working with a browser tab. The Tab object includes an attach
() function to attach a content script to the tab. page-worker: lets you retrieve a web page without displaying it. You can attach content scripts to the page, to access and manipulate the page's DOM. context-menu: use a content script to interact with the page in which the menu is invoked. Additionally, some SDK user interface components - panel, sidebar, frame - are specified using HTML, and u...
...that is, at the point the DOMContentLoaded event fires. At this point, content scripts are able to interact with the DOM content, but externally-referenced stylesheets and images may not have finished loading. "end": load the scripts after all content (DOM, JS, CSS, images) for the page has been loaded, at the time the window.onload event fires. The default value is "end". Note that tab.attach
() doesn't accept contentScriptWhen, because it's generally called after the page has loaded. Passing configuration options The contentScriptOptions is a JSON object that is exposed to content scripts as a read-only value under the self.options property: // main.js var tabs = require("sdk/tabs"); tabs.on('ready', function(tab) { tab.attach({ contentScript: 'window.alert(self.options.mes...
...ght want to share objects between content scripts and page scripts or to send messages between them. If you need to do this, read about interacting with page scripts. Event listeners You can listen for DOM events in a content script just as you can in a normal page script, but there are two important differences: First, if you define an event listener by passing it as a string into setAttribute
(), then the listener is evaluated in the page's context, so it will not have access to any variables defined in the content script. For example, this content script will fail with the error "theMessage is not defined": var theMessage = "Hello from content script!"; anElement.setAttribute("onclick", "alert(theMessage);"); Second, if you define an event listener by direct assignment to a global ev...
...And 11 more matches
core/heritage - Archive of obsolete content
nges // behavior, which in majority cases you need to handle, so you end up // with additional boilerplate. if (!(this instanceof Dog)) return new Dog(name); this.name = name; }; // To define methods you need to make a dance with a special 'prototype' // property of the constructor function. This is too much machinery exposed. Dog.prototype.type = 'dog'; Dog.prototype.bark = function bark
() { return 'Ruff! Ruff!' }; // Subclassing a `Dog` function Pet(name, breed) { // Once again we do our little dance if (!(this instanceof Pet)) return new Pet(name, breed); Dog.call(this, name); this.breed = breed; } // To subclass, you need to make another special dance with special // 'prototype' properties. Pet.prototype = Object.create(Dog.prototype); // If you want correct instance...
...prototype' properties. Pet.prototype = Object.create(Dog.prototype); // If you want correct instanceof behavior you need to make a dance with // another special `constructor` property of the `prototype` object. Object.defineProperty(Pet.prototype, 'constructor', { value: Pet }); // Finally you can define some properties. Pet.prototype.call = function(name) { return this.name === name ? this.bark
() : ''; }; Since SDK APIs may be interacting with untrusted code an extra security 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 &...
...k. That is why SDK provides utility functions to make it more declarative and less verbose. Class Module exports Class utility function for making constructor functions with a proper prototype chain setup in declarative manner: var { Class } = require('sdk/core/heritage'); var Dog = Class({ initialize: function initialize(name) { this.name = name; }, type: 'dog', bark: function bark
() { return 'Ruff! Ruff!' } }); Note: We use term Class to refer an exemplar constructs in a form of constructor functions with a proper prototype chain setup. Constructors created using Class function don't require new keyword (even though it can be used) for instantiation. Also, idiomatic SDK code does not uses optional new keywords, but you're free to use it in your add-on code: var fluff...
...And 11 more matches
Creating a dynamic status bar extension - Archive of obsolete content
Our extension will refresh the stock information display when the user clicks the panel. Write the JavaScript code The work of fetching the stock quote and updat...
...pt code The work of fetching the stock quote and updating the status bar panel's display is handled by the JavaScript code in the file stockwatcher.js. Unlike our previous sample, this one is implemented as an object. We do this because in future samples in this series, we're going to be doing things that are easier to do if our extension is implemented that way. We use the window.addEventListener
() DOM function to tell Firefox to call the StockWatcher.startup
() function when a new browser window is opened: window.addEventListener("load", function(e) { StockWatcher.startup
(); }, false); Our new extension has two primary functions: startup
() and refreshInformation
(). The refreshInformation
() function contains another function, called infoReceived
(). The following sections will examine these ...
...ll Firefox to call the StockWatcher.startup
() function when a new browser window is opened: window.addEventListener("load", function(e) { StockWatcher.startup
(); }, false); Our new extension has two primary functions: startup
() and refreshInformation
(). The refreshInformation
() function contains another function, called infoReceived
(). The following sections will examine these one by one. startup
() The startup
() function is called when a new browser window is opened. ...
...And 11 more matches
Manipulating Lists - Archive of obsolete content
L listbox provides a number of specialized methods. List Manipulation The listbox element provides numerous methods to retrieve and manipulate its items. Although listboxes may be manipulated using the standard DOM functions as well, it is recommended that the specialized listbox functions be used instead when possible. These functions are bit simpler and will do the right thing. ...
...t provides numerous methods to retrieve and manipulate its items. Although listboxes may be manipulated using the standard DOM functions as well, it is recommended that the specialized listbox functions be used instead when possible. These functions are bit simpler and will do the right thing. The appendItem
() function is used to append a new item to the end a list. ...
...unctions be used instead when possible. These functions are bit simpler and will do the right thing. The appendItem
() function is used to append a new item to the end a list. Similar to the DOM appendChild
() function except that it takes a string label, and you do not have to worry about where to add it in the list structure. Here is an example: Example 1 : Source View <script> function addItem
(){ document.getElementById('thelist').appendItem("Thursday", "thu"); } </script> <listbox id="thelist"/> <button label="Add" oncommand="addItem
();"/> The appendItem
() takes two arguments, the label, in this case 'Thursday', and a value 'thu'. The two arguments correspond to the label attribute and the value attribute on the listitem element. The value is used only as an extra optional value a...
...And 11 more matches
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
been released. This year, the ES2019 specification will be released and ES2020 is the current ECMAScript draft specification. You can see the latest proposals on the tc39/ecma262 GitHub repository. A channel for feedback on ECMAScript standards is es-discuss. Below is a list of features in ES2016+ and what version of Firefox they were implemented in. ...
...tion will be released and ES2020 is the current ECMAScript draft specification. You can see the latest proposals on the tc39/ecma262 GitHub repository. A channel for feedback on ECMAScript standards is es-discuss. Below is a list of features in ES2016+ and what version of Firefox they were implemented in. ...
... see the latest proposals on the tc39/ecma262 GitHub repository. A channel for feedback on ECMAScript standards is es-discuss. Below is a list of features in ES2016+ and what version of Firefox they were implemented in. ...
...And 11 more matches
Build your own function - Learn web development
Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, JavaScript first steps, Functions -- reusable blocks of code. Objective: To provide some practice in building a custom function, and explain a few more useful associated details. Active learning: Let's build a function The custom function we are going to build will be called displayMessage
(). It will display a custom message box on a web page and will act as a customized replacement for a browser's built-in alert
() function. We've seen this before, but let's just refresh our memories. Type the following in your browser's JavaScript console, on any page you like: alert('This is a message'); The alert function takes a single argument -- the string that is displayed in the alert box. ...
...entheses after them, and variables don't. Start by accessing the function-start.html file and making a local copy. You'll see that the HTML is simple -- the body contains just a single button. We've also provided some basic CSS to style the custom message box, and an empty <script> element to put our JavaScript in. Next, add the following inside the <script> element: function displayMessage
() { } We start off with the keyword function, which means we are defining a function. This is followed by the name we want to give to our function, a set of parentheses, and a set of curly braces. Any parameters we want to give to our function go inside the parentheses, and the code that runs when we call the function goes inside the curly braces. Finally, add the following code inside the curl...
...onst html = document.querySelector('html'); const panel = document.createElement('div'); panel.setAttribute('class', 'msgBox'); html.appendChild(panel); const msg = document.createElement('p'); msg.textContent = 'This is a message box'; panel.appendChild(msg); const closeBtn = document.createElement('button'); closeBtn.textContent = 'x'; panel.appendChild(closeBtn); closeBtn.onclick = function
() { panel.parentNode.removeChild(panel); } This is quite a lot of code to go through, so we'll walk you through it bit by bit. The first line uses a DOM API function called document.querySelector
() to select the <html> element and store a reference to it in a constant called html, so we can do things to it later on: const html = document.querySelector('html'); The next section uses another...
...And 11 more matches
What went wrong? Troubleshooting JavaScript - Learn web development
the JavaScript interpreter. Often, this error message actually means that we've spelled something wrong. If you are not sure of the correct spelling of a piece of syntax, it is often good to look up the feature on MDN. The best way to do this currently is to search for "mdn name-of-feature" with your favorite search engine. Here's a shortcut to save you some time in this instance: addEventListener
(). So, looking at this page, the error appears to be that we've spelled the function name wrong! Remember that JavaScript is case sensitive, so any slight difference in spelling or casing will cause an error. Changing addeventListener to addEventListener should fix this. Do this now. Note: See our TypeError: "x" is not a function reference page for more details about this error. Syntax errors...
...error! This time the error being reported is "TypeError: lowOrHi is null", on line 78. Note: Null is a special value that 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 i...
...owOrHi in the code. The earliest instance you'll find in the JavaScript is on line 48: const lowOrHi = document.querySelector('lowOrHi'); At this point we are trying to make the variable contain a reference to an element in the document's HTML. Let's check whether the value is null after this line has been run. Add the following code on line 49: console.log(lowOrHi); Note: console.log
() is a really useful debugging function that prints a value to the console. So it will print the value of lowOrHi to the console as soon as we have tried to set it in line 48. Save and refesh, and you should now see the console.log
() result in your console. Sure enough, lowOrHi's value is null at this point, so there is definitely a problem with line 48. Let's think about what the problem c...
...And 11 more matches
XPCOM Stream Guide
in them to something more useful. Primitive streams There are streams for several different types of data storage. Each of these implements nsIInputStream. ...
... ZIP nsJARInputStream N/A nsIInputStream zipReader.getInputStream(zipEntry); Similarly, each of these implements nsIOutputStream. ...
...afe-file-output-stream;1 nsISafeFileOutputStream, nsIFileOutputStream stream.init(file, ioFlags, perm, behaviorFlags); Channels have streams too Any implementation of nsIChannel will have an input stream as well, but unless you own the channel, you shouldn't try to read from the input stream. There are two ways of getting the input stream: by calling the channel's .open
() method for a synchronous read, or by calling the channel's .asyncOpen
() method with an nsIStreamListener object. You can get an nsIChannel object from the IO Service's newChannel(spec, charset, baseURI) method or its .newChannelFromURI(uri) method. The "safe file output stream" Mozilla provides a "safe file output stream" implementation. This implementation actually writes the contents of the ...
...And 11 more matches
nsIAppShell
tive event system layer. This interface is designed to be used on the main application thread only. ...
...veEvent(in PRBool aRealEvent, in voidPtr aEvent); Obsolete since Gecko 1.9 void exit
(); void favorPerformanceHint(in boolean favorPerfOverStarvation, in unsigned long starvationDelay); void GetNativeEvent(in PRBoolRef aRealEvent, in voidPtrRef aEvent); Obsolete since Gecko 1.9 void ListenToEventQueue(in nsIEventQueue aQueue, in PRBool aListen); Obsolete since Gecko 1.9 void resumeNative
(); void run
(); void runInStableState(in nsIRunnable aRunnable); void Spindown
(); Obsolete since Gecko 1.9 void Spinup
(); Obsolete since Gecko 1.9 void suspendNative
(); Attributes Attribute Type Description eventloopNestingLevel unsigned long The current event loop nesting level. Read only. ...
...RBool aListen); Obsolete since Gecko 1.9 void resumeNative
(); void run
(); void runInStableState(in nsIRunnable aRunnable); void Spindown
(); Obsolete since Gecko 1.9 void Spinup
(); Obsolete since Gecko 1.9 void suspendNative
(); Attributes Attribute Type Description eventloopNestingLevel unsigned long The current event loop nesting level. Read only. Methods Create
() Obsolete since Gecko 1.9 (Firefox 3) Creates an application shell. void Create( inout int argc, inout string argv ); Parameters argc The number of parameters passed in on the command line. argv A direct reference to the parameter array. DispatchNativeEvent
() Obsolete since Gecko 1.9 (Firefox 3) After event dispatch execute app specific code. void ...
...And 11 more matches
nsIDBFolderInfo
long delta); void ChangeNumUnreadMessages(in long delta); boolean getBooleanProperty(in string propertyName, in boolean defaultValue); void getCharacterSet(out ACString charSet, out boolean overriden); void getCharacterSetOverride(out boolean characterSetOverride); Obsolete since Gecko 1.8 string getCharPtrCharacterSet
(); string getCharPtrProperty(in string propertyName); void getLocale(in nsString result); Native code only! Obsolete since Gecko 1.8 void getMailboxName(in nsString boxName); Native code only! Obsolete since Gecko 1.8 AString getProperty(in string propertyName); nsIDBFolderInfo GetTransferInfo
(); unsigne...
...es long NumUnreadMessages long sortOrder nsMsgViewSortOrderValue sortType nsMsgViewSortTypeValue Version unsigned long viewFlags nsMsgViewFlagsTypeValue viewType nsMsgViewTypeValue Methods AndFlags
() long AndFlags( in long flags ); Parameters flags Missing Description Return value Missing Description Exceptions thrown Missing Exception Missing Description ChangeExpungedBytes
() void ChangeExpungedBytes( in long delta ); Parameters delta Missing Description Exceptions thrown Missing Exception Missing Description ChangeNumMess...
...g AndFlags( in long flags ); Parameters flags Missing Description Return value Missing Description Exceptions thrown Missing Exception Missing Description ChangeExpungedBytes
() void ChangeExpungedBytes( in long delta ); Parameters delta Missing Description Exceptions thrown Missing Exception Missing Description ChangeNumMessages
() void ChangeNumMessages( in long delta ); Parameters delta Missing Description Exceptions thrown Missing Exception Missing Description ChangeNumUnreadMessages
() void ChangeNumUnreadMessages( in long delta ); Parameters delta Missing Description Exceptions thrown Missing Exception Missing Description getBooleanProperty
() boolean ...
...And 11 more matches
nsIDOMNSHTMLDocument
dom/interfaces/html/nsIDOMNSHTMLDocument.idlScriptable This interface defines methods and properties supported by Gecko on the document object that are not part of DOM Level 2. ...
...rits from: nsISupports Last changed in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) Method overview void captureEvents(in long eventFlags); void clear
(); boolean execCommand(in DOMString commandID, in boolean doShowUI, in DOMString value); boolean execCommandShowHelp(in DOMString commandID); Obsolete since Gecko 14.0 DOMString getSelection
(); nsIDOMDocument open(in ACString aContentType, in boolean aReplace); boolean queryCommandEnabled(in DOMString commandID); boolean queryCommandIndeterm(in DOMString commandID); boolean queryCommandState(in DOMString commandID); boolean queryCommandSupported(in DOMString commandID); DOMString queryCommandText(in DOMString commandID); Obsolete si...
... commandID); boolean queryCommandState(in DOMString commandID); boolean queryCommandSupported(in DOMString commandID); DOMString queryCommandText(in DOMString commandID); Obsolete since Gecko 14.0 DOMString queryCommandValue(in DOMString commandID); void releaseEvents(in long eventFlags); void routeEvent(in nsIDOMEvent evt); void write
(); Obsolete since Gecko 2.0 void writeln
(); Obsolete since Gecko 2.0 Attributes Attribute Type Description alinkColor DOMString Same as body.aLink bgColor DOMString Same as body.bgColor compatMode DOMString Returns "BackCompat" if the document is in Quirks mode or "CSS1Compat" if the document is in Full Standards or Almost S...
...And 11 more matches
nsILoginManager
Note: Default values for the nsILoginMetaInfo properties are...
... Note: Default values for the nsILoginMetaInfo properties are created if the specified login doesn't explicitly specify them. void addLogin( in nsILoginInfo aLogin ); Parameters aLogin The login to store. ...
...gin in the Login Manager. Note: Default values for the nsILoginMetaInfo properties are created if the specified login doesn't explicitly specify them. void addLogin( in nsILoginInfo aLogin ); Parameters aLogin The login to store. Exceptions thrown An exception is thrown if the login information is already stored in the Login Manager. To change a login, you have to use modifyLogin
(). autoCompleteSearch
() Generates results for a user field autocomplete menu. Note: This method is provided for use only by the FormFillController, which calls it directly. It should not be used for any other purpose. nsIAutoCompleteResult autoCompleteSearch( in AString aSearchString, in nsIAutoCompleteResult aPreviousResult, in nsIDOMHTMLInputElement aElement ); Parameters aSearchS...
...And 11 more matches
nsIPluginHost
refox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview nsIFile createTempFileToPost(in string aPostDataURL); Native code only! void createTmpFileToPost(in string aPostDataURL, out string aTmpFileName); Native code only! Obsolete since Gecko 2.0 void deletePluginNativeWindow(in nsPluginNativeWindowPtr aPluginNativeWindow); Native code only! void destroy
(); Native code only! void findProxyForURL(in string aURL, out string aResult); Native code only! nsIPlugin getPlugin(in string aMimeType); Native code only! void getPluginCount(out unsigned long aPluginCount); Obsolete since Gecko 1.8 nsIPlugin getPluginFactory(in string aMimeType); Native code only! Obsolete since Gecko 1.9.2 void getPluginName(in nsI...
...tring aPluginName); Native code only! nsIPluginTag getPluginTagForInstance(in nsIPluginInstance aInstance); Native code only! void getPluginTags([optional] out unsigned long aPluginCount, [retval, array, size_is(aPluginCount)] out nsIPluginTag aResults); void handleBadPlugin(in PRLibraryPtr aLibrary, in nsIPluginInstance instance); Native code only! void init
(); Native code only! void instantiateDummyJavaPlugin(in nsIPluginInstanceOwner aOwner); Native code only! void instantiateEmbeddedPlugin(in string aMimeType, in nsIURI aURL, in nsIPluginInstanceOwner aOwner); Native code only! void instantiateEmbededPlugin(in string aMimeType, in nsIURI aURL, in nsIPluginInstanceOwner aOwner); Obsolete since Gecko 1.8 void inst...
...StreamListener aStreamListener); Native code only! nsIStreamListener instantiatePluginForChannel(in nsIChannel aChannel, in nsIPluginInstanceOwner aOwner); Native code only! void isPluginEnabledForExtension(in string aExtension, in constCharStarRef aMimeType); Native code only! void isPluginEnabledForType(in string aMimeType); Native code only! void loadPlugins
(); Native code only! void newPluginNativeWindow(out nsPluginNativeWindowPtr aPluginNativeWindow); Native code only! void parsePostBufferToFixHeaders(in string aInPostData, in unsigned long aInPostDataLen, out string aOutPostData, out unsigned long aOutPostDataLen); Native code only! void reloadPlugins(in boolean reloadPages); void setIsScriptableInstance(in ns...
...And 11 more matches
nsIWindowMediator
wTimeStamp(in nsIXULWindow aWindow); Native code only! void updateWindowTitle(in nsIXULWindow aWindow, in wstring inTitle ); Native code only! Constants Constant Value Description zLevelTop 1 Send window to top. zLevelBottom 2 Send window to bottom. zLevelBelow 3 Place window below some window. Methods addListener
() Register a listener for window status changes. void addListener( in nsIWindowMediatorListener aListener ); Parameters aListener The listener to register. Example: Of window listener object and how to register then unregister. This example below waits for listens to when a window opens, and then after that window opens it adds event listener to listen to when the window completes load...
... in the new window, selecting tabs will fire the alert. ...
...arguments.callee, false); //this removes this load function from the window //window has now loaded now do stuff to it //as example this will add a function to listen to tab select and will fire alert in that window if (domWindow.gBrowser && domWindow.gBrowser.tabContainer) { domWindow.gBrowser.tabContainer.addEventListener('TabSelect', function
() { domWindow.alert('tab was selected') }, false); } }, false); }, onCloseWindow: function (aWindow) {}, onWindowTitleChange: function (aWindow, aTitle) {} }; //to register Services.wm.addListener(windowListener); //Services.wm.removeListener(windowListener); //once you want to remove this listener execute removeListener, current...
...And 11 more matches
nsIWindowWatcher
must notify this component when they are created or destroyed, so only a weak reference is kept. Note that there is no interface for such notifications (not a public one, anyway). This is taken care of both in Mozilla and by common embedding code. Embedding clients need do nothing special about that requirement. This component must be initialized at application startup by calling setWindowCreator
(). ...
...artup by calling setWindowCreator
(). ...
...ow The Watcher serves as a global storage facility for the current active (front most non-floating-palette-type) window, storing and returning it on demand. Users must keep this attribute current, including after the topmost window is closed. This attribute will be null if the active window is not an nsIDOMWindow; for example, if the active window is an alert. Methods getChromeForWindow
() Retrieve the chrome window mapped to the given DOM window. nsIWindowWatcher keeps a list of all top-level DOM windows currently open, along with their corresponding chrome interfaces. Since DOM Windows lack a (public) means of retrieving their corresponding chrome, this method will do that. nsIWebBrowserChrome getChromeForWindow( in nsIDOMWindow aWindow ); Parameters aWindow The nsIDOMW...
...And 11 more matches
nsIXPCScriptable
NG_RESOLVE 1 << 24 ALLOW_PROP_MODS_TO_PROTOTYPE 1 << 25 DONT_SHARE_PROTOTYPE 1 << 26 DONT_REFLECT_INTERFACE_NAMES 1 << 27 WANT_EQUALITY 1 << 28 WANT_OUTER_OBJECT 1 << 29 WANT_INNER_OBJECT 1 << 30 RESERVED 1 << 31 The high order bit is RESERVED for consumers of these flags. No implementor of this interface should ever return flags with this bit set. ...
...T_INNER_OBJECT 1 << 30 RESERVED 1 << 31 The high order bit is RESERVED for consumers of these flags. No implementor of this interface should ever return flags with this bit set. ...
...urn flags with this bit set. ...
...And 11 more matches
Standard OS Libraries
winapi - WinAPI js-ctypes snippets that can be copied and pasted to scratchpad COM See Using COM from js-ctypes. UNIX Unix based operating systems are Linux, *BSD, Solaris, etc. There is a star/asterik...
...winapi - WinAPI js-ctypes snippets that can be copied and pasted to scratchpad COM See Using COM from js-ctypes. UNIX Unix based operating systems are Linux, *BSD, Solaris, etc. There is a star/asterik ("*") before "BSD" because this means t...
...POINT", [ { "x": ctypes.long }, { "y": ctypes.long } ]); /* Declare the signature of the function we are going to call */ var GetCursorPos = lib.declare('GetCursorPos', ctypes.winapi_abi, ctypes.bool, POINT.ptr ); /* Use it like this */ var point = POINT
(); var ret = GetCursorPos(point.address
()); Components.utils.reportError(ret); Components.utils.reportError(point); lib.close
(); Resources for WinAPI GitHubGISTS :: Noitidart / Search . winapi - WinAPI js-ctypes snippets that can be copied and pasted to scratchpad COM See Using COM from js-ctypes. UNIX Unix based operating systems are Linux, *BSD, Solaris, etc. There is a star/asterik ("*") before "BSD" because this means the BSD family such as FreeBSD, OpenBSD (who by the way made ssh), NetBSD, etc. GTK+ and...
...And 11 more matches
Waterfall - Firefox Developer Tools
ctures. Like garbage collection, but for C++ objects. See Kyle Huey's blog post about cycle collection. Type Always "Collect". CC Graph Reduction Preparation/pre-optimization for Cycle Collection. Type Always "ForgetSkippable". Console The period between matching calls to console.time
() and console.timeEnd
(). Timer name The argument passed to the console functions. Stack at start Call stack console.time
(), with links to functions. Stack at End (New in Firefox 41). Call stack at console.timeEnd
(). If this is inside a callback from a Promise, this will also show the "Async stack". Timestamp A single call to...
... DOMContentLoaded The document's DOMContentLoaded event. Load The document's load event. Worker event in main thread Shown when the main thread sends a message to a worker, or receives a message from a worker. ...
... DOMContentLoaded The document's DOMContentLoaded event. Load The document's load event. Worker event in main thread Shown when the main thread sends a message to a worker, or receives a message from a worker. ...
...And 11 more matches
DOMMatrixReadOnly - Web APIs
s. These are aliases for specific components of a 4x4 matrix, as shown below. 2D 3D equivalent a m11 b m12 c m21 d m22 e m41 f m42 Methods This interface doesn't inherit any methods. None of the following methods alter the original matrix. DOMMatrixReadOnly.flipX
() Returns a new DOMMatrix created by flipping the source matrix around its X-axis. This is equivalent to multiplying the matrix by DOMMatrix(-1, 0, 0, 1, 0, 0). The original matrix is not modified. DOMMatrixReadOnly.flipY
() Returns a new DOMMatrix created by flipping the source matrix around its Y-axis. This is equivalent to multiplying the matrix by DOMMatrix(1, 0, 0, -1, 0, 0). The original ...
...source matrix around its X-axis. This is equivalent to multiplying the matrix by DOMMatrix(-1, 0, 0, 1, 0, 0). The original matrix is not modified. DOMMatrixReadOnly.flipY
() Returns a new DOMMatrix created by flipping the source matrix around its Y-axis. This is equivalent to multiplying the matrix by DOMMatrix(1, 0, 0, -1, 0, 0). The original matrix is not modified. DOMMatrixReadOnly.inverse
() Returns a new DOMMatrix created by inverting the source matrix. If the matrix cannot be inverted, the new matrix's components are all set to NaN and its is2D property is set to false. The original matrix is not altered. DOMMatrixReadOnly.multiply
() Returns a new DOMMatrix created by computing the dot product of the source matrix and the specified matrix: A?B. If no matrix is specified as the m...
...created by computing the dot product of the source matrix and the specified matrix: A?B. If no matrix is specified as the multiplier, the matrix is multiplied by a matrix in which every element is 0 except the bottom-right corner and the element immediately above and to its left: m33 and m34. These have the default value of 1. The original matrix is not modified. ...
...And 11 more matches
HTMLMediaElement - Web APIs
eeking Read only Returns a Boolean that indicates whether the media is in the process of seeking to a new position. HTMLMediaElement.sinkId Read only Returns a DOMString that is the unique ID of the audio device delivering output, or an empty string if it is using the user agent default. This ID should be one of the MediaDeviceInfo.deviceid values returned from MediaDevices.enumerateDevices
(), id-multimedia, or id-communications. HTMLMediaElement.src Is a DOMString that reflects the src HTML attribute, which contains the URL of a media resource to use. HTMLMediaElement.srcObject Is a MediaStream representing the media to play or that has played in the current HTMLMediaElement, or null if not assigned. HTMLMediaElement.textTracks Read only Returns the list of TextTrack objects c...
...nted for Firefox OS, and was removed in Firefox 55. HTMLMediaElement.onmozinterruptend Sets the EventHandler called when the interruption is concluded. This was Firefox-specific, having been implemented for Firefox OS, and was removed in Firefox 55. Methods This interface also inherits methods from its ancestors HTMLElement, Element, Node, and EventTarget. ...
...ntHandler called when the interruption is concluded. This was Firefox-specific, having been implemented for Firefox OS, and was removed in Firefox 55. Methods This interface also inherits methods from its ancestors HTMLElement, Element, Node, and EventTarget. HTMLMediaElement.addTextTrack
() Adds a text track (such as a track for subtitles) to a media element. HTMLMediaElement.captureStream
() Returns MediaStream, captures a stream of the media content. ...
...And 11 more matches
Using Pointer Events - Web APIs
rse, also be a stylus, mouse, or other method of pointing at a location. Create a canvas The touch-action property is set to none to prevent the browser from applying its default touch behavior to the application. <canvas id="canvas" width="600" height="600" style="border:solid black 1px; touch-action:none"> Your browser does not support canvas element. ...
...er from applying its default touch behavior to the application. <canvas id="canvas" width="600" height="600" style="border:solid black 1px; touch-action:none"> Your browser does not support canvas element. ...
...ement. </canvas> <br> <button onclick="startup
()">Initialize</button> <br> Log: <pre id="log" style="border: 1px solid #ccc;"></pre> Setting up the event handlers When the page loads, the startup
() function shown below should be called by our <body> element's onload attribute (but in the example we use a button to trigger it, due to limitations of the MDN live example system). ...
...And 11 more matches
Range - Web APIs
Properties There are no inherited properties. Range.collapsed Read only Returns a Boolean indicating whether the range's start and end points are at the same position. ...
... Properties There are no inherited properties. Range.collapsed Read only Returns a Boolean indicating whether the range's start and end points are at the same position. ...
... Properties There are no inherited properties. Range.collapsed Read only Returns a Boolean indicating whether the range's start and end points are at the same position. ...
...And 11 more matches
WebGL model view projection - Web APIs
are rendered on top of the larger Z values. WebGLBox example This example will create a custom WebGLBox object that will draw a 2D box on the screen. Note: The code for each WebGLBox example is available in this github repo and is organized by section. In addition there is a JSFiddle link at the bottom of each section. ...
... settings.depth, settings.right, settings.bottom, settings.depth, settings.right, settings.top, settings.depth ]); // Use WebGL to draw this onto the screen. // Performance Note: Creating a new array buffer for every draw call is slow. // This function is for illustration purposes only. ...
....uniform4fv(this.colorLocation, settings.color); // Draw the triangles to the screen gl.drawArrays(gl.TRIANGLES, 0, 6); } The shaders are the bits of code written in GLSL that take our data points and ultimately render them to the screen. For convenience, these shaders are stored in a <script> element that is brought into the program through the custom function MDN.createWebGLProgramFromIds
(). This function is part of a collection of utility functions written for these tutorials and is not explained in depth here. This function handles the basics of taking some GLSL source code and compiling it into a WebGL program. The function takes three parameters -- the context to render the program in, the ID of the <script> element containing the vertex shader, and the ID of the <script> elem...
...And 11 more matches
WritableStreamDefaultWriter - Web APIs
Properties WritableStreamDefaultWriter.closedRead only Allows you to write code that responds to an end to the streaming process. Returns a promise that fulfills if the stream becomes closed or the writer's lock is released, or rejects if the stream errors. ...
... Properties WritableStreamDefaultWriter.closedRead only Allows you to write code that responds to an end to the streaming process. Returns a promise that fulfills if the stream becomes closed or the writer's lock is released, or rejects if the stream errors. ...
...tableStreamDefaultWriter.desiredSizeRead only Returns the desired size required to fill the stream's internal queue. WritableStreamDefaultWriter.readyRead only Returns a Promise that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. Methods WritableStreamDefaultWriter.abort
() Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. WritableStreamDefaultWriter.close
() Closes the associated writable stream. WritableStreamDefaultWriter.releaseLock
() Releases the writer's lock on the corresponding stream. After the lock is released, the wri...
...And 11 more matches
Using CSS transitions - CSS: Cascading Style Sheets
operty: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration: 0.5s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transformv color; transition-duration: 0.5s; transition-timing-function: ease-in-out; } function updateTransition
() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-duration: 1s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .bo...
...on-property: width height background-color font-size left top -webkit-transform transform color; -webkit-transition-duration: 1s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration: 1s; transition-timing-function: ease-in-out; } function updateTransition
() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-duration: 2s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .bo...
...on-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration: 2s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration: 2s; transition-timing-function: ease-in-out; } function updateTransition
() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-duration: 4s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .bo...
...And 11 more matches
color - CSS: Cascading Style Sheets
lone https://github.com/mdn/interactive-examples and send us a pull request. For an overview of using color in HTML, see Applying color to HTML elements using CSS. ...
... Note that the value must be a uniform color. It can't be a <grad...
...x or larger. WebAIM: Color Contrast Checker MDN Understanding WCAG, Guideline 1.4 explanations Understanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0 Formal definition Initial valueVaries from one browser to anotherApplies toall elements. ...
...And 11 more matches
Audio and Video Delivery - Developer guides
h video -- just remember to set isvideo=true in the flashvars value parameters. More options for Fallbacks. JavaScript Audio var myAudio = document.createElement('audio'); if (myAudio.canPlayType('audio/mpeg')) { myAudio.setAttribute('src','audiofile.mp3'); } else if (myAudio.canPlayType('audio/ogg')) { myAudio.setAttribute('src','audiofile.ogg'); } myAudio.currentTime = 5; myAudio.play
(); We set the source of the audio depending on the type of audio file the browser supports, then set the play-head 5 seconds in and attempt to play it. Note: Play will be ignored by most browsers unless issued by a user-initiated event. It's also possible to feed an <audio> element a base64 encoded WAV file, allowing to generate audio on the fly: <audio id="player" src="data:audio/x-wav;base6...
...src','videofile.mp4'); } else if (myVideo.canPlayType('video/webm')) { myVideo.setAttribute('src','videofile.webm'); } myVideo.width = 480; myVideo.height = 320; We set the source of the video depending on the type of video file the browser supports we then set the width and height of the video. ...
...Video.canPlayType('video/webm')) { myVideo.setAttribute('src','videofile.webm'); } myVideo.width = 480; myVideo.height = 320; We set the source of the video depending on the type of video file the browser supports we then set the width and height of the video. ...
...And 11 more matches
<input type="button"> - HTML: Hypertext Markup Language
addEventListene...
...{ if (button.value === 'Start machine') { button.value = 'Stop machine'; paragraph.textContent = 'The machine has started!'; } else { button.value = 'Start machine'; paragraph.textContent = 'The machine is stopped.'; } } The script gets a reference to the HTMLInputElement object representing the <input> in the DOM, saving this refence in the variable button. addEventListener
() is then used to establish a function that will be run when click events occur on the button. Adding keyboard shortcuts to buttons Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a button -- just as you would with any <input> for which it makes sense -- you us...
... to press s plus the particular modifier keys for your browser/OS combination; see accesskey for a useful list of those). ...
...And 11 more matches
Details of the object model - JavaScript
the inheritance occurs. The following Java and JavaScript Employee definitions are similar. The only difference is that you need to specify the type for each property in Java but not in JavaScript (this is due to Java being a strongly typed language while JavaScript is a weakly typed language). JavaScript (using this may cause an error for the following examples) class Employee { constructor
() { this.name = ''; this.dept = 'general'; } } JavaScript ** (use this instead) function Employee
() { this.name = ''; this.dept = 'general'; } Java public class Employee { public String name = ""; public String dept = "general"; } The Manager and WorkerBee definitions show the difference in how to specify the next object higher in the inheritance chain. In JavaScri...
...n JavaScript, you add a prototypical instance as the value of the prototype property of the constructor function, then override the prototype.constructor to the constructor function. You can do so at any time after you define the constructor. In Java, you specify the superclass within the class definition. You cannot change the superclass outside the class definition. ...
...ructor function. You can do so at any time after you define the constructor. In Java, you specify the superclass within the class definition. You cannot change the superclass outside the class definition. ...
...And 11 more matches
TypedArray - JavaScript
bigint int64_t (signed long long) BigUint64Array 0 to 264-1 8 64-bit unsigned integer bigint uint64_t (unsigned long long) Constructor This object cannot be instantiated directly. Instead, you create an instance of an array of a particular type, such as a Int8Array or a BigInt64Array. These objects all have a common syntax for their constructors: new TypedArray
(); new TypedArray(length); new TypedArray(typedArray); new TypedArray(object); new TypedArray(buffer [, byteOffset [, length]]); Where TypedArray is a constructor for one of the concrete types. Parameters length When called with a length argument, an internal array buffer is created in memory, of size length multiplied by BYTES_PER_ELEMENT bytes, containing zeros. typedArray When called wi...
...array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the typedArray argument. object When called with an object argument, a new typed array is created as if by the TypedArray.from
() method. buffer, byteOffset, length When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified ArrayBuffer. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is vie...
.... Static properties TypedArray.BYTES_PER_ELEMENT Returns a number value of the element size for the different TypedArray objects. TypedArray.name Returns the string value of the constructor name (e.g, "Int8Array"). get TypedArray[@@species] The constructor function used to create derived objects. TypedArray.prototype Prototype for TypedArray objects. Static methods TypedArray.from
() Creates a new TypedArray from an array-like or iterable object. See also Array.from
(). TypedArray.of
() Creates a new TypedArray with a variable number of arguments. See also Array.of
(). Instance properties TypedArray.prototype.buffer Returns the ArrayBuffer referenced by the typed array. Fixed at construction time and thus read only. TypedArray.prototype.byteLength Returns the length (...
...And 11 more matches
for await...of - JavaScript
tatement } variable On each iteration a value of a different property is assigned to variable. variable may be declared with const, let, or var. iterable Object whose iterable properties are to be iterated over. ...
...on a value of a different property is assigned to variable. variable may be declared with const, let, or var. iterable Object whose iterable properties are to be iterated over. ...
...ting over async iterables You can also iterate over an object that explicitly implements async iterable protocol: const asyncIterable = { [Symbol.asyncIterator]
() { return { i: 0, next
() { if (this.i < 3) { return Promise.resolve({ value: this.i++, done: false }); } return Promise.resolve({ done: true }); } }; } }; (async function
() { for await (let num of asyncIterable) { console.log(num); } })
(); // 0 // 1 // 2 Iterating over async generators Since the return values of async generators conform to the async iterable protocol, they can be looped using for await...of. async function* asyncGenerator
() { let i = 0; while (i < 3) { yield i++; } } (async function
() { for await (let num of asyncGenerat...
...And 11 more matches
function* - JavaScript
tool for asynchronous programming as they mitigate -- if not entirely eliminate -- the problems with callbacks, such as Callback Hell and Inversion of Control. However, an even simpler solution to these problems can be achieved with async functions. Calling a generator function does not execute its body immediately; an iterator object for the function is returned instead. When the iterator's next
() method is called, the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function. The next
() method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value, as a boolean. C...
...ed, the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function. The next
() method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value, as a boolean. Calling the next
() method with an argument will resume the generator function execution, replacing the yield expression where an execution was paused with the argument from next
(). A return statement in a generator, when executed, will make the generator finish (i.e. the done property of the object returned by it will be set to true). If a value is returned, it will be set as the value property of the object retur...
... make the generator finish (i.e. the done property of the object returned by it will be set to true). If a value is returned, it will be set as the value property of the object returned by the generator. Much like a return statement, an error is thrown inside the generator will make the generator finished -- unless caught within the generator's body. ...
...And 11 more matches
Understanding WebAssembly text format - WebAssembly
with the example, save the above our module into a file called add.wat, then convert it into a binary file called add.wasm using wabt (see Converting WebAssembly text format to wasm for details). Next, we'll load our binary into a typed array called addCode (as described in Fetching WebAssembly Bytecode), compile and instantiate it, and execute our add function in JavaScript (we can now find add
() in the exports property of the instance): WebAssembly.instantiateStreaming(fetch('add.wasm')) .then(obj => { console.log(obj.instance.exports.add(1, 2)); // "3" }); Note: You can find this example in GitHub as add.html (see it live also). Also see WebAssembly.instantiateStreaming
() for more details about the instantiate function. Exploring fundamentals Now we've covered the real ba...
... as. This is functionally equivalent to including a separate function statement outside the function, elsewhere in the module in the same manner as we did before, e.g.: (export "getAnswerPlus1" (func $functionName)) The JavaScript code to call our above module looks like so: WebAssembly.instantiateStreaming(fetch('call.wasm')) .then(obj => { console.log(obj.instance.exports.getAnswerPlus1
()); // "43" }); Importing functions from JavaScript We have already seen JavaScript calling WebAssembly functions, but what about WebAssembly calling JavaScript functions? WebAssembly doesn't actually have any built-in knowledge of JavaScript, but it does have a general way to import functions that can accept either JavaScript or wasm functions. Let's look at an example: (module (import "co...
...ced above. Imported functions are just like normal functions: they have a signature that WebAssembly validation checks statically, and they are given an index and can be named and called. JavaScript functions have no notion of signature, so any JavaScript function can be passed, regardless of the import's declared signature. Once a module declares an import, the caller of WebAssembly.instantiate
() must pass in an import object that has the corresponding properties. For the above, we need an object (let's call it importObject) such that importObject.console.log is a JavaScript function. This would look like the following: var importObject = { console: { log: function(arg) { console.log(arg); } } }; WebAssembly.instantiateStreaming(fetch('logger.wasm'), importObject) ...
...And 11 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
in examples. Resource mappings for files in the mozilla distribution, such as Services.jsm (above), will continue to work. In overlay extensions, you can place a resource mapping in the chrome.manifest for your add-on and load your own JSM from resource:// URIs. It's a great way to modularize your code that's been available since Firefox 3. You can use chrome:// URIs with "Components.utils.import
()" just fine; in fact you've been able to since Firefox 4. However, because it was implemented first for only file:// and resource:// but not chrome://, everyone who learned of this new feature learned that you had to load JSM from resource:// URIs and just stuck with that forever. It does still work if you don't have restartlessness to worry about, though the protocol (or scheme, or whatever term ...
...interface. If you need to read data, or otherwise access files within your bundle, there are two options. The first is to use the nsIZipReader interface which permits continuing to use nsIInputStreams, etc. The second is to re-code to use XMLHttpRequest. A file:// URI to the install location, or .xpi file, is available in installPath property of the bootstrap data structure passed to the startup
(), shutdown
(), install
(), and uninstall
() functions in what will be your bootstrap.js file (see below). How to get and load the data of of your add-on's files using the Add-on Manager API: // This is the OLD way of getting one of your files const myAddonID = ...; // Just store a constant with your ID Components.utils.import("resource://gre/modules/AddonManager.jsm"); AddonManager.getAddonByID(my...
... and best way to do things. ...
...And 10 more matches
Introducing the Audio API extension - Archive of obsolete content
his information is needed later to decode the audio data stream. ...
...the previous example to visualize the timestamp and the first two samples in a <div> element: <!DOCTYPE html> <html> <head> <title>JavaScript Visualization Example</title> </head> <body> <audio id="audio-element" src="revolve.ogg" controls="true" style="width: 512px;"> </audio> <pre id="raw">hello</pre> <script> function loadedMetadata
() { channels = audio.mozChannels; rate = audio.mozSampleRate; frameBufferLength = audio.mozFrameBufferLength; } function audioAvailable(event) { var frameBuffer = event.frameBuffer; var t = event.time; var text = "Samples at: " + t + "\n"; text += frameBuffer[0] + " " + frameBuffer[1]; raw.inne...
... audio.addEventListener('loadedmetadata', loadedMetadata, false); </script> </body> </html> Creating an audio stream It is also possible to create and setup an <audio> element for raw writing from script (i.e., without a src attribute). Content scripts can specify the audio stream's characteristics, then write audio samples. Users must create an audio object and then use the mozSetup
() function to specify the number of channels and the frequency (in Hz). For example: // Create a new audio element var audioOutput = new Audio
(); // Set up audio element with 2 channel, 44.1KHz audio stream. audioOutput.mozSetup(2, 44100); Once this is done, the samples need to be created. Those samples have the same format as the ones in the mozAudioAvailable event. Then the samples are writte...
...And 10 more matches
Monitoring downloads - Archive of obsolete content
the download speed, and the status of the download. A tooltip is included that displays the full source URL of the file. Download the full sample. Setting up When the extension loads, it will do some housekeeping chores. In particular, it needs to get an instance of the Download Manager's nsIDownloadManager interface and create the database into which its data will be stored. ...
...The database file is opened, and an sqlite CREATE TABLE command is executed to create the table. Finally, the database is closed. Note: The mozIStorageConnection met...
...on't care! dbConn.executeSimpleSQL("CREATE TABLE items (source TEXT, size INTEGER," + " startTime INTEGER, endTime INTEGER," + " speed REAL, status INTEGER)"); dbConn.close
(); }, This is fairly simple stuff. The Download Manager instance is cached into a member variable in the downloadlogger object for reuse later, and its addListener
() method is called to start listening for download status updates. The database file is opened, and an sqlite CREATE TABLE command is executed to create the table. Finally, the database is closed. Note: The mozIStorageConnection method close
() is being added to Firefox 3 alpha 8; in prior versions of Firefox, there is no way to explicitly close the database. Instead, it is closed when the garbage...
...And 10 more matches
Modifying a XUL Interface - Archive of obsolete content
<< PreviousNext >> The DOM provides various functions to modify the document. Creating New Elements You can create new elements using the createElement
() function of the document. It takes one argument, the tag name of the element to create. You can then set attributes of the element using the setAttribute
() function and append it to the XUL document using the appendChild
() function. ...
...You can create new elements using the createElement
() function of the document. It takes one argument, the tag name of the element to create. You can then set attributes of the element using the setAttribute
() function and append it to the XUL document using the appendChild
() function. For example, the following will add a button to a XUL window: Example 1 : Source View <script> function addButton
(){ var aBox = document.getElementById("aBox"); var button = document.createElement("button"); button.setAttribute("label","A new Button"); aBox.appendChild(button); } </script> <box id="aBox" width="200"> <button label="Add" oncommand="addButton
();"/> </box> This example has two parts a box container element in XUL. Notice that this is NOT the same as a vbox or an hbox. (T...
...tice that this is NOT the same as a vbox or an hbox. (This is discussed more in the Box Model pages.) the box element has two attributes "id" and "width". the box element contains a button element. the button element has two attributes "label" and "oncommand" a Javascript function named "addButton
()" This script first gets a reference to the box with getElementById
(), which is the container to add a new button to. The function getElementbyID
() does not know that the box it is looking for happens to be containing the tag that has the oncommand attribute that referenced it. getElementById
() only knows the box it is looking to find has an id with the value "aBox". This is a s...
...And 10 more matches
NPObject - Archive of obsolete content
ects exposed by either the plugin or by the browser through this API. The browsers are expected to expose their window objects and everything reachable from it through this API. NPObjects are reference counted objects, so callers need to be careful to properly release acquired references to them. To aid with the reference counting and ownership management in general, the functions NPN_CreateObject
(), NPN_RetainObject
(), NPN_ReleaseObject
(), and NPN_ReleaseVariantValue
() are provided as part of this API. NPObject behavior is implemented using the set of callback functions defined in NPClass. Syntax struct NPObject { NPClass *_class; uint32_t referenceCount; /* * Additional space may be allocated here by types of NPObjects */ }; Fields _class A pointer to the NPC...
...Count; /* * Additional space may be allocated here by types of NPObjects */ }; Fields _class A pointer to the NPClass of which the object is a member. referenceCount The reference count for the object. ...
...tional space may be allocated here by types of NPObjects */ }; Fields _class A pointer to the NPClass of which the object is a member. referenceCount The reference count for the object. ...
...And 10 more matches
Archived JavaScript Reference - Archive of obsolete content
er property used to provide the function that invoked the currently executing function. This property has been removed and no longer works.Array comprehensionsThe array comprehension syntax was a JavaScript expression which allowed you to quickly assemble a new array based on an existing one. However, it has been removed from the standard and the Firefox implementation. Do not use it!Array.observe
()The Array.observe
() method was used for asynchronously observing changes to Arrays, similar to Object.observe
() for objects. It provided a stream of changes in order of occurrence. It's equivalent to Object.observe
() invoked with the accept type list ["add", "update", "delete", "splice"]. However, this API has been deprecated and removed from Browsers. You can use the more general Proxy object ins...
...method was used for asynchronously observing changes to Arrays, similar to Object.observe
() for objects. It provided a stream of changes in order of occurrence. It's equivalent to Object.observe
() invoked with the accept type list ["add", "update", "delete", "splice"]. However, this API has been deprecated and removed from Browsers. You can use the more general Proxy object instead.Array.unobserve
()The Array.unobserve
() method was used to remove observers set by Array.observe
(), but has been deprecated and removed from Browsers. You can use the more general Proxy object instead.ArrayBuffer.transfer
()The static ArrayBuffer.transfer
() method returns a new ArrayBuffer whose contents have been taken from the oldBuffer's data and then is either truncated or zero-extended by newByteLength. If newB...
...he more general Proxy object instead.ArrayBuffer.transfer
()The static ArrayBuffer.transfer
() method returns a new ArrayBuffer whose contents have been taken from the oldBuffer's data and then is either truncated or zero-extended by newByteLength. If newByteLength is undefined, the byteLength of the oldBuffer is used. This operation leaves oldBuffer in a detached state.Date.prototype.toLocaleFormat
()The non-standard toLocaleFormat
() method converts a date to a string using the specified formatting. Intl.DateTimeFormat is an alternative to format dates in a standards-compliant way. ...
...And 10 more matches
Desktop mouse and keyboard controls - Game development
event.keyCode == 38) { upPressed = true; } } The keyUpHandler looks almost exactly the same as the keyDownHandler above, but instead of setting the pressed variables to true, we would set them to false. ...
...mobile or a click on desktop. That way, if you already implemented the buttons as shown in the Mobile touch controls article, it will work out of the box on the desktop too: var buttonEnclave = this.add.button(10, 10, 'logo-enclave', this.clickEnclave, this); The button will be placed ten pixels from the top left corner of the screen, use the logo-enclave image, and will execute the clickEnclave
() function when clicked. We can assign actions directly to the buttons: this.buttonShoot = this.add.button(this.world.width*0.5, 0, 'button-alpha', null, this); this.buttonShoot.onInputDown.add(this.shootingPressed, this); this.buttonShoot.onInputUp.add(this.shootingReleased, this); The button used for shooting works perfectly fine on both the mobile and desktop approach. If you want to use the ...
...r.rightButton.isDown; Keep in mind that instead of mousePointer, it's better to use activePointer for platform independent input if you want to keep the support for mobile touch interactions. Keyboard The whole game can be controlled with just the keyboard and nothing else. The built in this.game.input.keyboard object manages the input from the keyboard and has a few helpful methods like addKey
() and isDown
(). There's also the Phaser.KeyCode object, which contains all the available keyboard keys: In the main menu of the game we can add an extra way to begin playing. The Start button can be clicked to do so, but we can use the Enter key to do the same: var keyEnter = this.game.input.keyboard.addKey(Phaser.KeyCode.ENTER); var keyEnter.onDown.add(this.clickStart, this); You can use addK...
...And 10 more matches
Implementing controls using the Gamepad API - Game development
API -- gamepadconnected and gamepaddisconnected. ...
...amepaddisconnected. ...
...irst one is fired when the browser detects the connection of a new gamepad while the second one is fired when a gamepad is disconnected (either physically by the user or due to inactivity.) In the demo, the gamepadAPI object is used to store everything related to the API: var gamepadAPI = { controller: {}, turbo: false, connect: function
() {}, disconnect: function
() {}, update: function
() {}, buttonPressed: function
() {}, buttons: [], buttonsCache: [], buttonsStatus: [], axesStatus: [] }; The buttons array contains the Xbox 360 button layout: buttons: [ 'DPad-Up','DPad-Down','DPad-Left','DPad-Right', 'Start','Back','Axis-Left','Axis-Right', 'LB','RB','Power','A','B','X','Y', ], This can be different for other types of gamepads like the PS3 controller (or a no-na...
...And 10 more matches
Introduction to web APIs - Learn web development
an HTML <canvas> element to create 2D and 3D scenes. For example, you might draw shapes such as rectangles or circles, import an image onto the canvas, and apply a filter to it such as sepia or grayscale using the Canvas API, or create a complex 3D scene with lighting and textures using WebGL. Such APIs are often combined with APIs for creating animation loops (such as window.requestAnimationFrame
()) and others to make constantly updating scenes like cartoons and games. Audio and Video APIs like HTMLMediaElement, the Web Audio API, and WebRTC allow you to do really interesting things with multimedia such as creating custom UI controls for playing audio and video, displaying text tracks like captions and subtitles along with your videos, grabbing video from your web camera to be manipulated ...
...ton> that we'll use to play and stop the music, and an <input> element of type range, which we'll use to adjust the volume of the track while it's playing. Next, let's look at the JavaScript for this example. ...
...ying. Next, let's look at the JavaScript for this example. ...
...And 10 more matches
Object prototypes - Learn web development
up the chain of prototypes. Note: It's important to understand that there is a distinction between an object's prototype (available via Object.getPrototypeOf(obj), or via the deprecated __proto__ property) and the prototype property on constructor functions. The former is the property on each instance, and the latter is the property on the constructor. That is, Object.getPrototypeOf(new Foobar
()) refers to the same object as Foobar.prototype. Let's look at an example to make this a bit clearer. Understanding prototype objects Here we'll go back to the example in which we finished writing our Person
() constructor -- load the example in your browser. You can use our oojs-class-further-exercises.html example (see also the source code), if you don't already have it from working through t...
...mary above for full definition } We have then created an object instance like this: let person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']); If you type "person1." into your JavaScript console, you should see the browser try to auto-complete this with the member names available on this object: In this list, you will see the members defined on person1's constructor -- Person
() -- name, age, gender, interests, bio, and greeting. You will however also see some other members -- toString, valueOf, etc -- these are defined on person1's prototype object's prototype object, which is Object.prototype. What happens if you call a method on person1, which is actually defined on Object.prototype? For example: person1.valueOf
() valueOf
() returns the value of the object it is c...
...eOf, etc -- these are defined on person1's prototype object's prototype object, which is Object.prototype. What happens if you call a method on person1, which is actually defined on Object.prototype? For example: person1.valueOf
() valueOf
() returns the value of the object it is called on. In this case, what happens is: The browser initially checks to see if the person1 object has a valueOf
() method available on it, as defined on its constructor, Person
(), and it doesn't. So the browser checks to see if the person1's prototype object has a valueOf
() method available on it. It doesn't, then the browser checks person1's prototype object's prototype object, and it has. So the method is called, and all is good! Note: We want to reiterate that the methods and properties are not copied ...
...And 10 more matches
Application cache implementation overview
Channels having that flag set are searching for nsIApplicationCache object prior inspecting normal HTTP cache. nsIApplicationCacheService::ChooseApplicationCache is given the URL the channel is about to load. It synchronously returns an nsIApplicationCache object representing the most recent cache version from the most recent cache group containing the entry under the URL or a matching namespace. ...
...top level document with offline cache This happens between document load start and the first sub-resource download start and is not about associating nsIApplicationCache object with the channel, but with the document object the load is performed for. Until steps described further the document doesn't know anything about its appcache. The association happens in nsContentSink::ProcessOfflineManifest
() called from the HTML parser every time <html> tag has been parsed. ProcessOfflineManifest is an effective implementation of "cache selection algorithm" as described by the HTML5 spec. For purpose of this documentation it's enough to describe the simplest case ; for complete documentation of the selection algorithm refer to the spec or to the code. When the URL in the manifest attribute of the htm...
...anifest attribute of the html tag is identical to the manifest URL the channel's nsIApplicationCache object belongs to and, the channel's LoadedFromApplicationCache flag is set, the document is associated with that nsIApplicationCache object and an update attempt for the manifest is scheduled after the document completely loads. Marking entries as foreign When nsContentSink::ProcessOfflineManifest
() discovers that the URL in the manifest attribute of the html tag is different from the manifest URL the channel's nsIApplicationCache object belongs to, the entry the document has been loaded from is marked "Foreign" and the page load is completely restarted. The load starts again from the top with a completely new channel. But this time the entry is not selected to load the top level document fr...
...And 10 more matches
Choosing the right memory allocator
and tries to sort out which should be used under what circumstances. Allocating memory in XPCOM These are general purpose memory-management routines that you should use unless your code falls into one of the other categories below. Use these if you link against XPCOM or XPCOM Glue; this includes extensions with binary components. See the XPCOM string guide for additional information. NS_Alloc
() == nsIMemory::alloc
() NS_Realloc
() == nsIMemory::realloc
() NS_Free
() == nsIMemory::free
() nsMemory::Clone
() (note: not part of nsIMemory) See Infallible memory allocation for information about how to allocate memory infallibly; that is, how to use memory allocators that will only return valid memory buffers, and never return null. Allocating strings in XPCOM code See "Callee-allocated Para...
...These methods convert ns*String to nsIMemory allocated, unowned [PRUni]char* buffers. Do not use nsCRT::strdup for returning values from an XPCOM object, as that uses a different allocator. ...
...These methods convert ns*String to nsIMemory allocated, unowned [PRUni]char* buffers. Do not use nsCRT::strdup for returning values from an XPCOM object, as that uses a different allocator. ...
...And 10 more matches
Deferred
A Deferred object is returned by the obsolete Promise.defer
() method to provide a new promise along with methods to change its state. Starting from Gecko 30, this object is obsolete and should not be used anymore. Use the new Promise
() constructor instead (or use the above backwards/forwards compatible Deferred function given below). ...
... A Deferred object is returned by the obsolete Promise.defer
() method to provide a new promise along with methods to change its state. Starting from Gecko 30, this object is obsolete and should not be used anymore. Use the new Promise
() constructor instead (or use the above backwards/forwards compatible Deferred function given below). ...
... provide a new promise along with methods to change its state. Starting from Gecko 30, this object is obsolete and should not be used anymore. Use the new Promise
() constructor instead (or use the above backwards/forwards compatible Deferred function given below). ...
...And 10 more matches
Finishing the Component
o obtain * global services in an application. The service manager depends * on the repository to find and instantiate factories to obtain * services. * * Users of the service manager must first obtain a pointer to the * global service manager by calling NS_GetServiceManager. After that, * they can request specific services by calling GetService. * When they are finished they can NS_RELEASE
() the service as usual. * * A user of a service may keep references to particular services * indefinitely and only must call Release when it shuts down. * * @status FROZEN */ These frozen interfaces and functions are part of the Gecko SDK. The rule of thumb is that interfaces outside of the SDK are considered "experimental" or unfrozen. See the following sidebar for information about how fr...
...nent calls the method TestA and passes an integer, 10. This works fine in any Gecko installation where a contract guarantees that the interface that was compiled against has the same signature. However, when this same component is used in a Gecko installation where this interface has changed, the method TestA does not exist in the nsIFoo interface; the first entry in the v-table is in fact IsPrime
(). When this method call is made, the code execution treats the IsPrime method as TestA. Needless to say, this is a bad thing. Furthermore, there is no way easy way to realize this error at runtime. Gecko developers could change the interface's IID, and some do. This can prevent many errors like this. But unfrozen interfaces are not supported in any formal way, and relying upon a different IID f...
...ntPolicy, which you can do by simply adding a public declaration when defining the class. At the same time, you can add the macro NS_DECL_NSICONTENTPOLICY to the class declaration that provides all of the methods defined in the interface nsIContentPolicy. The updated WebLock class looks as follows: class WebLock: public nsIObserver, public iWeblock, public nsIContentPolicy { public: WebLock
(); virtual ~WebLock
(); NS_DECL_ISUPPORTS NS_DECL_NSIOBSERVER NS_DECL_IWEBLOCK NS_DECL_NSICONTENTPOLICY private: urlNode* mRootURLNode; PRBool mLocked; }; Remember to change the nsISupports implementation macro to include nsIContentPolicy so that other parts of Gecko will know WebLock supports the nsIContentPolicy interface without modifying this macro. NS_IMPL_I...
...And 10 more matches
nsIAbCard
getProperty. See //github.com/RealityRipple/UXP/blob/master//mailnews/addrbook/public/nsIAbCard.idl for more details. ...
...le/UXP/blob/master//mailnews/addrbook/public/nsIAbCard.idl for more details. ...
...blic/nsIAbCard.idl for more details. ...
...And 10 more matches
nsIBrowserHistory
); Method overview void addPageWithDetails(in nsIURI aURI, in wstring aTitle, in long long aLastVisited); Obsolete since Gecko 15.0 void markPageAsFollowedLink(in nsIURI aURI); Obsolete since Gecko 22.0 void markPageAsTyped(in nsIURI aURI); Obsolete since Gecko 22.0 void registerOpenPage(in nsIURI aURI); Obsolete since Gecko 9.0 void removeAllPages
(); void removePage(in nsIURI aURI); void removePages([array, size_is(aLength)] in nsIURI aURIs, in unsigned long aLength, in boolean aDoBatchNotify); void removePagesByTimeframe(in long long aBeginTime, in long long aEndTime); void removePagesFromHost(in AUTF8String aHost, in boolean aEntireDomain); void removeVisitsByTimeframe(in long long aBeginTime,...
...es. Read only. lastPageVisited Obsolete since Gecko 10.0 AUTF8String The last page that was visited in a top-level window. Read only. Note: The count attribute was removed in Gecko 15.0 because it was only used to determine if there were any entries at all anyway, so the nsINavHistoryService.hasHistoryEntries attribute is better for this. Methods addPageWithDetails
() Obsolete since Gecko 15.0 (Firefox 15.0 / Thunderbird 15.0 / SeaMonkey 2.12) Note: This method was removed in Gecko 15.0. You should use mozIAsyncHistory.updatePlaces
() instead. This method adds a page to the history with specific time stamp information. It is called by history importing code and is used in the History migration tool. void addPageWithDetails( in nsIURI aUR...
...tion. It is called by history importing code and is used in the History migration tool. void addPageWithDetails( in nsIURI aURI, in wstring aTitle, in long long aLastVisited ); Parameters aURI The page that will be added to the history. aTitle The title of the page. aLastVisited When the page was last visited, in microseconds since the Unix epoch. markPageAsFollowedLink
() Obsolete since Gecko 22.0 (Firefox 22.0 / Thunderbird 22.0 / SeaMonkey 2.19) Note: This method was moved to another interface in Gecko 22.0. You should use nsINavHistoryService.markPageAsFollowedLink
() instead. This function was originally added in Gecko 2.0 (Firefox 4/Thunderbird 3.3/SeaMonkey 2.1). Designates the specified URL as coming from a link explicitly followed by th...
...And 10 more matches
nsIBrowserSearchService
hanged in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Implemented by: @mozilla.org/browser/search-service;1. To access this service, use: var browserSearchService = Components.classes["@mozilla.org/browser/search-service;1"] .getService(Components.interfaces.nsIBrowserSearchService); Attempting to use any method or attribute of this interface before init
() has completed will force the service to fall back to a slower, synchronous, initialization. This is not an issue if your code is executed in reaction to a user interaction, as initialization is complete by then, but this is an issue if your code is executed during startup. If you need to write code that is executed during startup and makes use of nsIBrowserSearchService, you should make sure th...
... to a slower, synchronous, initialization. This is not an issue if your code is executed in reaction to a user interaction, as initialization is complete by then, but this is an issue if your code is executed during startup. If you need to write code that is executed during startup and makes use of nsIBrowserSearchService, you should make sure that this code is executed from the callback to init
(). Method overview void addEngine(in AString engineURL, in long dataType, in AString iconURL, in boolean confirm, [optional] in nsISearchInstallCallback callback); void addEngineWithDetails(in AString name, in AString iconURL, in AString alias, in AString description, in AString method, in AString url); void getDefaultEngines([optional] out unsigned l...
...May be null if there are no visible search engines. defaultEngine nsISearchEngine The default search engine. Returns the first visible engine if the default engine is hidden. May be null if there are no...
...And 10 more matches
nsIIOService
This interface provides a set of URL parsing utility functions. These are provided as a convenience to the programmer and in some cases to improve performance by eliminating intermediate data structures and interfaces. Inherits from: nsISupports Last changed in Gecko 1.2 This interface duplicates many of the nsIProtocolHandler methods in a protocol handler independent way (For example newURI
() inspects the scheme in order to delegate creation of the new URI to the appropriate protocol handler). Note: nsIIOService may only be used from the main thread. Implemented by @mozilla.org/network/io-service;1 as a service: var iOService = Components.classes["@mozilla.org/network/io-service;1"] .getService(Components.interfaces.nsIIOService); Method overview boolean...
... Description offline boolean Returns true if networking is in "offline" mode. When in offline mode, attempts to access the network will fail (although this does not necessarily correlate with whether there is actually a network available -- that's hard to detect without causing the dialer to come up). Observers will be notified of changes to this attribute. Methods allowPort
() Checks if a port number is banned. This involves consulting a list of unsafe ports, corresponding to network services that may be easily exploitable. If the given port is considered unsafe, then the protocol handler (corresponding to aScheme) will be asked whether it wishes to override the IO service's decision to block the port. This gives the protocol handler ultimate control over its own secu...
... network services that may be easily exploitable. If the given port is considered unsafe, then the protocol handler (corresponding to aScheme) will be asked whether it wishes to override the IO service's decision to block the port. This gives the protocol handler ultimate control over its own security policy while ensuring reasonable, default protection. Is similar to nsIProtocolHandler.allowPort
(). boolean allowPort( in long aPort, in string aScheme ); Parameters aPort The port to check aScheme The scheme for the protocol handler that could override the IOService's decision. Return value true if the port is allowed, false otherwise. extractScheme
() Utility to extract the scheme from a URL string, consistently and according to spec (see RFC 3986). Note: Most URL parsing ...
...And 10 more matches
nsILoginManagerStorage
edHosts([optional] out unsigned long count, [retval, array, size_is(count)] out wstring hostnames); void getAllEncryptedLogins([optional] out unsigned long count, [retval, array, size_is(count)] out nsILoginInfo logins); void getAllLogins([optional] out unsigned long count, [retval, array, size_is(count)] out nsILoginInfo logins); boolean getLoginSavingEnabled(in AString aHost); void init
(); void initWithFile(in nsIFile aInputFile, in nsIFile aOutputFile); void modifyLogin(in nsILoginInfo oldLogin, in nsISupports newLoginData); void removeAllLogins
(); void removeLogin(in nsILoginInfo aLogin); void searchLogins(out unsigned long count, in nsIPropertyBag matchData, [retval, array, size_is(count)] out nsILoginInfo logins); void setLoginSavingEnabled(in AString aHost, in bo...
...Logins
(); void removeLogin(in nsILoginInfo aLogin); void searchLogins(out unsigned long count, in nsIPropertyBag matchData, [retval, array, size_is(count)] out nsILoginInfo logins); void setLoginSavingEnabled(in AString aHost, in boolean isEnabled); Attributes Attribute Type Description uiBusy boolean true when a master password prompt is being shown. Read only. Methods addLogin
() Called by the Login Manager to store a new login. Gecko 1.9.1 note Default values for the nsILoginMetaInfo properties are created if the specified login doesn't explicitly specify them. void addLogin( in nsILoginInfo aLogin ); Parameters aLogin The login to add to the login storage. countLogins
() Implement this method to return the number of logins matching the specified criteria. This...
...rn 0. aActionURL The URL of the form to which the login will be submitted. To match any form login, specify an empty string. To not match to any form login, specify null. aHttpRealm The HTTP realm for which the login applies. To match logins for any realm, specify an empty string. To not match any realm, specify null. Return value The number of logins that match the specified criteria. findLogins
() Implement this method to search the login store for logins matching the specified criteria. This method is called by the Login Manager when looking for saved logins that might apply to a form or authentication request. void findLogins( out unsigned long count, in AString aHostname, in AString aActionURL, in AString aHttpRealm, [retval, array, size_is(count)] out nsILoginInfo logins ); ...
...And 10 more matches
nsIMsgDBHdr
Headers are backed by the database: a call to these functions directly modifies the state of the database, although it is not saved until the database is committed. ...
... Indicates the account that was originally used to fetch the message. May be blank if the message has not been moved or copied. folder nsIMsgFolder Readonly: Indicates the folder in which this message is stored. propertyEnumerator nsIUTF8StringEnumerator Readonly: Enumerator for names of all database properties in the header. (new in 3.1?) Methods getProperty
() AString getProperty(in string propertyName); Parameters propertyName The name of the property to retrieve. Return Value The value of the property. setProperty
() Sets a property on the header. For the currently selected message, Thunderbird provides a utility function: setMsgHdrPropertyAndReload(aProperty, aValue); which duplicates this functionality without requiring you to grab the ...
...elected message, Thunderbird provides a utility function: setMsgHdrPropertyAndReload(aProperty, aValue); which duplicates this functionality without requiring you to grab the current header. void setProperty(in string propertyName, in AString propertyStr); Parameters propertyName The name of the property to set. propertyStr The value of the property. setStringProperty
() void setStringProperty(in string propertyName, in string propertyValue); Parameters propertyName The name of the property to set. propertyValue The value of the property. getStringProperty
() string getStringProperty(in string propertyName); Parameters propertyName The name of the property to retrieve. Return Value The value of the property. getUint3...
...And 10 more matches
nsINavHistoryResultObserver
n AUTF8String aNewTitle); void nodeURIChanged(in nsINavHistoryResultNode aNode, in AUTF8String aNewURI); void sortingChanged(in unsigned short sortingMode); Attributes Attribute Type Description result nsINavHistoryResult The nsINavHistoryResult this observer monitors. Although this attribute is read-write, you should not alter it directly; instead, call nsINavHistoryResult.addObserver
() to add an observer to a result. Methods batching
() Lets the observer know when a batch operation in Places is about to start or end. The observer can then pause updates or events until the batch is completed, so that it won't handle the large number of updates that are about to be notified. This is especially useful when updating user interfaces, to avoid flicker or continuous selection change...
...of updates that are about to be notified. This is especially useful when updating user interfaces, to avoid flicker or continuous selection changes, which may result in performance degradation (for example, if updating a view for each update). void batching( in boolean aToggleMode ); Parameters aToggleMode Specify true to start batch mode or false to finish the batch. containerClosed
() Obsolete since Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8) Called when a container node's state changes from opened to closed. Note: This method was deprecated in Gecko 2.0 and removed in Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8). Implement the containerStateChanged
() method instead. void containerClosed( in nsINavHistoryContainerResultNode...
...ntainer node's state changes from opened to closed. Note: This method was deprecated in Gecko 2.0 and removed in Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8). Implement the containerStateChanged
() method instead. void containerClosed( in nsINavHistoryContainerResultNode aContainerNode ); Parameters aContainerNode The container node which was closed. containerOpened
() Obsolete since Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8) Called when a container node's state changes from closed to opened. Note: This method was deprecated in Gecko 2.0 and removed in Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8). Implement the containerStateChanged
() method instead. void containerOpened( in nsINavHistoryContainerResultNode...
...And 10 more matches
nsIOutputStream
xpcom/io/nsIOutputStream.idlScriptable An interface describing a writable stream of data. Inherits from: nsISupports Last changed in Gecko 1.0 An output stream may be "blocking" or "non-blocking" (see the IsNonBlocking
() method). A blocking output stream may suspend the calling thread in order to satisfy a call to Close
(), Flush
(), write
(), writeFrom
(), or writeSegments
(). A non-blocking output stream, on the other hand, must not block the calling thread of execution. ...
...gments
(). A non-blocking output stream, on the other hand, must not block the calling thread of execution. Note: Blocking output streams are often written to on a background thread to avoid locking up the main application thread. For this reason, it is generally the case that a blocking output stream should be implemented using thread-safe AddRef and Release. Method overview void close
(); void flush
(); boolean isNonBlocking
(); unsigned long write(in string aBuf, in unsigned long aCount); unsigned long writeFrom(in nsIInputStream aFromStream, in unsigned long aCount); unsigned long writeSegments(in nsReadSegmentFun aReader, in voidPtr aClosure, in unsigned long aCount); Native code only! Methods close
() Close the stream. Forces...
... boolean isNonBlocking
(); unsigned long write(in string aBuf, in unsigned long aCount); unsigned long writeFrom(in nsIInputStream aFromStream, in unsigned long aCount); unsigned long writeSegments(in nsReadSegmentFun aReader, in voidPtr aClosure, in unsigned long aCount); Native code only! ...
...And 10 more matches
nsIPermissionManager
string type, in PRUint32 permission, [optional] in PRUint32 expireType, [optional] in PRInt64 expireTime); void remove(in AUTF8String host, in string type); void removeFromPrincipal(in nsIPrincipal principal, in string type); void removePermission(in nsIPermission perm); void removeAllSince(in int64_t since); void removeAll
(); PRUint32 testExactPermission(in nsIURI uri, in string type); PRUint32 testExactPermissionFromPrincipal(in nsIPrincipal principal, in string type); PRUint32 testPermission(in nsIURI uri, in string type); PRUint32 testPermissionFromPrincipal(in nsIPrincipal principal, in string type); Attributes Attribute Type Description enume...
... 2 Permission is denied. PROMPT_ACTION 3 Prompt user if the permission is allowed. Permission expiration constants Constant Value Description EXPIRE_NEVER 0 Permission never expires. EXPIRE_SESSION 1 Permission expires at end of session. EXPIRE_TIME 2 Permission expires at a specified time. Methods add
() Add permission information and permission type for a given URI. If the permission already exists for a given type, it will be modified. void add( in nsIURI uri, in string type, in PRUint32 permission, [optional] in PRUint32 expireType, [optional] in PRInt64 expireTime ); Parameters uri The URI to add the permission for. type A unique, case-sensitive ASCII string identifying th...
...d choose this string to be unique, with respect to other consumers. permission An integer specifying the permission. See nsIPermissionManager.Permission_type_constants. expireType Expiration type of the permission. See nsIPermissionManager.Permission_expiration_constants. expireTime Time (in milliseconds since Jan 1 1970 0:00:00) representing expiration of this permission. addFromPrincipal
() Add permission information and permission type for a given principal. If the permission already exists for a given type, it will be modified. It is internally calling add
() method using the nsIURI from the principal. void addFromPrincipal( in nsIPrincipal principal, in string type, in PRUint32 permission, [optional] in PRUint32 expireType, [optional] in PRInt64 expireTime ); Paramet...
...And 10 more matches
nsIRadioInterfaceLayer
.getService(Components.interfaces.nsIInterfaceRequestor) .createInstance(Components.interfaces.nsIRadioInterfaceLayer); Method overview void answerCall(in unsigned long callIndex); void deactivateDataCall(in DOMString cid, in DOMString reason); void dial(in DOMString number); void enumerateCalls(in nsIRILTelephonyCallback callback); void getDataCallList
(); unsigned short getNumberOfMessagesForText(in DOMString text); void hangUp(in unsigned long callIndex); void registerCallback(in nsIRILTelephonyCallback callback); void registerDataCallCallback(in nsIRILDataCallback callback); void rejectCall(in unsigned long callIndex); void sendSMS(in DOMString number, in DOMString message, in long requestId, in unsigned long long processId); void...
...Obsolete since Gecko 13.0 microphoneMuted bool radioState jsval Read only. speakerEnabled bool Constants Call state constants Constant Value Description CALL_STATE_UNKNOWN ...
...ED 5 CALL_STATE_HOLDING 6 CALL_STATE_HELD 7 CALL_STATE_RESUMING 8 CALL_STATE_DISCONNECTING 9 CALL_STATE_DISCONNECTED 10 CALL_STATE_INCOMING 11 DATACALL_STATE_UNKNOWN 0 DATACALL_STATE_CONNECTING 1 DATACALL_STATE_CONNECTED 2 DATACALL_STATE_DISCONNECTING 3 DATACALL_STATE_DISCONNECTED 4 CALL_STATE_RINGING 2 Obsolete since Gecko 14.0 Methods answerCall
() void answerCall( in unsigned long callIndex ); Parameters callIndex Missing Description Exceptions thrown Missing Exception Missing Description deactivateDataCall
() void deactivateDataCall( in DOMString cid, in DOMString reason ); Parameters cid Missing Description reason Missing Description Exceptions thrown Missing Exception Missing Description dial
() Functionality for making an...
...And 10 more matches
nsITransactionManager
editor/txmgr/idl/nsITransactionManager.idlScriptable This interface is implemented by an object that wants to manage/track transactions. ...
... editor/txmgr/idl/nsITransactionManager.idlScriptable This interface is implemented by an object that wants to manage/track transactions. ...
... editor/txmgr/idl/nsITransactionManager.idlScriptable This interface is implemented by an object that wants to manage/track transactions. ...
...And 10 more matches
Intensive JavaScript - Firefox Developer Tools
ate thread using a web worker. If you want to play along you can find the demo website here. There's also a video version of this walkthrough: The demo website looks like this: It has three controls: a radio button group to control how to run the JavaScript: as a single blocking operation in the main thread, as a series of smaller operations in the main thread using requestAnimationFrame
(), or in another thread using a worker. a button to run the JavaScript, labeled "Do pointless computations!". a button to start and stop some CSS animations. This just gives the browser some background tasks to perform. Leaving the radio button set to "Use blocking call in main thread", make a recording: press the "Start animations" button start recording a performance profile press "Do po...
...all view: Here, when we pressed the button, the browser ran a JavaScript function, or series of functions, that blocked the main thread for 71.73ms, or more than four times our frame budget. Which function, though? By switching to the Flame Chart view we can find out: This shows us the JS call stack at this point in the execution. ...
...int in the execution. At the top of the stack is a function called calculatePrimes
(), and we can see its filename and line number. ...
...And 10 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
d IE 5+. The DOM methods presented here are part of the Document Object Model (Core) level 1 specification. DOM level 1 includes both methods for generic document access and manipulation (DOM 1 Core) as well as methods specific to HTML documents (DOM 1 HTML). ...
...are part of the Document Object Model (Core) level 1 specification. DOM level 1 includes both methods for generic document access and manipulation (DOM 1 Core) as well as methods specific to HTML documents (DOM 1 HTML). ...
...kground color of a paragraph getElementsByTagName(tagNameValue) is a method available in any DOM Element or the root Document element. When called, it returns an array with all of the element's descendants matching the tag name. The first element of the list is located at position [0] in the array. ...
...And 10 more matches
Drag Operations - Web APIs
ferent types. This allows data to be provided in more specific types, often custom types, yet still provide fallback data for drop targets that do not support more specific types. It is usually the case that the least specific type will be normal text data using the type text/plain. This data will be a simple textual representation. To set a drag data item within the dataTransfer, use the setData
() method. It takes two arguments: the type of data and the data value. For example: event.dataTransfer.setData("text/plain", "Text to drag"); In this case, the data value is "Text to drag" and is of the format text/plain. You can provide data in multiple formats. To do this, call the setData
() method multiple times with different formats. You should call it with formats in order from most speci...
... can include just a single URL or text version. Note that both the text/uri-list and text/plain contain the same data in this example. This will often be true, but doesn't need to be the case. If you attempt to add data twice with the same format, the new data will replace the old data, but in the same position within the list of types as the old data. You can clear the data using the clearData
() method, which takes one argument: the type of the data to remove. event.dataTransfer.clearData("text/uri-list"); The type argument to the clearData
() method is optional. If the type is not specified, the data associated with all types is removed. If the drag contains no drag data items, or all of the items have been subsequently cleared, then no drag will occur. Setting the drag feedback imag...
...tems, or all of the items have been subsequently cleared, then no drag will occur. Setting the drag feedback image When a drag occurs, a translucent image is generated from the drag target (the element the "dragstart" event is fired at), and follows the user's pointer during the drag. This image is created automatically, so you do not need to create it yourself. However, you can use setDragImage
() to specify a custom drag feedback image. event.dataTransfer.setDragImage(image, xOffset, yOffset); Three arguments are necessary. The first is a reference to an image. This reference will typically be to an <img> element, but it can also be to a <canvas> or any other element. The feedback image will be generated from whatever the image looks like on screen, although for images, they will be dr...
...And 10 more matches
Dragging and Dropping Multiple Items - Web APIs
Caution: All of the methods and properties with a moz prefix (such as mozSetDataAt
() are Gecko specific interfaces. These interfaces will only work with Gecko based browsers. Mozilla supports the ability to drag multiple items using some additional non-standard methods. These are methods that mirror the types property as well as the getData
(), setData
() and clearData
() methods, however, they take an additional argument that specifies the index of the item to retrieve, modify or remove. The drag processing described in this document use the DataTransfer interface. This processing does not use the DataTransferItem interface nor the DataTransferItemList interface. Setting and getting with indices The mozSetDataAt
() method allows you to add multiple items during a dragstart event. This ...
...at specifies the index of the item to retrieve, modify or remove. The drag processing described in this document use the DataTransfer interface. This processing does not use the DataTransferItem interface nor the DataTransferItemList interface. Setting and getting with indices The mozSetDataAt
() method allows you to add multiple items during a dragstart event. This function similarly to setData
() var dt = event.dataTransfer; dt.mozSetDataAt("text/plain", "Data to drag", 0); dt.mozSetDataAt("text/plain", "Second data to drag", 1); This example adds two items to be dragged. The last argument specifies the index of the item to add. You should add them in order starting with 0 as you cannot add items at positions farther than the last item, however you can replace existing items by using i...
...mozSetDataAt("text/plain", "Second data to drag", 1); This example adds two items to be dragged. The last argument specifies the index of the item to add. You should add them in order starting with 0 as you cannot add items at positions farther than the last item, however you can replace existing items by using indices you have already added. Using 0 as the index is equivalent to calling setData
(). You can clear an item using the mozClearDataAt
() method. event.dataTransfer.mozClearDataAt("text/plain", 1); Caution: removing the last format for a particular index will remove that item entirely, shifting the remaining items down, so the later items will have different indices. For example: var dt = event.dataTransfer; dt.mozSetDataAt("text/uri-list", "URL1", 0); dt.mozSetDataAt("text/pla...
...And 10 more matches
SVGPathElement - Web APIs
Properties This interface also inherits properties from its parent, SVGGeometryElement. SVGPathElement.pathLength An SVGAnimatedNumber corresponding to the pathLength attribute of the given <path> element. Note: In SVG 2 this...
...th="2px" /><text x="-29" y="94" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">SVGPathElement</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Note: In SVG 2 the getPathSegAtLength
() and createSVGPathSeg* methods were removed and the pathLength property and the getTotalLength
() and getPointAtLength
() methods were moved to SVGGeometryElement. Properties This interface also inherits properties from its parent, SVGGeometryElement. SVGPathElement.pathLength An SVGAnimatedNumber corresponding to the pathLength attribute of the given <path> element. Note: In SVG 2 this property was moved to the SVGGeometryElement interface, from which this interface inherits it. ...
... from its parent, SVGGeometryElement. SVGPathElement.pathLength An SVGAnimatedNumber corresponding to the pathLength attribute of the given <path> element. Note: In SVG 2 this property was moved to the SVGGeometryElement interface, from which this interface inherits it. Methods This interface also inherits methods from its parent, SVGGeometryElement. ...
...And 10 more matches
TransformStream - Web APIs
The TransformStream interface of the Streams API represents a set of transformable data. Constructor TransformStream
() Creates and returns a transform stream object from the given handlers. Properties TransformStream.readable Read only The readable end of a TransformStream. TransformStream.writable Read only The writable end of a TransformStream. Methods None Examples Anything-to-uint8array stream In the following example, a transform stream passes through all chunks it receives as Uint8Array values. const transformContent = { start
() {}, // required. ...
... Anything-to-uint8array stream In the following example, a transform stream passes through all chunks it receives as Uint8Array values. const transformContent = { start
() {}, // required. ...
... if (chunk === null) controller.terminate
() else if (ArrayBuffer.isView(chunk)) controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)) else if (Array.isArray(chunk) && chunk.every(value => typeof value === 'number')) controller.enqueue(new Uint8Array(chunk)) else if ('function' === typeof chunk.valueOf && chunk.valueOf
() !== chunk) this.transform(chunk.valueOf
(), controller) // hack else if ('toJSON' in chunk) this.transform(JSON.stringify(chunk), controller) break case 'symbol': controller.error("Cannot send a symbol as a chunk part") break case 'undefined': controller.error("Cannot send undefined as a chunk part") default: controller.en...
...And 10 more matches
Scissor animation - Web APIs
We again establish an animation loop using timers. Note that this time it is the position of the square (the scissoring area) that is updated every frame (we set frame rate to roughly one every 17ms, or roughly 60fps - frames per second). In contrast, the color of the square (set with clearColor) is only updated when a new square is created. ...
... goes here]</strong> the animation</button> <canvas>Your browser 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; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } ;(function
(){ "use strict" window.addEventListener("load", setupAnimation, false); // Variables to hold the WebGL context, and the color and // position of animated squares. var gl, color = getRandomColor
(), position; function setupAnimation (evt) { window.removeEventListener(evt.type, setupAnimation, false); if (!(gl = getRenderingContext
())) return; gl.enable(gl.SCISSOR_TEST); gl.clearC...
...// drawing buffer. position = [0, gl.drawingBufferHeight]; var button = document.querySelector("button"); var timer; function startAnimation(evt) { button.removeEventListener(evt.type, startAnimation, false); button.addEventListener("click", stopAnimation, false); document.querySelector("strong").innerHTML = "stop"; timer = setInterval(drawAnimation, 17); drawAnimation
(); } function stopAnimation(evt) { button.removeEventListener(evt.type, stopAnimation, false); button.addEventListener("click", startAnimation, false); document.querySelector("strong").innerHTML = "start"; clearInterval(timer); } stopAnimation({type: "click"}); } // Variables to hold the size and velocity of the square. var size = [60, 60], velocity = 3.0; function drawAn...
...And 10 more matches
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
Connection has methods which provide access to the list of RTP transports that service the peer connection. These correspond to the following three types of transport supported by RTCPeerConnection: RTCRtpSender RTCRtpSenders handle the encoding and transmission of MediaStreamTrack data to a remote peer. The senders for a given connection can be obtained by calling RTCPeerConnection.getSenders
(). RTCRtpReceiver RTCRtpReceivers provide the ability to inspect and obtain information about incoming MediaStreamTrack data. A connection's receivers can be obtained by calling RTCPeerConnection.getReceivers
(). RTCRtpTransceiver An RTCRtpTransceiver is a pair of one RTP sender and one RTP receiver which share an SDP mid attribute, which means they share the same SDP media m-line (representing ...
...about incoming MediaStreamTrack data. A connection's receivers can be obtained by calling RTCPeerConnection.getReceivers
(). RTCRtpTransceiver An RTCRtpTransceiver is a pair of one RTP sender and one RTP receiver which share an SDP mid attribute, which means they share the same SDP media m-line (representing a bidirectional SRTP stream). These are returned by the RTCPeerConnection.getTransceivers
() method, and each mid and transceiver share a one-to-one relationship, with the mid being unique for each RTCPeerConnection. Leveraging RTP to implement a "hold" feature Because the streams for an RTCPeerConnection are implemented using RTP and the interfaces above, you can take advantage of the access this gives you to the internals of streams to make adjustments. Among the simplest things you...
...e await expression. This enormously simplifies and makes far more readable the code dealing with the promises returned by WebRTC methods. In the examples below, we'll refer to the peer which is turning "hold" mode on and off as the local peer and the user being placed on hold as the remote peer. ...
...And 10 more matches
Writing a WebSocket server in C# - Web APIs
with the using keyword in order to write less. It allows usage of a namespace's classes without typing the full namespace every time. TcpListener Constructor: TcpListener(System.Net.IPAddress localaddr, int port) localaddr specifies the IP of the listener, and port specifies the port. To create an IPAddress object from a string, use the Parse static method of IPAddress. ...
...It allows usage of a namespace's classes without typing the full namespace every time. TcpListener Constructor: TcpListener(System.Net.IPAddress localaddr, int port) localaddr specifies the IP of the listener, and port specifies the port. To create an IPAddress object from a string, use the Parse static method of IPAddress. ...
...ifies the port. To create an IPAddress object from a string, use the Parse static method of IPAddress. Methods: Start
() System.Net.Sockets.TcpClient AcceptTcpClient
() Waits for a Tcp connection, accepts it and returns it as a TcpClient object. ...
...And 10 more matches
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
pose is represented by an XRPose object, whose transform property is an XRRigidTransform defining the transform matrix that, applied to any coordinate, vector, or matrix in the original space, converts it to the target space. Thus a pose can be used to not only convert and determine positions, but also rotational information. ...
... pose can be used to not only convert and determine positions, but also rotational information. There is only one way to create an XRPose, and that's using the getPose
() method on an animation frame as given using an XRFrame object. This means that most frequently, you'll be using poses within your frame rendering code, which is executed as a callback from the XRFrame method requestAnimationFrame
(). getPose
() computes the position of an XRReferenceSpace relative to the origin of a specified XRSpace and then creates a pose representing the resulting position and orientation. For example, if you wish to draw a hand controller's representation using the controller's gripSpace, you can get the pose needed like this: let controlPose = frame.getPose(worldRefSpace, inputSource.gripSpace); This...
...ng a frame, you'll use the viewer pose to determine the position and facing direction of the viewer in order to place the virtual camera and render the scene. The only way to obtain a pose that adapts positional information from one space to another is through the XRFrame object received by your frame rendering callback function specified when you called the XRSession method requestAnimationFrame
(). ...
...And 10 more matches
Synchronous and asynchronous requests - Web APIs
"freezing" on the screen and an unresponsive user experience. Asynchronous request If you use an asynchronous XMLHttpRequest, you receive a callback when the data has been received. This lets the browser continue to work as normal while your request is being handled. Example: send a file to the console log This is the simplest usage of asynchronous XMLHttpRequest. ...
...layed. Line 15 actually initiates the request. The callback routine is called whenever the state of the request changes. Example: writing a function to read an external file In some cases, you must read many external files. This is a standard function which uses the XMLHttpRequest object asynchronously in order to switch the content of the read file to a specified listener. ...
...called whenever the state of the request changes. Example: writing a function to read an external file In some cases, you must read many external files. This is a standard function which uses the XMLHttpRequest object asynchronously in order to switch the content of the read file to a specified listener. ...
...And 10 more matches
font - CSS: Cascading Style Sheets
0% sans-serif } /* Set the font weight to bold, the font-style to italic, the font size to large, and the font family to serif. */ p { font: bold italic large serif } /* Use the same font as the status bar of the window */ p { font: status-bar } Live sample HTML <p> Change the radio buttons below to see the generated shorthand and it's effect. ...
...ont as the status bar of the window */ p { font: status-bar } Live sample HTML <p> Change the radio buttons below to see the generated shorthand and it's effect. ...
...d it's effect. ...
...And 10 more matches
<input type="datetime-local"> - HTML: Hypertext Markup Language
the time. This is somewhat like having date and time widgets both created for you and merged into one. Value A DOMString representing a date and time (in the local time zone), or empty. Events change and input Supported common attributes autocomplete, list, readonly, and step IDL attributes list, value, valueAsNumber. Methods select
(), stepDown
(), stepUp
() Value A DOMString representing the value of the date entered into the input. The format of the date and time value used by this input type is described in Local date and time strings in Date and time formats used in HTML. You can set a default value for the input by including a date and time inside the value attribute, like so: <label for="party">Enter a date and t...
...d by their operating system, whereas the date/time value is always formatted yyyy-MM-ddThh:mm. When the above value submitted to the server, for example, it will look like partydate=2017-06-01T08:30. Note: Also bear in mind that if such data is submitted via HTTP GET, the colon character will need to be escaped for inclusion in the URL parameters, e.g. partydate=2017-06-01T08%3A30. See encodeURI
() for one way to do this. You can also get and set the date value in JavaScript using the HTMLInputElement.value property, for example: var dateControl = document.querySelector('input[type="datetime-local"]'); dateControl.value = '2017-06-01T08:30'; There are several methods provided by JavaScript's Date that can be used to convert numeric date information into a properly-formatted string, or y...
...date value in JavaScript using the HTMLInputElement.value property, for example: var dateControl = document.querySelector('input[type="datetime-local"]'); dateControl.value = '2017-06-01T08:30'; There are several methods provided by JavaScript's Date that can be used to convert numeric date information into a properly-formatted string, or you can do it manually. For example, the Date.toISOString
() method can be used for this purpose. Additional attributes In addition to the attributes common to all <input> elements, datetime-local inputs offer the following attributes: Attribute Description max The latest date and time to accept min The earliest date and time to accept step The stepping interval to use for this input, such as when clic...
...And 10 more matches
Indexed collections - JavaScript
shown above, arrays can also be assigned as a property of a new or an existing object: let obj = {} // ... obj.prop = [element0, element1, ..., elementN] // OR let obj = {prop: [element0, element1, ...., elementN]} If you wish to initialize an array with a single element, and the element happens to be a Number, you must use the bracket syntax. When a single Number value is passed to the Array
() constructor or function, it is interpreted as an arrayLength, not as a single element. let arr = [42] // Creates an array with only one element: // the number 42. let arr = Array(42) // Creates an array with no elements // and arr.length set to 42. // // This is equivalent to: let arr = [] arr.length = 42...
...ray consists only of DOM nodes, for example--you can use a more efficient idiom: let divs = document.getElementsByTagName('div') for (let i = 0, div; div = divs[i]; i++) { /* Process div in some way */ } This avoids the overhead of checking the length of the array, and ensures that the div variable is reassigned to the current item each time around the loop for added convenience. ...
..., 'fourth'] array.forEach(function(element) { console.log(element) }) // first // second // undefined // fourth Since JavaScript elements are saved as standard object properties, it is not advisable to iterate through JavaScript arrays using for...in loops, because normal elements and all enumerable properties will be listed. ...
...And 10 more matches
constructor - JavaScript
the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax constructor([arguments]) { ... } Description A constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object. ...
...equest. Syntax constructor([arguments]) { ... } Description A constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object. class Person { constructor(name) { this.name = name; } introduce
() { console.log(`Hello, my name is ${this.name}`); } } const otto = new Person('Otto'); otto.introduce
(); If you don't provide your own constructor, then a default constructor will be supplied for you. ...
...alled on an instantiated object. class Person { constructor(name) { this.name = name; } introduce
() { console.log(`Hello, my name is ${this.name}`); } } const otto = new Person('Otto'); otto.introduce
(); If you don't provide your own constructor, then a default constructor will be supplied for you. ...
...And 10 more matches
Object.prototype.__proto__ - JavaScript
formance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in obj.__proto__ = ... statements, but may extend to any code that has access to any object whose [[Prototype]] has been altered. If you care about performance you should avoid setting the [[Prototype]] of an object. Instead, create a new object with the desired [[Prototype]] using Object.create
(). Warning: While Object.prototype.__proto__ is supported today in most browsers, its existence and exact behavior has only been standardized in the ECMAScript 2015 specification as a legacy feature to ensure compatibility for web browsers. For better support, use Object.getPrototypeOf
() instead. The __proto__ property of Object.prototype is an accessor property (a getter function and a sette...
... is deprecated in favor of Object.getPrototypeOf/Reflect.getPrototypeOf and Object.setPrototypeOf/Reflect.setPrototypeOf (though still, setting the [[Prototype]] of an object is a slow operation that should be avoided if performance is a concern). The __proto__ property can also be used in an object literal definition to set the object [[Prototype]] on creation, as an alternative to Object.create
(). See: object initializer / literal syntax. Description The __proto__ getter function exposes the value of the internal [[Prototype]] of an object. For objects created using an object literal, this value is Object.prototype. For objects created using array literals, this value is Array.prototype. For functions, this value is Function.prototype. For objects created using new fun, where fun is one...
...objects created using new fun, where fun is a function defined in a script, this value is the value of fun.prototype. (That is, if the constructor didn't return an other object explicitly, or the fun.prototype has been reassigned since the instance was created.) The __proto__ setter allows the [[Prototype]] of an object to be mutated. The object must be extensible according to Object.isExtensible
(): if it is not, a TypeError is thrown. The value provided must be an object or null. Providing any other value will do nothing. To understand how prototypes are used for inheritance, see guide article Inheritance and the prototype chain. The __proto__ property is a simple accessor property on Object.prototype consisting of a getter and setter function. A property access for __proto__ that eventu...
...And 10 more matches
super - JavaScript
x super([arguments]); // calls the parent constructor. super.functionOnParent([arguments]); Description When used in a constructor, the super keyword appears alone and must be used before the this keyword is used. The super keyword can also be used to call functions on a parent object. Examples Using super in classes This code snippet is taken from the classes sample (live demo). ...
...be used to call functions on a parent object. Examples Using super in classes This code snippet is taken from the classes sample (live demo). Here super
() is called to avoid duplicating the constructor parts' that are common between Rectangle and Square. ...
... in classes This code snippet is taken from the classes sample (live demo). Here super
() is called to avoid duplicating the constructor parts' that are common between Rectangle and Square. ...
...And 10 more matches
XPath snippets - XPath
ty to JavaScript code. The snippets are functions you can use in the real world in your own code. Node-specific evaluator function The following custom utility function can be used to evaluate XPath expressions on given XML nodes. The first argument is a DOM node or Document object, while the second is a string defining an XPath expression. ...
...a string defining an XPath expression. Example: Defining a custom node-specific evaluateXPath
() utility function // Evaluate an XPath expression aExpression against a given DOM node // or Document object (aNode), returning the results as an array // thanks wanderingstan at morethanwarm dot mail dot com for the // initial work. ...
...ngstan at morethanwarm dot mail dot com for the // initial work. function evaluateXPath(aNode, aExpr) { var xpe = new XPathEvaluator
(); var nsResolver = xpe.createNSResolver(aNode.ownerDocument == null ? ...
...And 10 more matches
dev/panel - Archive of obsolete content
fy the mechanics of inheriting from Panel. You can use the Class utility function: const { Panel } = require("dev/panel"); const { Class } = require("sdk/core/heritage"); const MyPanel = Class({ extends: Panel, label: "My Panel", tooltip: "My new devtool", icon: "./my-devtool.png", url: "./my-devtool.html", setup: function(options) { // my setup goes here }, dispose: function
() { // my teardown goes here }, onReady: function
() { // I can send messages to // the panel document here } }); Alternatively, you can use the extend function: const { extend } = require("sdk/core/heritage"); function MyPanel
() {}; MyPanel.prototype = extend(Panel.prototype, { label: "My Panel", tooltip: "...", .... }); In the constructor definition there are a number...
...box"); const { Class } = require("sdk/core/heritage"); // define the panel constructor const MyPanel = Class({ extends: Panel, label: "My Panel", tooltip: "My new devtool's panel", icon: "./my-icon.png", url: "./my-panel.html", // when the panel is created, // take a reference to the debuggee setup: function(options) { this.debuggee = options.debuggee; }, dispose: function
() { this.debuggee = null; }, onReady: function
() { // in this function you can communicate // with the panel document } }); // export the constructor exports.MyPanel = MyPanel; // create a new tool, initialized // with the new constructor const myTool = new Tool({ panels: { myPanel: MyPanel } }); Panel document environment The panel document loaded from the url property can ...
... you've received the ready event. ...
...And 9 more matches
Creating Reusable Modules - Archive of obsolete content
To follow this tutorial you'll need to have learned the basics of jpm. With the SDK you don't have to keep all your add-on in a single "index.js" file. You can split your code into separate modules with clearly defined interfaces between them. You then import and use these modules from other parts of your add-on using the require
() statement, in exactly that same way that you import core SDK modules like page-mod or panel. It can often make sense to structure a larger or more complex add-on as a collection of modules. This makes the design of the add-on easier to understand and provides some encapsulation as each module will export only what it chooses to, so you can change the internals of the module without breaking its users. Once you've done this, you can package the modules and dist...
...orks fine outside a security context. Here we'll write an add-on that lets the user select a file on disk and calculates its hash. For both these operations we'll use XPCOM interfaces. File picker To let the user select a file we'll use nsIFilePicker. ...
...et the user select a file we'll use nsIFilePicker. The documentation for that interface includes an example which we can adapt like this: var {Cc, Ci} = require("chrome"); function promptForFile
() { const nsIFilePicker = Ci.nsIFilePicker; var fp = Cc["@mozilla.org/filepicker;1"] .createInstance(nsIFilePicker); var window = require("sdk/window/utils").getMostRecentBrowserWindow
(); fp.init(window, "Select a file", nsIFilePicker.modeOpen); fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText); var rv = fp.show
(); if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) { var file = fp.file; // Get the path as string. Note that you usually won't // need to work with the string paths. var path = fp.file.path; // work w...
...And 9 more matches
JavaScript Client API - Archive of obsolete content
r, decrypted, and synced up. You may find it useful to write getters and setters for various properties of your record implementation. ...
...various properties of your record implementation. ...
...ords in the store) called GUID. Depending of what type of data you're working with, you might already have GUIDs built into your data that you can make use of (note that GUIDs must be allowed to change and should be URL friendly). If not, you may have to invent your own mapping from data objects to GUIDs as long as it's consistent. ...
...And 9 more matches
File object - Archive of obsolete content
es on the local filesystem, and create OS pipelines. Creating a pipeline involves spawning arbitrary processes; this means that giving a script access to the File object is exactly equivalent to giving the script access to the UNIX shell or DOS command interpreter. Filesystem access is implemented with NSPR I/O Functions, and as such shares many semantics. Pipelines are implemented with the popen
() system call. There is currently no support for p2open
()-like semantics. Here is the original proposal for this object, and a status update from December 1998: http://www.mozilla.org/js/js-file-object.html Created By The File constructor: new File
(); new File(filename); Parameters filename Name of the file we want to work with. Directories and pipelines are considered special files. Pipel...
...his file. Binary (UTF-8) files and pipelines (including File.intput) do not support random access. File.hasAutoFlush Force a flush on each line break? (readonly) File.position The file position. Writing to the property moves the file pointer. File.isNative True if the file is backed by a native stdio FILE stream. (i.e. ...
...ntput) do not support random access. File.hasAutoFlush Force a flush on each line break? (readonly) File.position The file position. Writing to the property moves the file pointer. File.isNative True if the file is backed by a native stdio FILE stream. (i.e. file.input, file.output, file.error or a pipeline) Methods File.open
() Opens the file, specifying file mode and type. File.close
() Closes the file. ...
...And 9 more matches
Reading from Files - Archive of obsolete content
nary file. Using the former will cause characters in the stream to be interpreted with a particular character encoding. In addition, lines may be read by reading the file up until a linefeed character is detected. A binary stream would be used to read bytes or numbers encoded within the file. ...
...umbers encoded within the file. To create an input stream, first get a reference to a nsIFile, and then use nsIScriptableIO.newInputStream
() to open a stream for reading from it. To learn more about file objects, see Files and Streams. var file = IO.getFile("Home", "sample.txt"); var stream = IO.newInputStream(file, "text"); This example first retrieves a file object using nsIScriptableIO.getFile
(). In this case, the file 'sample.txt' within the user's home directory is retrieved. Next, nsIScriptableIO.newInputStream
() is called to create a new input stream for reading from the file. This method will open the file and return a stream. Naturally, if the file does not exist, an error will occur. You may wish to use nsIFile.exists
() to check if the file exists before opening it. In fact, it is...
...ms always read bytes. First, let's look at reading form text files. Reading Text Files Characters are interpreted from a text input stream using a specified character encoding. This means that if a character within the file occupies several bytes, it will converted into a single character when read. This is done automatically as long as you specify the 'text' flag to nsIScriptableIO.newInputStream
(). The default character encoding is UTF-8 which means that characters below value 128 will occupy a single byte whereas characters above value 128 will occupy multiple bytes, depending on their value. However, a number of other character encodings are available; see Reading Other Character Encodings below for details about reading text in other encodings. There are several methods available to rea...
...And 9 more matches
findbar - Archive of obsolete content
resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width browser Type: browser element Lets you set and get the browser in which the findbar is located. findMode Type: integer Read only. The find mode in use. ...
... , statusText, style, ,, tooltip, tooltipText, top, width browser Type: browser element Lets you set and get the browser in which the findbar is located. findMode Type: integer Read only. The find mode in use. ...
...ooltip, tooltipText, top, width browser Type: browser element Lets you set and get the browser in which the findbar is located. findMode Type: integer Read only. The find mode in use. ...
...And 9 more matches
XPCOM Examples - Archive of obsolete content
splaying a list of open windows, but we would like to enhance this so that clicking on the menu item will switch to that window. This is accomplished by using the window mediator component. It implements the interface nsIWindowDataSource. The code below shows how to get a component which implements it: var wmdata = Components.classes["@mozilla.org/rdf/datasource;1?name=window-mediator"].getService
(); wmdata.QueryInterface(Components.interfaces.nsIWindowDataSource); This code retrieves a window mediator data source component. The component used here is the same one that handles the window-mediator RDF datasource. You can also get this component through the RDF service, which is another service that manages RDF datasources. The nsIWindowDataSource interface has a function getWindowForResource...
...of windows and added it to a menu via a template. The template generates an id attribute on each menuitem element. The value of this attribute can be used as the resource. That means that in order to switch the window focus, we need to do the following: Determine the element that the user clicked on. Get the value of the id attribute from the element. Pass this value to getWindowForResource
() to get a window object. Switch the focus to this window. The example below shows how we might do this: <toolbox> <menubar id="windowlist-menubar"> <menu label="Window" oncommand="switchFocus(event.target);"> <menupopup id="window-menu" datasources="rdf:window-mediator" ref="NC:WindowMediatorRoot"> <template> <rule> <menuitem uri="rdf:*" label="rdf:http://home.netscape.com/...
...The functi...
...And 9 more matches
Implementation Status - Archive of obsolete content
292333; 3.4 Extension Module unsupported 300760; 3.5 MustUnderstand Module unsupported 300757; 4. Processing Model (Events) Section Title Status Notes Bugs 4 Processing Model (Events) partial Th...
...ms unsupported 4.7.1 References to Elements within a repeat Element unsupported 4.7.2 References to Elements within a bind Element unsupported 4.8 DOM Interface for Access to Instance Data supported 4.8.1 getInstanceDocument
() supported 4.8.2 rebuild
() supported 4.8.3 recalculate
() supported 4.8.4 revalidate
() supported 4.8.5 refresh
() supported 4.9 Feature string for the hasFeature method call su...
...won't be bound correctly 333638; 7.4.5 UI Binding in other XML vocabularies unsupported not a compliance requirement for an XForms processor 7.4.6 Binding Examples supported 7.5 XForms Core Function Library supported 7.6.1 boolean-from-string
() supported 7.6.2 is-card-number
() unsupported 7.7.1 avg
() supported 7.7.2 min
() supported 7.7.3 max
() supported 7.7.4 count-non-empty
() supported ...
...And 9 more matches
RDF in Mozilla FAQ - Archive of obsolete content
of how to write a datasource, refer to the RDF Datasource How-To. How does Mozilla manage datasources? The RDF service manages a table of all loaded datasources. The table is keyed by the datasource's "URI", which is either the URL of an RDF/XML file, or a "special" URI starting with rdf: that refers to a built-in datasource. Datasources may be loaded via the RDF service using the GetDataSource
() method. If the URI argument refers to an RDF/XML file's URL, then the RDF service will create an RDF/XML datasource and asynchronously parse it. The datasource will remain "cached" until the last reference to the datasource is released. If the URI argument refers to a built-in datasource, the RDF service will use the XPCOM Component Manager to load a component whose ContractID is constructed usi...
...prefix@mozilla.org/rdf/datasource;1?name=</code>. For example, rdf:foo Would load: @mozilla.org/rdf/datasource;1?name=foo As with RDF/XML datasources, a datasource that is retrieved this way is "cached" by the RDF service until the last reference is dropped. How do I create a datasource from an RDF/XML file? You can either create an RDF/XML datasource using the RDF service's GetDataSource
() method: // Get the RDF service var RDF = Components .classes["@mozilla.org/rdf/rdf-service;1"] .getService(Components.interfaces.nsIRDFService); // ...and from it, get the datasource. Make sure that your web server // dishes it up as text/xml (recommended) or text/rdf! var ds = RDF.GetDataSource("http://www.mozilla.org/some-rdf-file.rdf"); // Note that ds will load asynchronously, so asser...
...! remote.Refresh(false); // Note that ds will load asynchronously, so assertions will not // be immediately available You may decide that you need to "manually" create an RDF/XML datasource if you want to force it to load synchronously. How do I reload an RDF/XML datasource? You can force an RDF/XML datasource (or any datasource that supports nsIRDFRemoteDataSource) to reload using the Refresh
() method of nsIRDFRemoteDataSource. Refresh
() takes a single parameter that indicates whether you'd like it to perform its operation synchronously ("blocking") or asynchrounously ("non-blocking"). You should never do a synchronous load unless you really know what you're doing: this will freeze the UI until the load completes! How can I tell if an RDF/XML datasource has loaded? Using the nsIRDFRem...
...And 9 more matches
Audio for Web games - Game development
the file, we just use the known start and stop times for each audio sprite. The advantage is that we can prime one piece of audio and have our sprites ready to go. To do this we can just play and instantly pause the larger piece of audio. You'll also reduce the number of server requests and save bandwidth. var myAudio = document.createElement("audio"); myAudio.src = "mysprite.mp3"; myAudio.play
(); myAudio.pause
(); You'll need to sample the current time to know when to stop. If you space your individual sounds by at least 500ms then using the timeUpdate event (which fires every 250ms) should be sufficient. Your files may be slightly longer than they strictly need to be, but silence compresses well. Here's an example of an audio sprite player -- first let's set up the user interface in HT...
... consists of a number being spoken every 2 seconds, the idea being that we play back that number when the corresponding button is pressed. Let's add some JavaScript to make this work: var myAudio = document.getElementById('myAudio'); var buttons = document.getElementsByTagName('button'); var stopTime = 0; for (var i = 0; i < buttons.length; i++) { buttons[i].addEventListener('click', function
() { myAudio.currentTime = this.getAttribute("data-start"); stopTime = this.getAttribute("data-stop"); myAudio.play
(); }, false); } myAudio.addEventListener('timeupdate', function
() { if (this.currentTime > stopTime) { this.pause
(); } }, false); Note: You can try out our audio sprite player live on JSFiddle. Note: On mobile we may need to trigger this code from a user-ini...
...ssed, as described above. Note: Watch out for bit rates. Encoding your audio at lower bit rates means smaller file sizes but lower seeking accuracy. Background music Music in games can have a powerful emotional effect. You can mix and match various music samples and assuming you can control the volume of your audio element you could cross-fade different musical pieces. Using the playbackRate
() method you can even adjust the speed of your music without affecting the pitch, to sync it up better with the action. All this is possible using the standard <audio> element and associated HTMLMediaElement API, but it becomes much easier and more flexible with the more advanced Web Audio API. Let's look at this next. element and associated HTMLMediaElement API, but it becomes much easier and m...
...And 9 more matches
CSS values and units - Learn web development
ing angle brackets, to differentiate them from CSS properties (e.g. the color property, versus the <color> data type). You might get confused between CSS data types and HTML elements too, as they both use angle brackets, but this is unlikely -- they are used in very different contexts. In the following example we have set the color of our heading using a keyword, and the background using the rgb
() function: h1 { color: black; background-color: rgb(197,93,161); } A value in CSS is a way to define a collection of allowable sub-values. This means that if you see <color> as valid you don't need to wonder which of the different types of color value can be used -- keywords, hex values, rgb
() functions, etc. You can use any available <color> values assuming they are supported by your brow...
... values for each (16 x 16 = 256.) These values are a bit more complex and less easy to understand, but they are a lot more versatile than keywords -- you can use hex values to represent any color you want to use in your color scheme. Again, try changing the values to see how the colors vary. RGB and RGBA values The third scheme we'll talk about here is RGB. An RGB value is a function -- rgb
() -- which is given three parameters that represent the red, green, and blue channel values of the colors, in much the same way as hex values. The difference with RGB is that each channel is represented not by two hex digits, but by a decimal number between 0 and 255 -- somewhat easier to understand. Let's rewrite our last example to use RGB colors: You can also use RGBA colors -- these work i...
...ample below I have added a background image to the containing block of our colored boxes. I have then set the boxes to have different opacity values -- notice how the background shows through more when the alpha channel value is smaller. In this example, try changing the alpha channel values to see how it affects the color output. ...
...And 9 more matches
JavaScript basics - Learn web development
t loads first and it is supposed to affect the HTML that hasn't loaded yet, there could be problems. Placing JavaScript near the bottom of an HTML page is one way to accommodate this dependency. To learn more about alternative approaches, see Script loading strategies. What happened? The heading text changed to Hello world! using JavaScript. You did this by using a function called querySelector
() to grab a reference to your heading, and then store it in a variable called myHeading. This is similar to what we did using CSS selectors. When you want to do something to an element, you need to select it first. Following that, the code set the value of the myHeading variable's textContent property (which represents the content of the heading) to Hello world!. Note: Both of the features you u...
...e in your code. This is a good alternative to repeatedly writing the same code. You have already seen some uses of functions previously. For example: let myVariable = document.querySelector('h1'); alert('hello!'); These functions, document.querySelector and alert, are built into the browser. If you see something which looks like a variable name, but it's followed by parentheses--
() --it is likely a function. Functions often take arguments: bits of data they need to do their job. Arguments go inside the parentheses, separated by commas if there is more than one argument. For example, the alert
() function makes a pop-up box appear inside the browser window, but we need to give it a string as an argument to tell the function what message to display. You can also define your ...
...ebsite requires events handlers. These are code structures that listen for activity in the browser, and run code in response. The most obvious example is handling the click event, which is fired by the browser when you click on something with your mouse. ...
...And 9 more matches
Introduction to automated testing - Learn web development
m install --global gulp-cli Next, run the following command inside your npm project directory root to set up gulp as a dependency of your project: npm install --save-dev gulp Now create a new file inside your project directory called gulpfile.js. This is the file that will run all our tasks. ...
...is file, put the following: const gulp = require('gulp'); gulp.task('default', function
() { console.log('Gulp running'); }); This requires the gulp module we installed earlier, and then runs a basic task that does nothing except for printing a message to the terminal -- this is useful for letting us know that Gulp is working. Each gulp task is written in the same basic format -- gulp's task
() method is run, and given two parameters -- the name of the task, and a callback function containing the actual code to run to complete the task. You can run your gulp task with the following commands -- try this now: gulp Adding some real tasks to Gulp To add some real tasks to Gulp, we need to think about what we want to do. A reasonable set of basic functionalities to run on our projec...
...save-dev adds the package as a dependency to your project. If you look in your project's package.json file, you'll see an entry for it in the devDependencies property. ...
...And 9 more matches
Dict.jsm
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 before being used, so they're docu...
... specify non-strings as keys; these are converted to strings before being used, so they're documented here as if they were a string parameter. In Firefox 19 and above, you may also pass a JSON String to initialize the dictionary: var someJSON = '{key1: "foo", key2: {}}'; var newDict = new Dict(someJSON); Note: Any String you pass will be assumed to be JSON. ...
...d above, you may also pass a JSON String to initialize the dictionary: var someJSON = '{key1: "foo", key2: {}}'; var newDict = new Dict(someJSON); Note: Any String you pass will be assumed to be JSON. Method overview Dict copy
(); boolean del(String aKey); Object get(String aKey, [optional] Object aDefault); boolean has(String aKey); Array listitems
(); Array listkeys
(); Array listvalues
(); void set(String aKey, Object aValue); String toJSON
(); String toString
(); Properties Attribute Type Description count Number The number of items in the dictionary. items Iterator Returns an iterator over all of the items in the dictionary; each item is ret...
...And 9 more matches
Mozilla-JSS JCA Provider notes
algorithms. You have two choices. Use the binary release of JSS from mozilla.org. Apply for your own JCE code-signing certificate following the procedure at How to Implement a Provider for the JavaTM Cryptography Extension. Then you can sign your own JSS JAR file. Installing the Provider In order to use any part of JSS, including the JCA provider, you must first call CryptoManager.initialize
(). By default, the JCA provider will be installed in the list of providers maintained by the java.security.Security class. If you do not wish the provider to be installed, create a CryptoManager.InitializationValues object, set its installJSSProvider field to false, and pass the InitializationValues object to CryptoManager.initialize
(). Specifying the CryptoToken All cryptographic operations in JS...
...ions except MessageDigest on the Internal Key Storage Token, a software token included in JSS/NSS. MessageDigest operations take place by default on the Internal Crypto Token, another internal software token in JSS/NSS. There is no good design reason for this difference, but it is necessitated by a quirk in the NSS implementation. In order to use a different token, use CryptoManager.setThreadToken
(). This sets the token to be used by the JSS JCA provider in the current thread. When you call getInstance
() on a JCA class, the JSS provider checks the current per-thread default token (by calling CryptoManager.getThreadToken
()) and instructs the new object to use that token for cryptographic operations. The per-thread default token setting is only consulted inside getInstance
(). Once a JCA object...
...e application later changes the per-thread default token. Whenever a new thread is created, its token is initialized to the default, the Internal Key Storage Token. Thus, the thread token is not inherited from the parent thread. ...
...And 9 more matches
Redis Tips
etwork round trip. So chaining lots of commands together is going to waste a lot of time. Redis has a solution for this: Transaction Blocks. A transaction block is a series of commands sent all at once across the wire. They are executed sequentially as a single atomic operation. ...
...d trip. So chaining lots of commands together is going to waste a lot of time. Redis has a solution for this: Transaction Blocks. A transaction block is a series of commands sent all at once across the wire. They are executed sequentially as a single atomic operation. ...
... Awesome. ...
...And 9 more matches
Using XPCOM Components
interfaces]. When a user selects one of the cookies displayed in the list and then clicks the Remove button, the Remove method in the nsICookieManager interface is called. The function is carried out by the CookieManager component, and the selected cookie is deleted from disk and removed from the displayed list. ...
...d list. ...
... CookieManager component can be called from JavaScript: Getting the CookieManager Component in JavaScript // xpconnect to cookiemanager // get the cookie manager component in JavaScript var cmgr = Components.classes["@mozilla.org/cookiemanager;1"] .getService
(); cmgr = cmgr.QueryInterface(Components.interfaces.nsICookieManager); // called as part of a largerDeleteAllCookies
() function function FinalizeCookieDeletions
() { for (var c=0; c<deletedCookies.length; c++) { cmgr.remove(deletedCookies[c].host, deletedCookies[c].name, deletedCookies[c].path); } deletedCookies.length = 0; } Connecting to Components from the Interface The Mozilla user interface uses JavaScript that has been given access to XPCOM components in the appl...
...And 9 more matches
mozIStorageAggregateFunction
must be implemented by consumers. It allows consumers to add aggregate functions that are available to SQL queries and triggers. An aggregate function is a function that returns one value from a series of values. There are a number of already defined aggregate functions provided by SQLite. Objects implementing this interface can be registered with mozIStorageConnection.createAggregateFunction
(). storage/public/mozIStorageAggregateFunction.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Inherits from: nsISupports Method overview void onStep(in mozIStorageValueArray aFunctionArguments); nsIVariant onFinal
(); Methods onStep
() This is called for each row of results returned by the query. The implementation s...
...Likewise, if you execute SQL on a different thread, this callback will be executed on that thread. ...
...Likewise, if you execute SQL on a different thread, this callback will be executed on that thread. ...
...And 9 more matches
nsIAccessibleText
NDARY_LINE_START 5 BOUNDARY_LINE_END 6 BOUNDARY_ATTRIBUTE_RANGE 7 Coordinate Type Constants Obsolete since Gecko 1.9 (Firefox 3)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Constant Value Description COORD_TYPE_SCREEN 0 COORD_TYPE_WINDOW 1 Methods addSelection
() void addSelection( in long startOffset, in long endOffset ); Parameters startOffset endOffset getAttributeRange
() Obsolete since Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) Get the accessible and start/end offsets around the given offset. This accessible get return the DOM node and layout frame with the uniform attributes for this range of text. ...
.../ SeaMonkey 2.0) Get the accessible and start/end offsets around the given offset. This accessible get return the DOM node and layout frame with the uniform attributes for this range of text. nsIAccessible getAttributeRange( in long offset, out long rangeStartOffset, out long rangeEndOffset ); Parameters offset rangeStartOffset rangeEndOffset Return value getCharacterAtOffset
() It would be better to return an unsigned long here, to allow unicode chars > 16 bits. wchar getCharacterAtOffset( in long offset ); Parameters offset Return value getCharacterExtents
() Returns the bounding box of the specified position. The virtual character after the last character of the represented text, that is the one at position length is a special case. It represents the current inp...
...ding box of the referenced character. y Y coordinate of the bounding box of the referenced character. width Width of the bounding box of the referenced character. height Height of the bounding box of the referenced character. coordType Specifies if the coordinates are relative to the screen or to the parent window (see constants declared in nsIAccessibleCoordinateType.Constants). getOffsetAtPoint
() Get the text offset at the given point, or return -1 if no character exists at that point. long getOffsetAtPoint( in long x, in long y, in unsigned long coordType ); Parameters x The position's x value for which to look up the index of the character that is rendered on to the display at that point. y The position's y value for which to look up the index of the character that is rendered o...
...And 9 more matches
nsIBinaryInputStream
gged, big-endian binary data, that is as produced by an implementation of nsIBinaryOutputStream. This might be used, for example, to implement network protocols or to read from architecture-neutral disk files, that is ones that can be read and written by both big-endian and little-endian platforms. ...
..., that is as produced by an implementation of nsIBinaryOutputStream. This might be used, for example, to implement network protocols or to read from architecture-neutral disk files, that is ones that can be read and written by both big-endian and little-endian platforms. ...
...implementation of nsIBinaryOutputStream. This might be used, for example, to implement network protocols or to read from architecture-neutral disk files, that is ones that can be read and written by both big-endian and little-endian platforms. ...
...And 9 more matches
nsICacheEntryDescriptor
netwerk/cache/nsICacheEntryDescriptor.idlScriptable This interface provides a cache entry descriptor. ...
... netwerk/cache/nsICacheEntryDescriptor.idlScriptable This interface provides a cache entry descriptor. ...
... netwerk/cache/nsICacheEntryDescriptor.idlScriptable This interface provides a cache entry descriptor. ...
...And 9 more matches
nsIComponentRegistrar
nentRegistrar.idlScriptable This interface provides methods to access and modify the XPCOM component registry. ...
...rovides methods to access and modify the XPCOM component registry. ...
...Registration lasts for this run only, and is not cached. Note: Formerly this method would register component files directly. This is no longer supported. Component files must have an associated loader and export the required symbols which this loader defines. For example, if the given file is a native library, it must ex...
...And 9 more matches
nsICompositionStringSynthesizer
1.0 66 Introduced Gecko 26 Obsolete Gecko 38 Inherits from: nsISupports Last changed in Gecko 38.0 (Firefox 38.0 / Thunderbird 38.0 / SeaMonkey 2.35) This interface is obsoleted in Gecko 38. You need to use nsITextInputProcessor instead of this. Every instance is associated with a DOM window at created by nsIDOMWindowUtils.createCompositionStringSynthesizer
(). ...
...rd 38.0 / SeaMonkey 2.35) This interface is obsoleted in Gecko 38. You need to use nsITextInputProcessor instead of this. Every instance is associated with a DOM window at created by nsIDOMWindowUtils.createCompositionStringSynthesizer
(). To create an instance for this: var domWindowUtils = window.windowUtils; var compositionStringSynthesizer = domWindowUtils.createCompositionStringSynthesizer
(); For example, when you create a composition whose composing string is "foo-bar-buzz" and "bar" is selected to convert, then, first, you need to start composition: domWindowUtils.sendCompositionEvent("compositionstart", "", ""); Next, dispatch composition string with crause information and caret information (optional): // set new composition string with .setString
(). compositionStringSynthesi...
...oo-bar-buzz" and "bar" is selected to convert, then, first, you need to start composition: domWindowUtils.sendCompositionEvent("compositionstart", "", ""); Next, dispatch composition string with crause information and caret information (optional): // set new composition string with .setString
(). compositionStringSynthesizer.setString("foo-bar-buzz"); // set clause information with .appendClause
(). compositionStringSynthesizer.appendClause("foo-".length, compositionStringSynthesizer.ATTR_CONVERTEDTEXT); compositionStringSynthesizer.appendClause("bar".length, compositionStringSynthesizer.ATTR_SELECTEDCONVERTEDTEXT); compositionStringSynthesizer.appendClause("-buzz".length, compositionStringSynthesizer.ATTR_CONVERTEDTEXT); // set caret position in the composition string. (optional) compos...
...And 9 more matches
nsICycleCollectorListener
xpcom/base/nsICycleCollectorListener.idlScriptable Interface to pass to the cycle collector to get information about the cycle collector graph while it is being built. ...
...leCollectorListener.idlScriptable Interface to pass to the cycle collector to get information about the cycle collector graph while it is being built. ...
...criptable Interface to pass to the cycle collector to get information about the cycle collector graph while it is being built. ...
...And 9 more matches
nsIDOMWindowInternal
t changed in Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) In Gecko 8.0 this Interface was merged into the nsIDOMWindow interface. This interface no longer has any members; it exists solely to prevent add-ons that reference it from failing completely. Add-ons should be updated to use nsIDOMWindow instead. ...
...in Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) In Gecko 8.0 this Interface was merged into the nsIDOMWindow interface. This interface no longer has any members; it exists solely to prevent add-ons that reference it from failing completely. Add-ons should be updated to use nsIDOMWindow instead. It provides many of the common functions used in JavaScript such as alert
() or open
(). ...
...instead. It provides many of the common functions used in JavaScript such as alert
() or open
(). Note: Because most of nsIDOMWindowInternal's functions and attributes are well documented in window, those articles are linked to rather than re-documented. However, they are not guaranteed to document all available arguments (i.e. see window.prompt). Method overview Firefox 3.5 note The prompt
() and find
() methods changed in Firefox 3.5 to make all their parameters optional; in previous versions, all parameters were required. void alert(in DOMString text) boolean confirm(in DOMString text) DOMString prompt([optional] in DOMString aMessage, [optional] in DOMString aInitial, [optional] in DOMString aTitle, [optional] in unsigned long aSavePassword) v...
...And 9 more matches
nsIFilePicker
This attribute has no effect if private browsing mode is in effect. defaultExtensi...
... defaultExtension AString The extension for the type of files you want to work with. On some platforms, this is automatically appended to filenames the user enters, if required. Specify it without a leading dot, for example "jpg". defaultString AString The filename, including extension, that should be suggested to the user as a default. This should be set before calling open
() or show
(). Exceptions thrown NS_ERROR_FAILURE If you try to read this attribute. displayDirectory nsILocalFile The directory that the file picker dialog should initially display. This should be set this before calling open
() or show
() to specify a starting point. file nsILocalFile The currently selected file or directory. Read only. ...
... fileURL nsIURI The URI of the currently selected file or directory. Read only. filterIndex long The (0-based) index of the filter which is currently selected in the file picker dialog. Set this to choose a particular filter to be selected by default. Constants Mode constants These constants are used to specify the type of file picker to create when calling init
(). ...
...And 9 more matches
nsILocalFileMac
xpcom/io/nsILocalFileMac.idlScriptable Please add a summary to this article. ...
... xpcom/io/nsILocalFileMac.idlScriptable Please add a summary to this article. ...
... xpcom/io/nsILocalFileMac.idlScriptable Please add a summary to this article. ...
...And 9 more matches
nsINavHistoryObserver
changed in Gecko 21.0 (Firefox 21.0 / Thunderbird 21.0 / SeaMonkey 2.18) Warning: If you are in the middle of a batch transaction, there may be a database transaction active. You can still access the database in this situation but be careful (of what?). ...
...1.0 / Thunderbird 21.0 / SeaMonkey 2.18) Warning: If you are in the middle of a batch transaction, there may be a database transaction active. You can still access the database in this situation but be careful (of what?). ...
...his situation but be careful (of what?). ...
...And 9 more matches
nsINavHistoryResultViewer
aNewIndex); void sortingChanged(in unsigned short sortingMode); Attributes Attribute Type Description result nsINavHistoryResult The nsINavHistoryResult this viewer monitors. Although this attribute is read-write, you should not alter it directly; instead, use the nsINavHistoryResult.viewer attribute to set the viewer. Methods containerClosed
() Called when a container node's state changes from closed to opened. void containerClosed( in nsINavHistoryContainerResultNode aContainerNode ); Parameters aContainerNode The container node whose state changed. containerOpened
() Called when a container node's state changes from closed to opened. void containerOpened( in nsINavHistoryContainerResultNode aContainerNode ); Par...
...osed( in nsINavHistoryContainerResultNode aContainerNode ); Parameters aContainerNode The container node whose state changed. containerOpened
() Called when a container node's state changes from closed to opened. void containerOpened( in nsINavHistoryContainerResultNode aContainerNode ); Parameters aContainerNode The container node whose state changed. invalidateContainer
() Called when something has happened that requires that the contents of a container be rebuilt. void invalidateContainer( in nsINavHistoryContainerResultNode aContainerNode ); Parameters aContainerNode The container that should be rebuilt. nodeAnnotationChanged
() Called right after the annotation on a node has changed. This is called when the annotation is changed, set, or unset. void...
...ner that should be rebuilt. nodeAnnotationChanged
() Called right after the annotation on a node has changed. This is called when the annotation is changed, set, or unset. void nodeAnnotationChanged( in nsINavHistoryResultNode aNode, in AUTF8String aAnnoName ); Parameters aNode The node whose title has changed. aAnnoName The name of the annotation that hanged. nodeDateAddedChanged
() Called right after the date added property of a node has changed. void nodeKeywordChanged( in nsINavHistoryResultNode aNode, in PRTime aNewValue ); Parameters aNode The node whose title has changed. aNewValue The new value for the node's date added property. nodeLastModifiedChanged
() Called right after the last modified date property of a node has changed. void nodeKeywordChange...
...And 9 more matches
nsIThreadObserver
This method is only called on the target thread. Note: It is valid to change the thread's observer during a call to this method. void afterProcessNextEvent( in nsIThreadInternal thread, in unsigned long recursionDepth ); Parameters thread The nsIThread on which the event was processed. recursion...
...pports Method overview void afterProcessNextEvent(in nsIThreadInternal thread, in unsigned long recursionDepth); void onDispatchedEvent(in nsIThreadInternal thread); void onProcessNextEvent(in nsIThreadInternal thread, in boolean mayWait, in unsigned long recursionDepth); Methods afterProcessNextEvent
() Called by the nsIThread method nsIThread.ProcessNextEvent
() after an event is processed. ...
...This method may be called from any thread. Note: It is valid to change the thread's observer during a call to this method. void onDispatchedEvent( in nsIThreadInternal thread ); Parameters thread The nsIThread on which the event was dispatched. ...
...And 9 more matches
nsITransactionListener
void didDo( in nsITransactio...
...saction aTransaction); boolean willUndo(in nsITransactionManager aManager, in nsITransaction aTransaction); Methods didBeginBatch
() Called after a nsITransactionManager begins a batch. void didBeginBatch( in nsITransactionManager aManager, in nsresult aResult ); Parameters aManager The nsITransactionManager that began a batch. aResult The nsresult returned after beginning a batch. didDo
() Called after a nsITransactionManager calls the nsITransaction.doTransaction
() method of a transaction. void didDo( in nsITransactionManager aManager, in nsITransaction aTransaction, in nsresult aDoResult ); Parameters aManager The nsITransactionManager that did the transaction. aTransaction The transaction that was executed. aDoResult The nsresult returned after executing the transaction.
... a nsITransactionManager calls the nsITransaction.doTransaction
() method of a transaction. void didDo( in nsITransactionManager aManager, in nsITransaction aTransaction, in nsresult aDoResult ); Parameters aManager The nsITransactionManager that did the transaction. aTransaction The transaction that was executed. aDoResult The nsresult returned after executing the transaction. didEndBatch
() Called after a nsITransactionManager ends a batch. void didEndBatch( in nsITransactionManager aManager, in nsresult aResult ); Parameters aManager The nsITransactionManager ending a batch. aResult The nsresult returned after ending a batch. ...
...And 9 more matches
Using COM from js-ctypes
aking done. #include <sapi.h> int main(void) { if (SUCCEEDED(CoInitialize(NULL))) { ISpVoice* pVoice = NULL; HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void**)&pVoice); if (SUCCEEDED(hr)) { pVoice->Speak(L"Hello, Firefox!", SPF_DEFAULT, NULL); pVoice->Release
(); } } // MSDN documentation says that even if CoInitalize fails, CoUnitialize // must be called CoUninitialize
(); return 0; } To run the code, save it as test.cpp, and run following command in the directory (needs Visual Studio). $ cl ole32.lib test.cpp vtable Needs vtable description here. The order of the vtable is very critical. When used from C or js-ctype...
... $ cl ole32.lib test.c C code with pseudo struct Needs pseudo struct description here. #include <sapi.h> struct MyISpVoiceVtbl; struct MyISpVoice { struct MyISpVoiceVtbl* lpVtbl; }; struct MyISpVoiceVtbl { /* start inherit from IUnknown */ void* QueryInterface; void* AddRef; ...
...It could be converted into js-ctypes in almost straightforward way. CLSID and IID Needs CLSID and IID of SpVoice and ISpVoice description here. COM types and functions Needs COM types (GUID) and functions (CoInitialize etc) description here. Converted js-ctypes code Here's converted code. This example ...
...And 9 more matches
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 w...
... the library, in this order: The application's directory. The system directory. The 16-bit system directory. The Windows directory. The current working directory The directories listed in the PATH environment variable. Note: This information comes from this article on MSDN. After you're done When you're finished using a library, you should close it by calling the Library object's close
() method: lib.close
(); If you fail to close the library, it will be automatically closed when it is garbage collected. Using the library You may need to declare new types. These can be simple types or more complex types such as structures. See Declaring types for details. You will almost certainly need to declare one or more functions, so that you can call them. Once you've declared the types ...
... Instead of defining the whole path, you may also just give the file name. ABOUT DECLARING THE FUNCTION How...
...And 9 more matches
Debugger.Object - Firefox Developer Tools
ferent 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 displayName and name properties are equal. If a function has no name, SpiderMonkey attempts to infer an appropriate name for it given its context. ...
...unction, 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 displayName and name properties are equal. If a function has no name, SpiderMonkey attempts to infer an appropriate name for it given its context. For example: function f
() {} // display name: f (the given name) var g = function
() {}; // display name: g o.p = function
() {}; // display name: o.p var q = { r: function
() {} // display name: q.r }; Note that the display name may not be a proper JavaScript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property. Thus, we use a/b to refer to theb defined ...
... Note that the display name may not be a proper JavaScript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property. Thus, we use a/b to refer to theb defined withina, and a< to refer to a function that occurs somewhere within an expression that is assigned toa. For example: function h
() { var i = function
() {}; // display name: h/i f(function
() {}); // display name: h/< } var s = f(function
() {}); // display name: s< parameterNames If the referent is a debuggee function, the names of the its parameters, as an array of strings. If the referent is not a debuggee function, or not a function at all, this is undefined. If the referent is a host function for w...
...And 9 more matches
The JavaScript input interpreter - Firefox Developer Tools
ress Enter. To enter multi-line expressions, press Shift+Enter after typing each line, then Enter to run all the entered lines. The expression you type is echoed under the input prompt, followed by the result. If your input does not appear to be complete when you press Enter, then the Console treats this as Shift+Enter , enabling you to finish your input. For example, if you type: function foo
() { and then Enter, the Console does not immediately execute the input, but behaves as if you had pressed Shift+Enter , so you can finish entering the function definition. Multi-line mode For multi-line entry, click the "split pane" icon at the right hand side of the single-line entry field, or press Ctrl+B (Windows/Linux) or Cmd+B (macOS). The multi-line editing pane opens on the left side the...
... browser if Accessibility features have been enabled. Execution history The interpreter remembers expressions you've typed. To move back and forward through your history: In single-line mode, use the up and down arrows. In multi-line mode, use the ? and ? icons in the editing panel's toolbar. The expression history is persisted across sessions. To clear the history, use the clearHistory
() helper function. You can initiate a reverse search through the expression history, much like you can in bash on Linux and Mac or PowerShell on Windows. On Windows and Linux press F9. On Mac press Ctrl+R (note: not Cmd+R!) to initiate the reverse search. Enter the text you want to search for in the input box at the bottom of the Console. Start typing part of the expression you are looking for ...
...rough the matches. Once you have initiated 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. ...
...And 9 more matches
BaseAudioContext - Web APIs
. Event handlers BaseAudioContext.onstatechange An event handler that runs when an event of type statechange has fired. This occurs when the AudioContext's state changes, due to the calling of one of the state change methods (AudioContext.suspend, AudioContext.resume, or AudioContext.close). Methods Also implements methods from the interface EventTarget. ...
...anges, due to the calling of one of the state change methods (AudioContext.suspend, AudioContext.resume, or AudioContext.close). Methods Also implements methods from the interface EventTarget. BaseAudioContext.createAnalyser
() Creates an AnalyserNode, which can be used to expose audio time and frequency data and for example to create data visualisations. ...
... BaseAudioContext.createAnalyser
() Creates an AnalyserNode, which can be used to expose audio time and frequency data and for example to create data visualisations. BaseAudioContext.createBiquadFilter
() Creates a BiquadFilterNode, which represents a second order filter configurable as several different common filter types: high-pass, low-pass, band-pass, etc BaseAudioContext.createBuffer
() Creates a new, empty AudioBuffer object, which can then be populated by data and played via an AudioBufferSourceNode. BaseAudioContext.createBufferSource
() Creates an AudioBufferSourceNode, which can be used to play and manipulate audio data contained within an AudioBuffer object. AudioBuffers are created using AudioContext.createBuffer or returned by AudioContext.decodeAudioData when it succe...
...And 9 more matches
CSSPrimitiveValue - Web APIs
imitiveValue interface derives from the CSSValue interface and represents the current computed value of a CSS property. This interface represents a single CSS value. It may be used to determine the value of a specific style property currently set in a block or to set a specific style property explicitly within the block. An instance of this interface might be obtained from the getPropertyCSSValue
() method of the CSSStyleDeclaration interface. A CSSPrimitiveValue object only occurs in a context of a CSS property. Conversions are allowed between absolute values (from millimeters to centimeters, from degrees to radians, and so on) but not between relative values. (For example, a pixel value cannot be converted to a centimeter value.) Percentage values can't be converted since they are relativ...
...dle" alignment-baseline="middle">CSSPrimitiveValue</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits properties from its parent, CSSValue. CSSPrimitiveValue.primitiveType Read only An unsigned short representing the type of the value. Possible values are: Constant Description CSS_ATTR The value is an attr
() function. The value can be obtained by using the getStringValue
() method. CSS_CM The value is a <length> in centimeters. The value can be obtained by using the getFloatValue
() method. CSS_COUNTER The value is a counter or counters function. The value can be obtained by using the getCounterValue
() method. CSS_DEG The value is an <angle> in degrees. T...
...etStringValue
() method. CSS_CM The value is a <length> in centimeters. The value can be obtained by using the getFloatValue
() method. CSS_COUNTER The value is a counter or counters function. The value can be obtained by using the getCounterValue
() method. CSS_DEG The value is an <angle> in degrees. The value can be obtained by using the getFloatValue
() method. CSS_DIMENSION The value is a <number> with an unknown dimension. The value can be obtained by using the getFloatValue
() method. CSS_EMS The value is a <length> in em units. The value can be obtained by using the getFloatValue
() method. CSS_EXS The value is a <length> in ex units. ...
...And 9 more matches
Examples of web and XML development using the DOM - Web APIs
eb and XML development using the DOM. Wherever possible, the examples use common APIs, tricks, and patterns in JavaScript for manipulating the document object. ...
...i < arrImages.length; i++) { strHtml += "<li>image" + (i+1) + ": height=" + arrImages[i].height + ", width=" + arrImages[i].width + ", style.height=" + arrImages[i].style.height + ", style.width=" + arrImages[i].style.width + "<\/li>"; } strHtml += "<\/ul>"; objOutput.innerHTML = strHtml; } </script> </head> <body onload="init
();"> <p>Image 1: no height, width, or style <img id="image1" src="https://udn.realityripple.com/samples/d2/8ba7141ed1.gif"> </p> <p>Image 2: height="50", width="500", but no style <img id="image2" src="https://udn.realityripple.com/samples/d2/8ba7141ed1.gif" height="50" width="500"> </p> <p>Image 3: no height, width, but style="height: 50px; width: 500px;" <img id="image3" ...
...he element and that object's CSS style properties, which can be retrieved and set from the DOM. In this case, you are manipulating the individual styles directly. In the next example (see Example 4), you can use stylesheets and their rules to change styles for whole documents. ...
...And 9 more matches
Using FormData Objects - Web APIs
The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's submit
() method would use to send the data if the form's encoding type were set to multipart/form-data. ...
...g form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's submit
() method would use to send the data if the form's encoding type were set to multipart/form-data. Creating a FormData object from scratch You can build a FormData object yourself, instantiating it then appending fields to it by calling its append
() method, like this: var formData = new FormData
(); formData.append("username", "Groucho"); formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456" // HTML file input, chosen by user formData.append("userfile", fileInputElement.files[0]); // JavaScript file-like object var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file... ...
...56); // number 123456 is immediately converted to a string "123456" // HTML file input, chosen by user formData.append("userfile", fileInputElement.files[0]); // JavaScript file-like object var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file... ...
...And 9 more matches
Working with the History API - Web APIs
HTML5 introduced the pushState
() and replaceState
() methods for add and modifying history entries, respectively. These methods work in conjunction with the onpopstate event. Adding and modifying history entries Using pushState
() changes the referrer that gets used in the HTTP header for XMLHttpRequest objects created after you change the state. The referrer will be the URL of the document whose window is this at the time of creation of the XMLHttpRequest object. ...
...tries, respectively. These methods work in conjunction with the onpopstate event. Adding and modifying history entries Using pushState
() changes the referrer that gets used in the HTTP header for XMLHttpRequest objects created after you change the state. The referrer will be the URL of the document whose window is this at the time of creation of the XMLHttpRequest object. Example of pushState
() method Suppose http://mozilla.org/foo.html executes the following JavaScript: let stateObj = { foo: "bar", } history.pushState(stateObj, "page 2", "bar.html") This will cause the URL bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists. Suppose now that the user navigates to http://google.com, then clicks the Back bu...
...ar.html. If the user clicks Back once again, the URL will change to http://mozilla.org/foo.html, and the document will get a popstate event, this time with a null state object. Here too, going back doesn't change the document's contents from what they were in the previous step, although the document might update its contents manually upon receiving the popstate event. Note: Calling history.back
() normally behaves the same way as clicking the Back button. But there is one important exception: After using history.pushState
(), calling history.back
() does not raise a popstate event. Clicking the browser's Back button (still) does. The pushState
() method pushState
() takes three parameters: a state object; a title (currently ignored); and (optionally), a URL. Let's examine each of these th...
...And 9 more matches
MediaDevices.ondevicechange - Web APIs
The MediaDevices.ondevicechange property is an EventHandler which specifies a function to be called when the devicechange event occurs on a MediaDevices instance. This happens whenever the set of media devices available to the user agent and, by extension, to the web site or app has changed. You can at any time use enumerateDevices
() to get the updated list of available devices. ...
... can at any time use enumerateDevices
() to get the updated list of available devices. Syntax MediaDevices.ondevicechange = eventHandler; Value A function you provide which accepts as input a Event object describing the devicechange event that occurred. There is no information about the change included in the event object; to get the updated list of devices, you'll have to use enumerateDevices
(). Example In this example, we create a function called updateDeviceList
(), which is called once when MediaDevices.getUserMedia
() successfully obtains a stream, and then is called any time the device list changes. It displays in the browser window two lists: one of audio devices and one of video devices, with both the device's label (name) and whether it's an input or an output device. Because th...
...tent Other code Below is other code which, while needed to make this example work, isn'tt related directly to ondevicechange, so we won't go into any detail. ...
...And 9 more matches
TextRange - Web APIs
r scripts. A TextRange object represents a fragment of text in a document, similar to the standard defined Range interface. This object is used to represent a specific piece of text in the document. For example, when you hold down the mouse to select the content on the page, you create a typical TextRange. It is implemented in IE, then a TextRange object can be created by Element.createTextRange
() or Document.selection.createRange
(). Note that this interface is not supported in non IE browsers. Alternative Selection and Range interfaces can be used. Properties TextRange.boundingHeightRead only Returns the height of the rectangle bound to the TextRange object. TextRange.boundingLeftRead only Returns the distance between the left edge of the rectangle that binds the TextRange o...
...ge of the rectangle that binds the TextRange object and the top edge that completely contains the TextRange object. TextRange.boundingWidthRead only Returns the width of the rectangle bound to the TextRange object. TextRange.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...
...opy 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
() Returns whether the current range contains the specified range. TextRange.isEqual
() Returns whether the current range is equal to the specified range. TextRange.move
() Collapses the range and moves the blank range by a specified number of units. Such as, move("character",...
...And 9 more matches
Using the User Timing API - Web APIs
ne. A live version of the examples is available on Github, as is the source code. Pull requests, enhancement requests and bug reports are welcome. Performance marks A performance mark is a named performance entry that is created by the application at some location in an application. The mark is a timestamp in the browser's performance timeline. Creating a performance mark The performance.mark
() method is used to create a performance mark. The method takes one argument, the name of the mark, as shown in the following example. function create_marks(ev) { if (performance.mark === undefined) { log("Create Marks: performance.mark Not supported", 0); return; } else { log("Create marks", 0); // Create several performance marks including two with the same name performance.mar...
...(50000); performance.mark("mark-2"); do_work(50000); performance.mark("mark-2"); var marks = ["mark-1", "mark-2", "mark-2"]; for (var i=0; i < marks.length; i++) log("... Created mark = " + marks[i], 0); } Retrieving performance marks The Performance interface has three methods to retrieve marks. ...
... each of these methods (performance.getEntries
(), performance.getEntriesByType(entryType), and performance.getEntriesByName(name, entryType) ) to retrieve one or more marks. function display_marks(ev) { if (performance.getEntries === undefined) { log("Display Marks: performance.getEntries Not supported", 0); return; } log("Display marks", 0); // Display each mark using getEntries
() var entries = performance.getEntries
(); var j=0; for (var i=0; i < entries.length; i++) { if (entries[i].entryType == "mark") { if (j == 0) { log("= getEntries
()", 0); j++ } log("... ...
...And 9 more matches
Adding 2D content to a WebGL context - Web APIs
That position is then multiplied by two 4x4 matrices we provide called uProjectionMatrix and uModelViewMatrix; gl_Position is set to the result. For more info on projection and other matrixes you might find this article useful. // Vertex shader program const vsSource = ` attribute vec4 aVertexPosition; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; void main
() { gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition; } `; It's worth noting that we're using a vec4 attribute for the vertex position, which doesn't actually use a 4-component vector; that is, it could be handled as a vec2 or vec3 depending on the situation. But when we do our math, we will need it to be a vec4, so rather than convert it to a vec4 every time we do...
...lying the appropriate lighting to the color. The color is then returned to the WebGL layer by storing it in the special variable gl_FragColor. That color is then drawn to the screen in the correct position for the shape's corresponding pixel. In this case, we're simply returning white every time, since we're just drawing a white square, with no lighting in use. const fsSource = ` void main
() { gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); } `; Initializing the shaders Now that we've defined the two shaders we need to pass them to WebGL, compile them, and link them together. The code below creates the two shaders by calling loadShader
(), passing the type and source for the shader. It then creates a program, attaches the shaders and links them together. If compiling or linkin...
...r. If compiling or linking fails the code displays an alert. ...
...And 9 more matches
Using textures in WebGL - Web APIs
f textures follows cross-domain rules; that is, you can only load textures from sites for which your content has CORS approval. See Cross-domain textures below for details. The code that loads the texture looks like this: // // Initialize a texture and load an image. // When the image finished loading copy it into the texture. // function loadTexture(gl, url) { const texture = gl.createTexture
(); gl.bindTexture(gl.TEXTURE_2D, texture); // Because images have to be download over the internet // they might take a moment until they are ready. // Until then put a single pixel in the texture so we can // use it immediately. When the image has finished downloading // we'll update the texture with the contents of the image. const level = 0; const internalFormat = gl.RGBA; con...
... if (isPowerOf2(image.width) && isPowerOf2(image.height)) ...
... if (isPowerOf2(image.width) && isPowerOf2(image.height)) { // Yes, it's a power...
...And 9 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
ted using NotifyWinEvent(eventNum, hWnd, worldID, childID), and there may not be an obvious way to get a window handle and a 32 bit childID for an object. You may be using windowless controls, or have an entire document with lots of objects in a given window. The child ID must be unique, because this is what the assistive technology will use to retrieve the accessible via AccessibleObjectFromEvent
() which ends up using get_accChild on the accessible for the given window. Solution: In Gecko/Mozilla, we did not want to store an extra 32 bit unique ID value on every object. Instead, we hand back a 32 bit value derived from the UI object's pointer, which is unique. We ensure that the value we hand back is always negative. When the get_accChild call comes back, we check our hash table cache for ...
... away, and another different object will be created with the same pointer value.That case seems extremely remote, because information from events is generally retrieved right after the event. If you're not using a hash table to keep track of unique ID's, store the child ID's and objects for the last 50 or so events in a circular array. In practice, this is enough to keep AccessibleObjectFromEvent
() happy. Missing functionality in MSAA Problem and solutions: Assistive technology vendors need some things which MSAA does not provide, such as: No way of signifying that a document has finished loading. Fire EVENT_OBJECT_STATECHANGE for a window/client/pane object when it starts to load a new document. Use STATE_BUSY to indicate that a new document is being loaded. When the loading has finis...
...ree view object. Simply put the level, i.e. "1", "2", 3", etc. in the value field. MSAA Implementation is Not Performant Problem: The assistive technology may interact slowly with your application. Solution: Try not to calculate the same things more than once or create the same objects more than once. For example, create and cache an object's children when you look for them in get_accChildCount
(), so that you can just hand them back when asked for using get_accChild
() or accNavigate
(). Support IEnumVARIANT so that the MSAA client can ask for a number of children in one call. In custom interfaces, create methods that hand back a lot of data in one call, rather than requiring a large number of calls. Fewer calls are much better better because COM Marshaling is slow. Differing client implem...
...And 9 more matches
Cubic Bezier Generator - CSS: Cascading Style Sheets
<html> <canvas id="bezier" width="336" height="336"> </canvas> <form> <label for="x1">x1 = </label><input onchange="updateCanvas
();" type="text" maxlength=6 id="x1" value="0.79" class='field'> <label for="y1">y1 = </label><input onchange="updateCanvas
();return true;" type="text" maxlength=6 id="y1" value="0.33" class='field'> <label for="x2">x2 = </label><input onchange="updateCanvas
();return true;" type="text" maxlength=6 id="x2" value="0.14" class='field'> <label for="y2">y2 = </label><input onchange="updateCanvas
();return true;" type="text" maxlength=6 id="y2" value="0.53" class='field'> <br> <output id="output">Log</output> </form> </html> .field { width: 40px; } function updateCanvas
() { var x1...
...rCurve(x1, y1, x2, y2); } const radius = 4; // Place needed to draw the rulers const rulers = 30.5; const margin = 10.5; const basic_scale_size = 5; // Size of 0.1 tick on the rulers var scaling; //LIMITATION: scaling is computed once: if canvas.height/canvas.width change it won't be recalculated var dragSM = 0; // Drag state machine: 0 = nodrag, others = object being dragged function initCanvas
() { // get the canvas element using the DOM var canvas = document.getElementById('bezier'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext) { // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); scaling = Math.min(canvas.height - rulers - margin, canvas.width - rulers - margin); canvas.
...element using the DOM var canvas = document.getElementById('bezier'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext) { // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); // Clear canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw the rulers ctx.beginPath
(); ctx.strokeStyle = "black"; // Draw the Y axis ctx.moveTo(cX(0), cY(0)); ctx.lineTo(cX(1), cY(0)); ctx.textAlign = "right"; for (var i = 0.1; i <= 1; i = i + 0.1) { ctx.moveTo(-basic_scale_size + cX(0), lY(i)); if ((i == 0.5) || (i > 0.9)) { ctx.moveTo(-2 * basic_scale_size + cX(0), lY(i)); c...
...And 9 more matches
transform - CSS: Cascading Style Sheets
sform: skewY(1.07rad); /* Multiple function values */ transform: translateX(10px) rotate(10deg) translateY(5px); transform: perspective(500px) translate(10px, 0, 20px) rotateY(3deg); /* Global values */ transform: inherit; transform: initial; transform: unset; The transform property may be specified as either the keyword value none or as one or more <transform-function> values. If perspective
() is one of multiple function values, it must be listed first. Values <transform-function> One or more of the CSS transform functions to be applied. The transform functions are multiplied in order from left to right, meaning that composite transforms are effectively applied in order from right to left. none Specifies that no transform should be applied. Accessibility concerns Scaling/zoom...
...anding WCAG 2.1 Formal definition Initial valuenoneApplies totransformable elementsInheritednoPercentagesrefer to the size of bounding boxComputed valueas specified, but with relative lengths converted into absolute lengthsAnimation typea transformCreates stacking contextyes Formal syntax none | <transform-list>where <transform-list> = <transform-function>+where <transform-function> = <matrix
()> | <translate
()> | <translateX
()> | <translateY
()> | <scale
()> | <scaleX
()> | <scaleY
()> | <rotate
()> | <skew
()> | <skewX
()> | <skewY
()> | <matrix3d
()> | <translate3d
()> | <translateZ
()> | <scale3d
()> | <scaleZ
()> | <rotate3d
()> | <rotateX
()> | <rotateY
()> | <rotateZ
()> | <perspective
()>where <matrix
()> = matrix( <number>#{6} )<translate
()> = translate( <length-percentage> , <length-percentage>? ...
...te
()> | <translateX
()> | <translateY
()> | <scale
()> | <scaleX
()> | <scaleY
()> | <rotate
()> | <skew
()> | <skewX
()> | <skewY
()> | <matrix3d
()> | <translate3d
()> | <translateZ
()> | <scale3d
()> | <scaleZ
()> | <rotate3d
()> | <rotateX
()> | <rotateY
()> | <rotateZ
()> | <perspective
()>where <matrix
()> = matrix( <number>#{6} )<translate
()> = translate( <length-percentage> , <length-percentage>? )<translateX
()> = translateX( <length-percentage> )<translateY
()> = translateY( <length-percentage> )<scale
()> = scale( <number> , <number>? )<scaleX
()> = scaleX( <number> )<scaleY
()> = scaleY( <number> )<rotate
()> = rotate( [ <angle> | <zero> ] )<skew
()> = skew( [ <angle> | <zero> ] , [ <angle> | <zero> ]? ...
...And 9 more matches
Creating a cross-browser video player - Developer guides
of web browsers to show apps using your computer's full screen. Setup Before dealing with the individual buttons, a number of initialisation calls are required. To begin with, it's a good idea to first check if the browser actually supports the <video> element and to only setup the custom controls if it does. This is done by simply checking if a created <video> element supports the canPlayType
() method, which any supported HTML5 <video> element should. var supportsVideo = !!document.createElement('video').canPlayType; if (supportsVideo) { // set up custom controls // ... } Once it has been confirmed that the browser does indeed support HTML5 video, it's time to set up the custom controls. A number of variables pointing to HTML elements are required: var videoContainer = documen...
...etElementById('fs'); Using these handles, events can now be attached to each of the custom control buttons making them interactive. Most of these buttons require a simple click event listener to be added, and a Media API defined method and/or attributes to be called/checked on the video. Play/Pause playpause.addEventListener('click', function(e) { if (video.paused || video.ended) video.play
(); else video.pause
(); }); When a click event is detected on the play/pause button, the handler first of all checks if the video is currently paused or has ended (via the Media API's paused and ended attributes); if so, it uses the play
() method to playback the video. Otherwise the video must be playing, so it is paused using the pause
() method. Stop stop.addEventListener('click', function(e...
...the video's current playing position) and the <progress> element's position is set to 0 (more on the <progress> element later). ...
...And 9 more matches
Rich-Text Editing in Mozilla - Developer guides
mple is an HTML document setting its own designMode to "On". This makes the entire document editable in Mozilla 1.3. Internet Explorer, however, does not allow javascript to change the current document's designMode. For it to work in Internet Explorer, the contentEditable attribute of the body tag needs to be set to "true". Figure 2 : First example HTML: <body contentEditable="true" onload="load
()"> JavaScript: function load
(){ window.document.designMode = "On"; } Example 2 The second example is a simple rich text editing page, where text can be bolded/italicized/underlined, new links can be added and the color of text changed. The example page consists of an iframe, which will be the rich editing area, as well as elements for basic editing commands such as bold/italics/text color. ...
...On"; } Example 2 The second example is a simple rich text editing page, where text can be bolded/italicized/underlined, new links can be added and the color of text changed. The example page consists of an iframe, which will be the rich editing area, as well as elements for basic editing commands such as bold/italics/text color. ...
...example is a simple rich text editing page, where text can be bolded/italicized/underlined, new links can be added and the color of text changed. The example page consists of an iframe, which will be the rich editing area, as well as elements for basic editing commands such as bold/italics/text color. ...
...And 9 more matches
Map - JavaScript
Performance Performs better in scenarios involving frequent additions and removals of key-value pairs. Not optimized for frequent additions and removals of key-value pairs. Setting object properties Setting Object properties works for Map objects as well, and can cause considerable confusion. Therefore, this appears to work in a way: let wrongMap = new Map
() wrongMap['bla'] = 'blaa' wrongMap['bla2'] = 'blaaa2' console.log(wrongMap) // Map { bla: 'blaa', bla2: 'blaaa2' } But that way of setting a property does not interact with the Map data structure. It uses the feature of the generic object. The value of 'bla' is not stored in the Map for queries. Other operations on the data fail: wrongMap.has('bla') // false wrongMap.delete('bla') // false...
...with the Map data structure. It uses the feature of the generic object. The value of 'bla' is not stored in the Map for queries. Other operations on the data fail: wrongMap.has('bla') // false wrongMap.delete('bla') // false console.log(wrongMap) // Map { bla: 'blaa', bla2: 'blaaa2' } The correct usage for storing data in the Map is through the set(key, value) method. ...
... Map.prototype.delete(key) Returns true if an element in the Map ob...
...And 9 more matches
async function - JavaScript
l get a SyntaxError. The purpose of async/await is to simplify the syntax necessary to consume promise-based APIs. The behavior of async/await is similar to combining generators and promises. Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. For example, the following: async function foo
() { return 1 } ...is equivalent to: function foo
() { return Promise.resolve(1) } The body of an async function can be thought of as being split by zero or more await expressions. Top-level code, up to and including the first await expression (if there is one), is run synchronously. In this way, an async function without an await expression will run synchronously. If there is an await exp...
...ght of as being split by zero or more await expressions. Top-level code, up to and including the first await expression (if there is one), is run synchronously. In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously. For example: async function foo
() { await 1 } ...is equivalent to: function foo
() { return Promise.resolve(1).then(
() => undefined) } Code after each await expression can be thought of as existing in a .then callback. In this way a promise chain is progressively constructed with each reentrant step through the function. The return value forms the final link in the chain. In the following example, we successively await...
...ielded. Some time later, when the second promise has either been fulfilled or rejected, control re-enters foo. The result of the second promise resolution is returned from the second await expression. Here 2 is assigned to result2. Control moves to the return expression (if any). The default return value of undefined is returned as the resolution value of the current promise. async function foo
() { const result1 = await new Promise((resolve) => setTimeout(
() => resolve('1'))) const result2 = await new Promise((resolve) => setTimeout(
() => resolve('2'))) } foo
() Note how the promise chain is not built-up in one go. Instead, the promise chain is constructed in stages as control is successively yielded from and returned to the async function. As a result, we must be mindful of error h...
...And 9 more matches
lang/type - Archive of obsolete content
let { isNull } = require('sdk/lang/type'); isNull(null); // true isNull(false); // false Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is null. isString(value) Returns true if value is a String, false otherwise. Uses typeof operator to check type, and will only properly detect string primitives: for example, a string created with new String
() will always return false. let { isString } = require('sdk/lang/type'); isString('my string'); // true isString(100); // false isString('100'); // true Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is a String. isNumber(value) Returns true if value is a Number, false otherwise. Uses typeof operator to check type, and will only properly detec...
...ype'); isString('my string'); // true isString(100); // false isString('100'); // true Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is a String. isNumber(value) Returns true if value is a Number, false otherwise. Uses typeof operator to check type, and will only properly detect number primitives: for example, a number created with new Number
() will always return false. let { isNumber } = require('sdk/lang/type'); isNumber(3.1415); // true isNumber(100); // true isNumber('100'); // false Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is a Number. isRegExp(value) Returns true if value is a RegExp, false otherwise. let { isRegExp } = require('sdk/lang/type'); isRegExp(/[^\.]*\.js$/...
...se otherwise. let { isRegExp } = require('sdk/lang/type'); isRegExp(/[^\.]*\.js$/); // true isRegExp(new RegExp('substring')); // true isRegExp(1000); // false Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is a RegExp. isDate(value) Returns true if value is a Date, false otherwise. ...
...And 8 more matches
Forms related code snippets - Archive of obsolete content
itle>DatePicker Example - MDN</title> <script type="text/javascript"> /*\ |*| |*| DatePicker Example MDNDeveloper Network |*| |*| https://developer.mozilla.org/docs/Code_snippets/Forms |*| https://developer.mozilla.org/User:fusionchess |*| |*| This snippet is released under the GNU Public License, version 3 or later. ...
...ment("thead"), oCapt = document.createElement("caption"), oDecrYear = document.createElement("span"), oIncrYear = document.createElement("span"), oDecrMonth = document.createElement("span"), oIncrMonth = document.createElement("span"); var nId = aInstances.length, oTH; this.target = oTarget; this.display = document.createElement("span"); this.current = new Date
(); this.container = oTable; this.display.className = sPrefs + "-current-month"; this.id = nId; oTable.className = sPrefs + "-calendar"; oTable.id = sPrefs + "-cal-" + nId; oDecrYear.className = sPrefs + "-decrease-year"; oDecrMonth.className = sPrefs + "-decrease-month"; oIncrMonth.className = sPrefs + "-increase-month"; oIncrYear.className = sPrefs + "-increase-...
...lement("th"); oTH.innerHTML = sDays[nThId]; oHRow.appendChild(oTH); } oTHead.appendChild(oHRow); oCapt.appendChild(oDecrYear); oCapt.appendChild(oDecrMonth); oCapt.appendChild(oIncrYear); oCapt.appendChild(oIncrMonth); oCapt.appendChild(this.display); this.container.appendChild(oCapt); this.container.appendChild(oTHead); this.current.setDate(1); this.writeDays
(); oTarget.onclick = function
() { if (oTable.parentNode) { oTable.parentNode.removeChild(oTable); return; } oTable.style.zIndex = nZIndex++; oTable.style.position = "absolute"; oTable.style.left = oTarget.offsetLeft + "px"; oTable.style.top = (oTarget.offsetTop + oTarget.offsetHeight) + "px"; oTarget.parentNode.insertBefore(oTable, oTa...
...And 8 more matches
Rosetta - Archive of obsolete content
ber 12, 2014 |*| |*| https://developer.mozilla.org/Add-ons/Code_snippets/Rosetta |*| https://developer.mozilla.org/User:fusionchess |*| |*| This framework is released under the GNU Public License, version 3 or later. ...
...ser:fusionchess |*| |*| This framework is released under the GNU Public License, version 3 or later. ...
...rCompiler); |*| \*/ var rosetta = new (function
() { function createScript (oScript, oXHR200) { var sMimeType = oScript.getAttribute("type").toLowerCase
(), oBaton = document.createComment(" The previous code has been automatically translated from \"" + sMimeType + "\" to \"text/ecmascript\". ...
...And 8 more matches
JavaScript crypto - Archive of obsolete content
ing text. Handling smart card events Web sites can make themselves more SmartCard friendly by listening for SmartCard insertion and removal events. To enable your document to receive these events, you must first tell the crypto system you are interested by setting window.crypto.enableSmartCardEvents to true. ...
...t handlers for these events with the document.addEventListener
() method. Two smart card related events are generated: smartcard-insert when SmartCards are inserted, and smartcard-remove when SmartCards are removed. Web sites which use SSL clientAuth login could use the following code to refresh the page on token insertions and removals: <!DOCTYPE html> <p>... ...
...ith the document.addEventListener
() method. Two smart card related events are generated: smartcard-insert when SmartCards are inserted, and smartcard-remove when SmartCards are removed. Web sites which use SSL clientAuth login could use the following code to refresh the page on token insertions and removals: <!DOCTYPE html> <p>... ...
...And 8 more matches
Nanojit - Archive of obsolete content
in zero or more other LirWriter objects, all of which implement the same interface as LirBufWriter. This chain of LirWriter objects forms a pipeline for the instructions to pass through. Each LirWriter can perform an optimization or other task on the program as it passes through the system and into the LirBuffer. Once the instructions are in the LirBuffer, the application calls nanojit::compile
() to produce machine code, which is stored in a nanojit::Fragment. Internally to Nanojit, another set of filters operates on the LIR as it passes from the LirBuffer toward the assembler. The result of compilation is a function that the application can call from C via a pointer to the first instruction. Example The following code works with SpiderMonkey's hacked version of Nanojit. Figuring out h...
...ttest ../jittest.cpp libjs_static.a Note: Remove the -DDEBUG if you have not compiled SpiderMonkey with --enable-debug, and use whatever you called the sample source file in place of jittest.cpp. ...
...the -DDEBUG if you have not compiled SpiderMonkey with --enable-debug, and use whatever you called the sample source file in place of jittest.cpp. ...
...And 8 more matches
Reference - Archive of obsolete content
Inheritance and Private Variables 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: function MyClass
(){ var property = 5; this.tellMe = function
(){ return property; } } function MyOtherClass
(){ MyClass.apply( this ); } var o = new MyOtherClass; alert( o.tellMe
() ); //alerts 5 as you'd expect -- the preceding comment was added by Psygnisfive (talk - contribs) on 22:23, 4 December 2006 Terminology We need a terminology appendix. For example, "script" and "pro...
...-Nickolay 00:58, 26 Aug 2005 (PDT) (More coding style questions) --Maian 04:06, 31 Aug 2005 (PDT) I'd say, just make a note here about decisions you make. It would be best to have all examples to use the same style. --Nickolay 05:37, 31 Aug 2005 (PDT) Gonna follow Mozilla's coding guides here: http://www.mozilla.org/hacking/mozil...de.html#Visual --Maian 00:30, 20 September 2005 (PDT) btoa
() and atob
() base64 encode and decode functions This documentation is missing the base64 encode (btoa) and decode (atob) functions. Anyone know why this has been left out? Danbeck 07:02, 22 September 2005 (PDT) AFAICT , base64-related functionality is not a part of the JavaScript engine, but a DOM feature (probably non-standard). --Nickolay 08:31, 22 September 2005 (PDT) What's funny is that th...
...e following you get same results which suggests that this is indeed the top level object. alert(Function.constructor.constructor) alert(Function.constructor.constructor.constructor.constructor) Function == Object However the following statement suggests that Function IS Object. ...
...And 8 more matches
Build the brick field - Game development
ded variables -- add the following below your previous variable definitions: var bricks; var newBrick; var brickInfo; The bricks variable will be used to create a group, newBrick will be a new object added to the group on every iteration of the loop, and brickInfo will store all the data we need. ...
...evious variable definitions: var bricks; var newBrick; var brickInfo; The bricks variable will be used to create a group, newBrick will be a new object added to the group on every iteration of the loop, and brickInfo will store all the data we need. Rendering the brick image Next, let's load the image of the brick -- add the following load.image
() call just below the others: function preload
() { // ... game.load.image('brick', 'img/brick.png'); } You also need to grab the brick image from Github and save it in your /img directory. Drawing the bricks We will place all the code for drawing the bricks inside an initBricks function to keep it separated from the rest of the code. Add a call to initBricks at the end of the create
() function: function create
(){ // ... ini...
...// ... game.load.image('brick', 'img/brick.png'); } You also need to grab the brick image from Github and save it in your /img directory. Drawing the bricks We will place all the code for drawing the bricks inside an initBricks function to keep it separated from the rest of the code. Add a call to initBricks at the end of the create
() function: function create
(){ // ... initBricks
(); } Now onto the function itself. ...
...And 8 more matches
Function - MDN Web Docs Glossary: Definitions of Web-related terms
n 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. ...
... 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. ...
...n 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 the ECMAScript language specification, they're jargon used to refer to different types of functions. A named function is a function with a function name: // Function declaration function foo
() {}; // Named function expression (function bar
() {}); // or using the ECMAScript 2015 arrow notation const foo =
() => {}; An inner function is a function inside another function (square in this case). An outer function is a function containing a function (addSquares in this case): function addSquares(a,b) { function square(x) { return x * x; } return square(a) + square(b); }; /...
...And 8 more matches
Manipulating documents - Learn web development
'Mozilla Developer Network'; We should also change the URL the link is pointing to, so that it doesn't go to the wrong place when it is clicked on. Add the following line, again at the bottom: link.href = 'https://developer.mozilla.org'; Note that, as with many things in JavaScript, there are many ways to select an element and store a reference to it in a variable. ...
...ed on. Add the following line, again at the bottom: link.href = 'https://developer.mozilla.org'; Note that, as with many things in JavaScript, there are many ways to select an element and store a reference to it in a variable. Document.querySelector
() is the recommended modern approach, which is convenient because it allows you to select elements using CSS selectors. The above querySelector
() call will match the first <a> element that appears in the document. If you wanted to match and do things to multiple elements, you could use Document.querySelectorAll
(), which matches every element in the document that matches the selector, and stores references to them in an array-like object called a NodeList. There are older methods available for grabbing element references, such as: Docum...
...he first <a> element that appears in the document. If you wanted to match and do things to multiple elements, you could use Document.querySelectorAll
(), which matches every element in the document that matches the selector, and stores references to them in an array-like object called a NodeList. There are older methods available for grabbing element references, such as: Document.getElementById
(), which selects an element with a given id attribute value, e.g. <p id="myId">My paragraph</p>. The ID is passed to the function as a parameter, i.e. const elementRef = document.getElementById('myId'). Document.getElementsByTagName
(), which returns an array-like object containing all the elements on the page of a given type, for example <p>s, <a>s, etc. The element type is passed to the function ...
...And 8 more matches
Componentizing our React app - Learn web development
before you run these! mkdir src/components touch src/components/Todo.js Our new Todo.js file is currently empty! Open it up and give it its first line: import React from "react"; Since we're going to make a component called Todo, you can start adding the code for that to Todo.js too, as follows. ...
...art adding the code for that to Todo.js too, as follows. ...
...mponent renders a unique name. In App.js, give each <Todo /> a name prop. Let's use the names of our tasks that we had before: <Todo name="Eat" /> <Todo name="Sleep" /> <Todo name="Repeat" /> When your browser refreshes, you will see... the exact same thing as before. We gave our <Todo /> some props, but we aren't using them yet. Let's go back to Todo.js and remedy that. First modify your Todo
() function definition so that it takes props as a parameter. You can console.log
() your props as we did before, if you'd like to check that they are being received by the component correctly. Once you're confident that your component is getting its props, you can replace every occurrence of Eat with your name prop. Remember: when you're in the middle of a JSX expression, you use curly braces to in...
...And 8 more matches
Getting started with React - Learn web development
ented to the same position as its corresponding closing tag. Of course, your browser can't read JSX without help. When compiled (using a tool like Babel or Parcel), our header expression would look like this: const header = React.createElement("header", null, React.createElement("h1", null, "Mozilla Developer Network") ); It's possible to skip the compilation step and use React.createElement
() to write your UI yourself. In doing this, however, you lose the declarative benefit of JSX, and your code becomes harder to read. Compilation is an extra step in the development process, but many developers in the React community think that the readability of JSX is worthwhile. Plus, popular tooling makes the JSX-to-JavaScript compilation part of its setup process. You don't have to configure com...
...is a reusable module that renders a part of our app. These parts can be big or small, but they are usually clearly defined: they serve a single, obvious purpose. Let's open src/App.js, since our browser is prompting us to edit it. This file contains our first component, App, and a few other lines of code: import React from 'react'; import logo from './logo.svg'; import './App.css'; function App
() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React ...
...eact components follow this pattern. Import statements The import statements at the top of the file allow App.js to use code that has been defined elsewhere. Let's look at these statements more closely. import React from 'react'; import logo from './logo.svg'; import './App.css'; The first statement imports the React library itself. Because React turns the JSX we write into React.createElement
(), all React components must import the React module. If you skip this step, your application will produce an error. The second statement imports a logo from './logo.svg'. Note the use of ./ at the beginning of the path, and the .svg extension at the end -- these tell us that the file is local and that it is not a JavaScript file. Indeed, the logo.svg file lives in our source directory. We don't ...
...And 8 more matches
A bird's-eye view of the Mozilla framework
y interacts with the IDL interface. The client would like to ask the nsIRDFNode whether its supports nsIRDFLiteral. An nsIRDFNode must be an nsIRDFLiteral or an nsIRDFResource. The link is a literal, so the client wants nsIRDFLiteral. Since all XPCOM interfaces inherit the base interface nsISupports, the client can ask whether nsIRDFNode supports nsIRDFLiteral by calling nsIRDFNode.QueryInterface
(), a method in the nsISupports interface. [scriptable, uuid(00000000-0000-0000-c000-000000000046)] interface nsISupports { void QueryInterface(in nsIIDRef uuid, iid_is(uuid),retval] out nsQIResult result); [noscript, notxpcom] nsrefcnt AddRef
(); [noscript, notxpcom] nsrefcnt Release
(); }; The uuid parameter to QueryInterface
() is the IID uniqely identifying the interface. If...
... Inside an XPCOM Component Figure 3 shows a more detailed view of an XPCOM component. Figure 3. ...
... Inside an XPCOM Component Figure 3 shows a more detailed view of an XPCOM component. Figure 3. ...
...And 8 more matches
Communicating with frame scripts
y, frame scripts can pass wrappers called Cross Process Object Wrappers (also known as CPOWs) to chrome, and chrome can use these wrappers to get synchronous access to content objects. Content to chrome The frame script can choose to send synchronous or asynchronous messages to chrome code. Asynchronous messaging To send an asynchronous message the frame script uses the global sendAsyncMessage
() function: // frame script sendAsyncMessage("my-addon@me.org:my-e10s-extension-message"); sendAsyncMessage
() takes one mandatory parameter, which is the name of the message. All messages share the same namespace, so to avoid conflicts with other code, you'll need to ensure that the names you use are unique. If you're using the message manager in an add-on, a good way to do that is to prefix mess...
... target The XUL <browser> element from which this message ...
...o add a message listener using the message manager's addMessageListener
() API. The message passed to the listener is an object containing the following properties: name String containing the message name. sync Boolean declaring whether the message was send synchronously or aynchronously. data The JSON object passed as the second parameter to sendAsyncMessage
(). target The XUL <browser> element from which this message was sent. ...
...And 8 more matches
Assert.jsm
, actual, expected, message, operator); Constructor Creates a new Assert object. let assert = new Assert(reporterFunc); The new Assert instance, assert, uses reporterFunc to report assertion results or throws an AssertionError when an assertion fails, as default behavior. ok, equal, notEqual, deepEqual, notDeepEqual, strictEqual, notStrictEqual, throws, setReporter, report Methods ok
() Pure assertion tests whether a value is truthy, as determined by !!guard. This statement is equivalent to assert.equal(true, !!guard, message_opt);. To test strictly for the value true, use assert.strictEqual(true, guard, message_opt);. undefined ok( actual, message ); Parameters actual Test subject to be evaluated as truthy message Short explanation of the expected result equal(...
... to be evaluated as truthy message Short explanation of the expected result equal
() The equality assertion tests shallow, coercive equality with ==. undefined equal( actual, expected, message ); Parameters actual Test subject to be evaluated as equivalent to expected expected Test reference to evaluate against actual message Short explanation of the expected result notEqual
() The non-equality assertion tests for whether two objects are not equal with !=. undefined notEqual( actual, expected, message ); Parameters actual Test subject to be evaluated as not equivalent to expected expected Test reference to evaluate against actual message Short explanation of the expected result deepEqual
() The equivalence assertion tests a deep equality relation. W...
... expected Test reference to evaluate against actual message Short explanation of the expected result deepEqual
() The equivalence assertion tests a deep equality relation. We check using the most exact approximation of equality between two objects to keep the chance of false positives to a minimum. JSON.stringify is not designed to be used for this purpose; objects may have ambiguous toJSON
() implementations that would influence the test. undefined deepEqual( actual, expected, message ); Parameters actual Test subject to be evaluated as equivalent to expected, including nested properties expected Test reference to evaluate against actual message Short explanation of the expected result notDeepEqual
() The non-equivalence assertion tests for any deep inequality. und...
...And 8 more matches
DeferredTask.jsm
The DeferredTask constructor Requires Gecko 18.0(Firefox 18.0 / Thunderbird 18.0 / SeaMonkey 2.15) If you have a function call you want to defer for two seconds, you can do so using the DeferredTask constructor, like this: var task = new DeferredTask(myFunction, 2000); You can also pass a generator function as the first argument of constructor. ...
...cko 18.0(Firefox 18.0 / Thunderbird 18.0 / SeaMonkey 2.15) If you have a function call you want to defer for two seconds, you can do so using the DeferredTask constructor, like this: var task = new DeferredTask(myFunction, 2000); You can also pass a generator function as the first argument of constructor. Method overview bool isPending
();Obsolete since Gecko 28 void start
();Obsolete since Gecko 28 void flush
();Obsolete since Gecko 28 void cancel
();Obsolete since Gecko 28 void arm
(); void disarm
(); Promise finalize
(); Attributes isArmed boolean Indicates whether the task is currently requested to start again later, regardless of whether it is currently running. isRunning boolean Indica...
... regardless of whether it is currently running. isRunning boolean Indicates whether the task is currently running. This is always true when read from code inside the task function, but can also be true when read from external code, in case the task is an asynchronous generator function. Methods isPending Obsolete since Gecko 28 Check the current task state. bool isPending
(); Return value Returns true if pending, false otherwise. start Obsolete since Gecko 28 Start (or postpone) task. void start
(); flush Obsolete since Gecko 28 Perform any postponed task immediately. void flush
(); cancel Obsolete since Gecko 28 Cancel any pending task. void cancel
(); arm Request the execution of the task after the delay specified on construction. Multiple calls ...
...And 8 more matches
Following the Android Toasts Tutorial from a JNI Perspective
aft saved" toast to let you know that you can continue editing later. Toasts automatically disappear after a timeout. Toasts do not have to be created with JNI; they are exposed by the NativeWindow feature on Firefox for Android, see toast documentation. Java code Let's start with the following 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 F...
... Java environment Before we go on to declare the other important features, we need to load our environment variable. We want to wrap this in a try-catch statement so if any errors occur we make sure to unload the classes and the Java environment, this is good for performance. This is the template that will follow our object of signatures: var my_jenv = null; try { my_jenv = JNI.GetForThread
(); // do the jni work here } finally { if (my_jenv) { JNI.UnloadClasses(my_jenv); } } The reason we choose my_jenv for a variable name, and not jenv, is 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 ...
...eturn column of the show method does not contain the word static. Therefore, it is a plain method. Let's declare these methods in the third argument of LoadClass we add a key-value pair, with the key being static_methods and methods and the value being an array. var Toast = JNI.LoadClass(my_jenv, SIG.Toast.substr(1, SIG.Toast.length - 2), { static_methods: [ { name: 'makeText', sig: '
()' } ], methods: [ { name: 'show', sig: '
()' } ] }); The sig of methods is always in the format of "method format" from our types table above. The reason is that methods accept arguments and return something. We need to declare now the arguments and return type for each of the methods. The documentation says makeText takes three arguments, the types are Context, int, and int ...
...And 8 more matches
Log.jsm
/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.Level.Debug; // A console appender logs to the browser console. log.addAppender(new Log.ConsoleAppender(new Log.BasicFormatter
())); // A dump appender logs to stdout. log.addAppender(new Log.DumpAppender(new Log.BasicFormatter
())); // Log some messages log.error("Oh noes!! Something bad happened!"); log.debug("Details about bad thing only useful during debugging", {someInfo: "nothing"}); log.warn("Here is an error", new Error("ouch")); Logger levels FATAL Severe errors that cause premature termination. Ex...
..., so be conservative and keep to a minimum. CONFIG Information regarding important configuration options the system is using that affect how it runs. DEBUG Detailed information on the flow through the system. Expect these to be written to logs only. TRACE Most detailed information. Expect these to be written to logs only. ...
...ion regarding important configuration options the system is using that affect how it runs. DEBUG Detailed information on the flow through the system. Expect these to be written to logs only. TRACE Most detailed information. Expect these to be written to logs only. ...
...And 8 more matches
Property cache
ime t1 an object y has shape s; and no shape-regenerating GC occurred; then at time t1 y's own property p is the same method property. (The existence of this property is guaranteed by the basic layout guarantee above.) (Informally: two objects with the same shape have the same METHOD properties.) Branded object guarantee -- If at time t0 the object x has shape s; and x is branded (x->branded
()); and x has an own property p, which is a writable, Function-valued data property with the stub getter and setter and a slot; and at time t1 an object y has shape s; and no shape-regenerating GC occurred; then y is x, and at time t1 x's own property p has the same Function value it had at time t0. (The existence of this property is guaranteed by the basic layout guarantee above.) (Informally: bra...
.... because the property has a setter and not a getter; or vice versa. Lookups for JOF_NAME instructions are quite different from ordinary property lookups: name lookups follow the scope chain and the prototype chain, whereas the others only follow the prototype chain. There are two different types of property cache entry. Non-adding cache entries {.kpc=pc, .kshape=kshape, .vshape
()=vshape, .scopeIndex
()=scopeIndex, .protoIndex
()=protoIndex, .vword=vword} This type of entry is created for all instructions that use the property cache. When the operand to the instruction at pc is an object obj with shape kshape, let pobj = the object found by walking scopeIndex steps up the parent chain and then protoIndex steps up the prototype chain. If pobj exists (that is,...
...property with the same name is ever added to an object anywhere along the search path, then this cache entry becomes invalid: the property described by this property cache entry has been shadowed. The two shadowing guarantees ensure that if this happens, the shape of pobj changes, invalidating the entry. Setting. For JOF_SET instructions, this makes two additional guarantees: first, vword.isSprop
(); second, the correct behavior is to set the property described by vword.toSprop
(), rather than to shadow it with a new own property. Teleportation. The JIT handles situations where scopeIndex != 0 or protoIndex > 1 specially. It walks the scope chain and prototype chain as described above only once, at compile time, and emits code containing the pointer to the object that contains the property. ...
...And 8 more matches
Aggregating the In-Memory Datasource
ul, prone to errors, and fragile as the interfaces are still in flux (a wee bit). Aggregation to the rescue! Here are the gory details on how. When It Won't Work Although this magic is terribly convenient to use, it won't work in the case that you want to "override" some of the in-memory datasource's methods. For example, while writing the bookmarks datasource, I wanted to be able to trap Assert
() to enforce the bookmarks datasource would only accept "bookmarks related" assertions. If I'd just delegated to the in-memory datasource, Assert
() would've taken any old random garbage. Similarly, I wanted to trap Flush
() so that I could write the bookmarks.html file back to disk. In short, the only case where this technique is useful is when you're implementing a datasource to get "read-only ref...
...you'll just want an nsCOMPtr<nsISupports>: class MyClass : public nsIMyInterface { ... ...
...he datasource delegate when your object is constructed (or, at worst, when somebody QI's for it): rv = nsComponentManager::CreateInstance( kRDFInMemoryDataSourceCID, this, /* the "outer" */ nsCOMTypeInfo<nsISupports>::GetIID
(), getter_AddRefs(mInner)); Note passing this as the "outer" parameter. Now, if the in-memory datasource's implementation of QueryInterface
() fails because it doesn't support the requested interface, it willforward the query interface to its "outer" (which is "us"). ...
...And 8 more matches
Generic factory
In XPCOM, a generic factory is a factory created using the facilities in xpcom/glue/nsIGenericFactory.h. Summary Most XPCOM factories can be very simple. Rick Potts wrote a templated-based generic factory (nsFactory<T>) that simplifies the factory creation process that just requires writing a CreateInstance
() method. ...
...ory interface takes this a step further, by providing a single interface that can be reused anytime a simple implementation of nsIFactory is needed. Here is the interface, and a description of its use. /** * Provides a Generic nsIFactory implementation that can be used by * DLLs with very simple factory needs. */ class nsIGenericFactory : public nsIFactory { public: static const nsIID& IID
() { static nsIID iid = NS_IGENERICFACTORY_IID; return iid; } typedef NS_CALLBACK(ConstructorProcPtr) (nsISupports *aOuter, REFNSIID aIID, void **aResult); /** * Establishes the generic factory's constructor function, which will be called * by CreateInstance. */ NS_IMETHOD SetConstructor(ConstructorProcPtr constructor) = 0; }; Using nsIGenericFactory is simple. Create ...
...ance from the repository with a CID of NS_GENERICFACTORY_CID, and and IID of NS_IGENERICFACTORY_IID. Define a constructor function that matches the ConstructorProcPtr prototype, and call nsIGenericFactory::SetConstructor with a pointer to that function. You're done. You now have a fully functional factory object. ...
...And 8 more matches
Components.utils
Components.utils is a collection of various useful XPConnect features. Its interface is defined at js/xpconnect/idl/xpccomponents.idl. The object currently has the following members: EDITORS! 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 para...
...s an array created in specified compartment. createObjectIn
() Creates a new object, created in the scope of the specified object's compartment. dispatch
() Dispatches a runnable to the current/main thread. If the parameter is passed, the runnable will be dispatch in the compartment of the parameter, which affects which error reporter gets called. evalInSandbox
() Runs JavaScript code in a sandbox, usually used to run code with restricted privileges. evalInWindow
() Removed in Gecko 34. Evaluate JavaScript code in a less-privileged JavaScript context. exportFunction
() Export a JavaScript function from a more-privileged to a less-privileged scope, allowing it to be called in the less-privileged scope. ...
...aScript 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. forceGC
() Forces a garbage collection cycle. forceCC
() Forces a cycle collection cycle. forceShrinkingGC
() Forces a shrinking garbage collection cycle. ...
...And 8 more matches
IAccessible2
An extended role is a role which is dynamically generated by the application. It is not predefined ...
...pget] HRESULT uniqueID([out] long uniqueID ); [propget] HRESULT windowHandle([out] HWND windowHandle ); Methods attributes
() Returns the attributes specific to this IAccessible2 object, such as a cell's formula. [propget] HRESULT attributes( [out] BSTR attributes ); Parameters attributes Return value S_FALSE returned if there is nothing to return, [out] value is null. S_OK. extendedRole
() Returns the extended role. An extended role is a role which is dynamically generated by the application. It is not predefined by the IAccessible2 specification. [propget] HRESULT extendedRole( [out] BSTR extendedRole ); Parameters extendedRole Return value S_FALSE if there is nothing to return, [out] value is null. S_OK. extendedStates
() Returns the extended states (array of strings). An ex...
...s This parameter is ignored. Refer to @ref _arrayConsideration "Special Consideration when using Arrays" for more details. extendedStates This array is allocated by the server. Free it with CoTaskMemFree. nExtendedStates The number of extended states returned; the size of the returned array. Return value S_FALSE if there are no states, [out] values are null and 0 respectively. S_OK. groupPosition
() Returns grouping information. Used for tree items, list items, tab panel labels, radio buttons, and so on. Also used for collections of non-text objects. [propget] HRESULT groupPosition( [out] long groupLevel, [out] long similarItemsInGroup, [out] long positionInGroup ); Parameters groupLevel 1 based, 0 indicates that this value is not applicable. similarItemsInGroup 1 based, 0 indicates ...
...And 8 more matches
imgIRequest
modules/libpr0n/public/imgIRequest.idlScriptable Please add a summary to this article. Inherits from: nsIRequest Last changed in Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5) Method overview void cancelAndForgetObserver(in nsresult aStatus); imgIRequest clone(in imgIDecoderObserver aObserver); void decrementAnimationConsumers
(); imgIRequest getStaticRequest
(); void incrementAnimationConsumers
(); void lockImage
(); void requestDecode
(); void unlockImage
(); Attributes Attribute Type Description CORSMode long The CORS mode that this image was loaded with. Read only. decoderObserver imgIDecoderObserver Read only. image imgIContainer The image container. Read only. imagePrincipal nsIPrincipal The principal gotten from the channel th...
...age load was started with. Note that this might not be the actual URI for the image (for example if HTTP redirects happened during the load). Read only. Constants Constant Value Description STATUS_NONE 0x0 Nothing to report. STATUS_SIZE_AVAILABLE 0x1 We received enough image data from the network or filesystem that we know the width and height of the image, and have thus called SetSize
() on the container. STATUS_LOAD_PARTIAL 0x2 Used internally by imgRequest to flag that a request is being cancelled as a result of a failure of a proxy holder and not an internal failure. At least I think that's what it does. Regardless, there's no reason for this flag to be public, and it should either go away or become a private state flag within imgRequest. Do not rely on it. STATUS_LOAD_COM...
...an be loaded with. By default, all images are loaded with CORS_NONE and cannot be used cross-origin in context like WebGL. If an HTML img element has the crossorigin attribute set, the imgIRequest will be validated for cross-origin usage with CORS, and, if successful, will have its CORS mode set to the relevant type. CORS_ANONYMOUS 2 CORS_USE_CREDENTIALS 3 Methods cancelAndForgetObserver
() Cancels this request as in nsIRequest.Cancel
(); further, also nulls out decoderObserver so it gets no further notifications from us. Note: You should not use this in any new code; instead, use cancel
(). Note that cancel
() is asynchronous, which means that some time after you call it, the listener/observer will get an OnStopRequest
(). This means that, if you're the observer, you can not call cance...
...And 8 more matches
nsIDOMMozNetworkStatsManager
Read only. maxStorageAge long long Time in milliseconds recorded by the API until present time. All samples older than...
...Read only. maxStorageAge long long Time in milliseconds recorded by the API until present time. All samples older than maxStorageAge from now are deleted. Read only. ...
...Read only. maxStorageAge long long Time in milliseconds recorded by the API until present time. All samples older than maxStorageAge from now are deleted. Read only. Constants Constant Type Descripti...
...And 8 more matches
nsIDocumentLoader
tifications. Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Implemented by: @mozilla.org/docloaderservice;1. ...
...g/docloaderservice;1. ...
...quest aRequest, in nsIURI aUri); Obsolete since Gecko 1.8 void fireOnStatusChange(in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage); Obsolete since Gecko 1.8 void getContentViewerContainer(in nsISupports aDocumentID, out nsIContentViewerContainer aResult); Native code only! ...
...And 8 more matches
nsIDragService
widget/nsIDragService.idlScriptable Implements the Drag Service for handling drag and drop operations. Inherits from: nsISupports Last changed in Gecko 43 (Firefox 43 / Thunderbird 43 / SeaMonkey 2.40) Note: Using this interface directly from add-on code is deprecated. Add-ons should use the standard dataTransfer drag and drop API instead. The only exception is getCurrentSession
(), since there's currently no way to check for a drag in progress using standard DOM methods or properties. Method overview void endDragSession( in PRBool aDoneDrag ) ; void dragMoved(in long aX, in long aY); Native code only! void fireDragEventAtSource(in unsigned long aMsg); Obsolete since Gecko 43 void fireDragEventAtSource(in mozilla::EventMessage aEventMess...
... DRAGDROP_ACTION_COPY 1 The drag and drop operation should copy the object. DRAGDROP_ACTION_MOVE 2 The drag and drop operation should move the object. DRAGDROP_ACTION_LINK 4 The drag and drop operation should link t...
... DRAGDROP_ACTION_COPY 1 The drag and drop operation should copy the object. DRAGDROP_ACTION_MOVE 2 The drag and drop operation should move the object. DRAGDROP_ACTION_LINK 4 The drag and drop operation should link the object. DRAGDROP_...
...And 8 more matches
nsIMicrosummaryService
summary/service;1 as a service: var microsummaryService = Components.classes["@mozilla.org/microsummary/service;1"] .getService(Components.interfaces.nsIMicrosummaryService); Method overview void addGenerator(in nsIURI generatorURI); nsIMicrosummary createMicrosummary(in nsIURI pageURI, in nsIURI generatorURI); nsISimpleEnumerator getBookmarks
(); nsIMicrosummaryGenerator getGenerator(in nsIURI generatorURI); nsIMicrosummarySet getMicrosummaries(in nsIURI pageURI, in long long bookmarkID); nsIMicrosummary getMicrosummary(in long long bookmarkID); boolean hasMicrosummary(in long long bookmarkID); nsIMicrosummaryGenerator installGenerator(in nsIDOMDocument xmlDefinition); boolean isMicr...
...nsIMicrosummary createMicrosummary( in nsIURI ...
...ary microsummary); nsIMicrosummary refreshMicrosummary(in long long bookmarkID); void removeMicrosummary(in long long bookmarkID); void setMicrosummary(in long long bookmarkID, in nsIMicrosummary microsummary); Methods addGenerator
() Install the microsummary generator from the resource at the supplied URI. Callable by content via nsISidebar.addMicrosummaryGenerator
(). void addGenerator( in nsIURI generatorURI ); Parameters generatorURI The URI of the resource providing the generator. createMicrosummary
() Create a microsummary for a given page URI and generator URI. nsIMicrosummary createMicrosummary( in nsIURI pageURI, in nsIURI generatorURI ); Parameters pageURI The URI of the page to be summarized. generatorURI The URI of ...
...And 8 more matches
nsISupportsArray
xpcom/ds/nsISupportsArray.idlScriptable Please add a summary to this article. ...
... xpcom/ds/nsISupportsArray.idlScriptable Please add a summary to this article. ...
...lates the XPCOM interface guidelines boolean RemoveLastElement([const] in nsISupports aElement); Violates the XPCOM interface guidelines boolean ReplaceElementAt(in nsISupports aElement, in unsigned long aIndex); Violates the XPCOM interface guidelines boolean SizeTo(in long aSize); Violates the XPCOM interface guidelines Methods Violates the XPCOM interface guidelines AppendElements
() boolean AppendElements( in nsISupportsArray aElements ); Parameters aElements Return value clone
() nsISupportsArray clone
(); Parameters None. Return value Compact
() void Compact
(); Parameters None. DeleteElementAt
() void DeleteElementAt( in unsigned long aIndex ); Parameters aIndex DeleteLastElement
() void DeleteLastElement( in nsISupports aElement ); Parameters aElement ...
...And 8 more matches
Debugger.Object - Firefox Developer Tools
ferent 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 displayName and name properties are equal. If a function has no name, SpiderMonkey attempts to infer an appropriate name for it given its context. ...
...unction, 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 displayName and name properties are equal. If a function has no name, SpiderMonkey attempts to infer an appropriate name for it given its context. For example: function f
() {} // display name: f (the given name) var g = function
() {}; // display name: g o.p = function
() {}; // display name: o.p var q = { r: function
() {} // display name: q.r }; Note that the display name may not be a proper JavaScript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property. Thus, we use a/b to refer to the b defined...
...Note that the display name may not be a proper JavaScript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property. Thus, we use a/b to refer to the b defined within a, and a< to refer to a function that occurs somewhere within an expression that is assigned to a. For example: function h
() { var i = function
() {}; // display name: h/i f(function
() {}); // display name: h/< } var s = f(function
() {}); // display name: s< parameterNames If the referent is a debuggee function, the names of the its parameters, as an array of strings. If the referent is not a debuggee function, or not a function at all, this is undefined. If the referent is a host function for ...
...And 8 more matches
Attr - Web APIs
The Attr interface represents one of a DOM element's attributes as an object. In most DOM methods, you will directly retrieve the attribute as a string (e.g., Element.getAttribute
()), but certain functions (e.g., Element.getAttributeNode
()) or means of iterating return Attr types. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/EventTarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="Consolas,Mona...
...information associated with this attribute. While the type information contained in this attribute is guaranteed to be correct after loading the document or invoking Document.normalizeDocument, this property may not be reliable if the node was moved. specified This property now always returns true. textContent Use Attr.value instead. ...
...ed in this attribute is guaranteed to be correct after loading the document or invoking Document.normalizeDocument, this property may not be reliable if the node was moved. specified This property now always returns true. textContent Use Attr.value instead. The following methods have been deprecated: appendChild
() Obsolete since Gecko 14 Modify the value of Attr.value instead. ...
...And 8 more matches
CSS Painting API - Web APIs
You can then apply these values to properties like background-image to set complex custom backgrounds on an element. ...
... 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 CanvasRenderingContext2D settings. ...
...ead-only values of the output bitmap's width and height. Dictionaries PaintRenderingContext2DSettings A dictionary providing a subset of CanvasRenderingContext2D settings. Examples To draw directly into an element's background using JavaScript in our CSS, we define a paint worklet using the registerPaint
() function, tell the document to include the worklet using the paintWorklet addModule
() method, then include the image we created using the CSS paint
() function. ...
...And 8 more matches
CacheStorage - Web APIs
her type of worker or window scope (you're not limited to only using it with service workers, even though the Service Workers spec defines it). 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. Use CacheStorage.open
() to obtain a Cache instance. Use CacheStorage.match
() to check if a given Request is a key in any of the Cache objects that the CacheStorage object tracks. You can access CacheStorage through the global caches property. Note: CacheStorage always rejects with a SecurityError on untrusted origins (i.e. those that aren't using HTTPS, although this definition will likely become more complex in the ...
...e global caches property. Note: CacheStorage always rejects with a SecurityError on untrusted origins (i.e. those that aren't using HTTPS, although this definition will likely become more complex in the future.) When testing, you can get around this by checking the "Enable Service Workers over HTTP (when toolbox is open)" option in the Firefox Devtools options/gear menu. ...
...definition will likely become more complex in the future.) When testing, you can get around this by checking the "Enable Service Workers over HTTP (when toolbox is open)" option in the Firefox Devtools options/gear menu. Note: CacheStorage.match
() is a convenience method. Equivalent functionality to match a cache entry can be implemented by returning an array of cache names from CacheStorage.keys
(), opening each cache with CacheStorage.open
(), and matching the one you want with Cache.match
(). Methods CacheStorage.match
() Checks if a given Request is a key in any of the Cache objects that the CacheStorage object tracks, and returns a Promise that resolves to that match. CacheStorage.has
() Returns a Promise that resolves to true if a Cache object matching the cacheName exists. CacheSt...
...And 8 more matches
Element.classList - Web APIs
mited string via element.className. Syntax const elementClasses = elementNodeReference.classList; Returns A DOMTokenList representing the contents of the element's class attribute. If the class attribute is not set or empty, it returns an empty DOMTokenList, i.e. a DOMTokenList with the length property equal to 0. The DOMTokenList itself is read-only, although you can modify it using the add
() and remove
() methods. Examples const div = document.createElement('div'); div.className = 'foo'; // our starting state: <div class="foo"></div> console.log(div.outerHTML); // use the classList API to remove and add classes div.classList.remove("foo"); div.classList.add("anotherclass"); // <div class="anotherclass"></div> console.log(div.outerHTML); // if visible is set remove it, otherwise ...
...className property that fires the specified event once it is changed. The following polyfill for both classList and DOMTokenList ensures full compliance (coverage) for all standard methods and properties of Element.prototype.classList for IE10-IE11 browsers plus nearly compliant behavior for IE 6-9. Check it out: // 1. ...
...haracters, which are not valid in tokens."); } // 2. ...
...And 8 more matches
Event - Web APIs
The Event interface represents an event which takes place in the DOM. An event can be triggered by the user action e.g. clicking the mouse button or tapping keyboard, or generated by APIs to represent the progress of an asynchronous task. It can also be triggered programmatically, such as by calling the HTMLElement.click
() method of an element, or by defining the event, then sending it to a specified target using EventTarget.dispatchEvent
(). There are many types of events, some of which use other interfaces based on the main Event interface. Event itself contains the properties and methods which are common to all events. Many DOM elements can be set up to accept (or "listen" for) these events, and execute code in response to process (or "handle") them. Event-handlers are usually connecte...
...ed on the main Event interface. Event itself contains the properties and methods which are common to all events. Many DOM elements can be set up to accept (or "listen" for) these events, and execute code in response to process (or "handle") them. Event-handlers are usually connected (or "attached") to various HTML elements (such as <button>, <div>, <span>, etc.) using EventTarget.addEventListener
(), and this generally replaces using the old HTML event handler attributes. Further, when properly added, such handlers can also be disconnected if needed using removeEventListener
(). Note: One element can have several such handlers, even for the exact same event--particularly if separate, independent code modules attach them, each for its own independent purposes. (For example, a webpage with an...
...Setting its value to true before returning from an event handler prevents propagation of the event. Event.cancelable Read only A boolean indicating whether th...
...And 8 more matches
HTMLSelectElement - Web APIs
ue property of the first selected option element if there is one, otherwise the empty string. HTMLSelectElement.willValidateRead only A Boolean that indicates whether the button is a candidate for constraint validation. It is false if any conditions bar it from constraint validation. Methods This interface inherits the methods of HTMLElement, and of Element and Node. HTMLSelectElement.add
() Adds an element to the collection of option elements for this select element. HTMLSelectElement.blur
() Removes input focus from this element. This method is now implemented on HTMLElement. HTMLSelectElement.checkValidity
() Checks whether the element has any constraints and whether it satisfies them. If the element fails its constraints, the browser fires a cancelable invalid event at the el...
...nts for this select element. HTMLSelectElement.blur
() Removes input focus from this element. This method is now implemented on HTMLElement. HTMLSelectElement.checkValidity
() Checks whether the element has any constraints and whether it satisfies them. If the element fails its constraints, the browser fires a cancelable invalid event at the element (and returns false). HTMLSelectElement.focus
() Gives input focus to this element. This method is now implemented on HTMLElement. HTMLSelectElement.item
() Gets an item from the options collection for this <select> element. You can also access an item by specifying the index in array-style brackets or parentheses, without calling this method explicitly. ...
... the element (and returns false). HTMLSelectElement.focus
() Gives input focus to this element. This method is now implemented on HTMLElement. HTMLSelectElement.item
() Gets an item from the options collection for this <select> element. You can also access an item by specifying the index in array-style brackets or parentheses, without calling this method explicitly. HTMLSelectElement.namedItem
() Gets the item in the options collection with the specified name. The name string can match either the id or the name attribute of an option node. You can also access an item by specifying the name in array-style brackets or parentheses, without calling this method explicitly. ...
...And 8 more matches
Ajax navigation example - Web APIs
(or git clone https://github.com/giabao/mdn-ajax-nav-example.git ): Note: For fully integrating the <form> elements within this mechanism, please take a look at the paragraph Submitting forms and uploading files. first_page.php: <?php $page_title = "First page"; $as_json = false; if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") { $as_json = true; ob_start
(); } else { ?> <!doctype html> <html> <head> <?php include "include/header.php"; echo "<title>" . $page_title . "</title>"; ?> </head> <body> <?php include "include/before_content.php"; ?> <p>This paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p> <div id="ajax-content"> <?php } ?> <p>This is the content of <strong>first_page.p...
...title . ...
...$page_title . "</title>"; ?> </head> <body> <?php include "include/before_content.php"; ?> <p>This paragraph is shown only when the navigation starts from <strong>second_page.php</strong>.</p> <div id="ajax-content"> <?php } ?> <p>This is the content of <strong>second_page...
...And 8 more matches
NodeList - Web APIs
Live vs. Static NodeLists Although they are both considered NodeLists, there are 2 varieties of NodeList: live and static. ...
... Live vs. Static NodeLists Although they are both considered NodeLists, there are 2 varieties of NodeList: live and static. ...
... Live vs. Static NodeLists Although they are both considered NodeLists, there are 2 varieties of NodeList: live and static. ...
...And 8 more matches
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
the job done. The following function returns a projection perspective matrix that integrates the specified field of view angle as well as the given near and far clipping plane distances: function createPerspectiveMatrix(viewport, fovDegrees, nearClip, farClip) { const fovRadians = fov * (Math.PI / 180.0); const aspectRatio = viewport.width / viewport.height; const transform = mat4.create
(); mat4.perspective(transform, fovRadians, aspectRatio, nearClip, farClip); return transform; } After converting the FOV angle, fovDegrees, from degrees to radians and computing the aspect ratio of the XRViewport specified by the viewport parameter, this function uses the glMatrix library's mat4.perspective
() function to compute the perspective matrix. The perspective matri...
...The position of the camera in space does not change, only the direction in which it's looking. And that direction does not change oth...
...ishing 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 a standard 4x4 matrix. To rotate the viewpoint defined by the matrix viewMatrix by panAngle radians: mat4.rotateY(viewMatrix, viewMatrix, panAngle); If panAngle is positive, this transform will pan the camera 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...
...And 8 more matches
XMLHttpRequest - Web APIs
ver text { fill: #0095DD; pointer-events: all;} Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML. If your communication needs to involve receiving event data or message data from a server, consider using server-sent events through the EventSource interface. For full-duplex communication, WebSockets may be a better choice. Constructor XMLHttpRequest
() The constructor initializes an XMLHttpRequest. It must be called before any other method calls. Properties This interface also inherits properties of XMLHttpRequestEventTarget and of EventTarget. XMLHttpRequest.onreadystatechange An EventHandler that is called whenever the readyState attribute changes. XMLHttpRequest.readyState Read only Returns an unsigned short, the state of the requ...
...instead. Event handlers onreadystatechange as a property of the XMLHttpRequest instance is supported in all browsers. Since then, a number of additional event handlers have been implemented in various browsers (onload, onerror, onprogress, etc.). See Using XMLHttpRequest. ...
...ed in all browsers. Since then, a number of additional event handlers have been implemented in various browsers (onload, onerror, onprogress, etc.). See Using XMLHttpRequest. More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard addEventListener
() APIs in addition to setting on* properties to a handler function. Methods XMLHttpRequest.abort
() Aborts the request if it has already been sent. ...
...And 8 more matches
Video player styling basics - Developer guides
red for implementing the button functionality. Play/Pause and Mute Now that the buttons actually look like buttons and have images that indicate what they do, some changes need to be made so that the "dual functionality" buttons (such as the play/pause button) are in the correct "state" and display the correct image. ...
....paused || video.ended) { playpause.setAttribute('data-state', 'play'); } else { playpause.setAttribute('data-state', 'pause'); } } // Mute button else if (type == 'mute') { mute.setAttribute('data-state', video.muted ? ...
... else { playpause.setAttribute('data-state', 'pause'); } } // Mute button else if (type == 'mute') { mute.setAttribute('data-state', video.muted ? ...
...And 8 more matches
Method definitions - JavaScript
er syntax for method definitions on objects initializers is introduced. It is a shorthand for a function assigned to the method's name. 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 obj = { get property
() {}, set property(value) {}, property( parameters... ) {}, *generator( parameters... ) {}, async property( parameters... ) {}, async* generator( parameters... ) {}, // with computed keys get [property]
() {}, set [property](value) {}, [property]( parameters... ) {}, *[generator]( parameters... ) {}, async [property]( parameters... ) {}, async* [generator]( parameters... ) ...
... // with computed keys get [property]
() {}, set [property](value) {}, [property]( parameters... ) {}, *[generator]( parameters... ) {}, async [property]( parameters... ) {}, async* [generator]( parameters... ) {}, }; Description The shorthand syntax is similar to the getter and setter syntax introduced in ECMAScript 2015. Given the following code: const obj = { foo: function
() { // ... }, bar: function
() { // ... } } You are now able to shorten this to: const obj = { foo
() { // ... }, bar
() { // ... } } Generator methods Generator methods can be defined using the shorthand syntax as well. When doing so: The asterisk (*) in the shorthand syntax must be before the generator property name. ...
...nst obj = { foo: function
() { // ... }, bar: function
() { // ... } } You are now able to shorten this to: const obj = { foo
() { // ... }, bar
() { // ... } } Generator methods Generator methods can be defined using the shorthand syntax as well. When doing so: The asterisk (*) in the shorthand syntax must be before the generator property name. (That is, * g
(){} will work, but g *
(){} will not.) Non-generator method definitions cannot contain the yield keyword. This means that legacy generator functions won't work either, and will throw a SyntaxError. Always use yield in conjunction with the asterisk (*). ...
...And 8 more matches
Strict mode - JavaScript
ioning to strict mode, if you want to change your code to work in the restricted variant of JavaScript. Invoking strict mode Strict mode applies to entire scripts or to individual functions. It doesn't apply to block statements enclosed in {} braces; attempting to apply it to such contexts does nothing. eval code, Function code, event handler attributes, strings passed to WindowTimers.setTimeout
(), and related functions are entire scripts, and invoking strict mode in them works as expected. Strict mode for scripts To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements. // Whole-script strict mode syntax 'use strict'; var v = "Hi! I'm a strict mode script!"; This syntax has a trap that has already bitten a major ...
...n 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 "I'm not strict."; } Strict mode for modules ECMAScript 2015 introduced JavaScript modules and therefore a 3rd way to enter strict mode. The entire contents of JavaScript modules are automatically in s...
...nested
() { return 'And so am I!'; } return "Hi! I'm a strict mode function! " + nested
(); } function notStrict
() { return "I'm not strict."; } Strict mode for modules ECMAScript 2015 introduced JavaScript modules and therefore a 3rd way to enter strict mode. The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it. function strict
() { // because this is a module, I'm strict by default } export default strict; Changes in strict mode Strict mode changes both syntax and runtime behavior. Changes generally fall into these categories: changes converting mistakes into errors (as syntax errors or at runtime), changes simplifying how the particular variable for a given use of a name is computed, changes simplifying eval and a...
...And 8 more matches
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
begin with. Request permission To show a notification, we have to request permission to do so first. Instead of showing the notification immediately though, best practice dictates that we should show the popup when the user requests it by clicking on a button: var button = document.getElementById("notifications"); button.addEventListener('click', function(e) { Notification.requestPermission
().then(function(result) { if(result === 'granted') { randomNotification
(); } }); }); This shows a popup using the operating system's own notifications service: When the user confirms to receive notifications, the app can then show them. The result of the user action can be default, granted or denied. The default option is chosen when the user won't make a choice,...
... respectively. When accepted, the permission works for both notifications and push. ...
...rks for both notifications and push. ...
...And 8 more matches
Caching compiled WebAssembly modules - WebAssembly
ny other type of cloneable object. This includes compiled wasm modules (WebAssembly.Module JavaScript objects). Setting up a caching library Because IndexedDB is a somewhat old-fashioned API, we wanted to provide a library function to speed up writing caching code, and make it work better along with today's more modern APIs. In our wasm-utils.js library script, you'll find instantiateCachedURL
() -- this function fetches the wasm module at url with a version of dbVersion, instantiates it with the given importObject, and returns a promise resolving to the finished wasm Instance. Additionally, it handles creating a database to cache the compiled wasm modules in, attempts to store new modules in the database, and retrieves previously cached modules from the database, saving you from having t...
...re new modules in the database, and retrieves previously cached modules from the database, saving you from having to download them again. Note: The entire site's wasm cache (not just the given URL) is versioned by the specified dbVersion passed into the function. If the wasm module code is updated, or its URL changes, you will need to update dbVersion. ...
... call to instantiateCachedURL
() will then clear out the entire cache, allowing you to avoid using out-of-date modules. The function starts off by defining some necessary constants: function instantiateCachedURL(dbVersion, url, importObject) { const dbName = 'wasm-cache'; const storeName = 'wasm-cache'; Setting up the database The first helper function contained inside instantiateCachedURL
() -- openDatabase
() -- creates an object store for storing wasm modules, and also handles clearing out the database if the dbVersion is updated; it returns a promise resolving to the new database. ...
...And 8 more matches
port - Archive of obsolete content
ing conversations between a content script and the main add-on code. Each end of the conversation has access to a port: the content script via the global self property, and the main add-on code via a worker object associated with the SDK module you've used to attach the content script, such as page-mod or page-worker. For an overview of content scripts, see the main article. port Methods emit
() The port.emit
() function sends a message from one side to the other. It may be called with any number of parameters, but is most likely to be called with a name for the message and an optional payload. The payload can be any value that is serializable to JSON. From the content script to the main add-on code: // content-script.js var myMessagePayload = "some data"; self.port.emit("myMessage",...
... message and an optional payload. The payload can be any value that is serializable to JSON. From the content script to the main add-on code: // content-script.js var myMessagePayload = "some data"; self.port.emit("myMessage", myMessagePayload); From the main add-on code to the content script: // main.js var myMessagePayload = "some data"; worker.port.emit("myMessage", myMessagePayload); on
() The port.on
() function registers a function as a listener for a particular message sent from the other side using port.emit
(). It takes two parameters: the name of the message and a function to handle it. In a content script, to listen for "myMessage" sent from the main add-on code: // content-script.js self.port.on("myMessage", function handleMyMessage(myMessagePayload) { // Handle the me...
... a content script, to listen for "myMessage" sent from the main add-on code: // content-script.js self.port.on("myMessage", function handleMyMessage(myMessagePayload) { // Handle the message }); In the main add-on code, to listen for "myMessage" sent from a a content script: // main.js worker.port.on("myMessage", function handleMyMessage(myMessagePayload) { // Handle the message }); once
() Often you'll want to receive a message just once, then stop listening. The port object offers a shortcut to do this: the once
() method. This example rewrites the content script in the port.removeListener
() example so that it uses once
(): // content-script.js function getFirstParagraph
() { var paras = document.getElementsByTagName('p'); console.log(paras[0].textContent); } self.port.once(...
...And 7 more matches
Canvas code snippets - Archive of obsolete content
roperties. ...
...lGradient', 'getImageData', 'putImageData' ]; var props = ['canvas', 'fillStyle', 'font', 'globalAlpha', 'globalCompositeOperation', 'lineCap', 'lineJoin', 'lineWidth', 'miterLimit', 'shadowOffsetX', 'shadowOffsetY', 'shadowBlur', 'shadowColor', 'strokeStyle', 'textAlign', 'textBaseline']; for (let m of methods) { let method = m; Canvas2DContext.prototype[method] = function
() { this.ctx[method].apply(this.ctx, arguments); return this; }; } for (let m of getterMethods) { let method = m; Canvas2DContext.prototype[method] = function
() { return this.ctx[method].apply(this.ctx, arguments); }; } for (let p of props) { let prop = p; Canvas2DContext.prototype[prop] = function(value) { if (value === undefined) r...
... Saving a canvas image to a file The following function accepts a canvas object and a destination file path string. The canvas is converted to a PNG file and saved to the specified location. The function returns a promise which resolves when the file has been comp...
...And 7 more matches
Finding window handles - Archive of obsolete content
ndWindow( * __in_ HWND hWnd * ); */ var SetForegroundWindow = user32.declare('SetForegroundWindow', ctypes.winapi_abi, ctypes.bool, // return BOOL ctypes.voidptr_t // HWND ); var hwnd = ctypes.voidptr_t(ctypes.UInt64(hwndString)); var rez_SetForegroundWindow = SetForegroundWindow(hwnd); console.log('rez_SetForegroundWindow:', rez_SetForegroundWindow, rez_SetForegroundWindow.toString
()); user32.close
(); Mac OS X Objective-C Components.utils.import('resource://gre/modules/Services.jsm'); var browserWindow = Services.wm.getMostRecentWindow('navigator:browser'); if (!browserWindow) { throw new Error('No browser window found'); } var baseWindow = browserWindow.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) ...
...The string is made into an actual GdkWindow* like this: var GdkWindow = ctypes.StructType('GdkWindow'); var GDKWindowPtrString = baseWindow.nativeHandle; var GdkWinPtr = GdkWindow.ptr(ctypes.UInt64(GDKWindowPtrString)); Working with GdkWindow* GdkWindow* to XID ...
...The string is made into an actual GdkWindow* like this: var GdkWindow = ctypes.StructType('GdkWindow'); var GDKWindowPtrString = baseWindow.nativeHandle; var GdkWinPtr = GdkWindow.ptr(ctypes.UInt64(GDKWindowPtrString)); Working with GdkWindow* GdkWindow* to XID var GdkWindow =...
...And 7 more matches
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
included incorrectly: make -C directory/that/failed OS_CPPFLAGS=-showIncludes The frozen string API is similar but not identical to the nonfrozen string API. ...
...hat/failed OS_CPPFLAGS=-showIncludes The frozen string API is similar but not identical to the nonfrozen string API. ...
...milar but not identical to the nonfrozen string API. The frozen string API does not have (or need) nsXPIDLString: - nsXPIDLString value; + nsString value; ptr->GetterMethod(getter_Copies(value)); - const PRUnichar *strvalue = value; + // nsString doesn't cast directly to PRUnichar*, use .get
()+ const PRUnichar *strvalue = value.get
(); The frozen string API doesn't accept a length for .Truncate
(). ...
...And 7 more matches
MMgc - Archive of obsolete content
phase. If you know for certain that the objects will not contain GC pointers, leave this flag off; it will make the mark phase faster by excluding your object. kFinalize and kRCObject are used internally by the GC; you should not need to set them in your user code. GC::GetGC Given the pointer to any GCObject, it is possible to get a pointer to the GC object that allocated it. ...
... class MyUnmanagedObject : public MMgc::GCRoot { MyObject *object; }; Any pointers to a GCObject from managed memory require a DWB write barrier macro. ...
... there are no other references, and you want to help the GC along: // Optimization: Get rid of myObject now, because we know there are no other // references, so no need to wait for GC to clean it up. delete myObject; The destructor for a GCObject will never be called (unless the object is also a descendant of GCFinalizedObject... see below.) class MyObject : public MMgc::GCObject { ~MyObject
() { assert(!"this will never be hit (unless we also descend from GCFinalizedObject)"); } }; GCObject::GetWeakRef GCWeakRef *GetWeakRef
() const; The GetWeakRef method returns a weak reference to the object. Normally, a pointer to the object is considered a hard reference -- any such reference will prevent the object from being destroyed. Sometimes, it is desirable to hold a pointer to a GCObject, ...
...And 7 more matches
Learn XPI Installer Scripting by Example - Archive of obsolete content
install files in system folders and other areas. Overview of the Install Script XPI install scripts are written in JavaScript using XPInstall Engine syntax defined in the XPInstall API Reference. ...
...tem folders and other areas. Overview of the Install Script XPI install scripts are written in JavaScript using XPInstall Engine syntax defined in the XPInstall API Reference. ...
...n in JavaScript using XPInstall Engine syntax defined in the XPInstall API Reference. Most installation scripts, including the one discussed here, take the following basic form (in pseudo-code and with links to the sections in which these installation steps are documented): initInstall
(); if (verify_space
()) { err = add_dirs_and_files; register_files; if (err==SUCCESS) { performInstall
() }; else { cancelInstall
() }; } As you can see in the code listing, the verification process at the top is on lines 1 to 18; the file addition process, here part of the main installation block, is on lines 24 to 41; the registration part of the main installation block is on lines 42-58; and the execution at the end of the main block is on lines 59 to 71. If you choose not to register the inst...
...And 7 more matches
Document Object Model - Archive of obsolete content
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 as a property of the window object. For example, the following code will display the text 'Message' in an alert twice. ...
...,"_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 as a property of the window object. For example, the following code will display the text 'Message' in an alert twice. function getText
(){ return "Message"; } alert(getText
()); alert(window.getText
()); Thus, if you want to access variables or call a function declared in a script used by another window, you just need to access it using the other window's window object. For example, if we combined the last two examples into a single file, we might want to call the getText
() function from within the other window (for example, the test.xul window). To do this, we can do...
...ant to access variables or call a function declared in a script used by another window, you just need to access it using the other window's window object. For example, if we combined the last two examples into a single file, we might want to call the getText
() function from within the other window (for example, the test.xul window). To do this, we can do the following: alert(window.opener.getText
()); Each window has an opener property which holds the window object that opened this one. ...
...And 7 more matches
Tree Selection - Archive of obsolete content
u add the seltype attribute to the tree, set to the value single, the user may only select one row at a time. Otherwise, the user may select multiple rows, which will not necessarily be contiguous. The tree provides a number of functions which can be used to determine whether an item is selected. Handling the Select Event First, let's see how we can determine when an item is selected. The onselect
() event handler may be added to the tree element. When the user selects an item from the tree, the event handler is called. The user may also change the selection by using the cursor keys. If the user holds down the cursor key to rapidly scroll through the items, the event handler is not called until the user stops. This results in a performance improvement. This also means that the highlight will ...
... is called. The user may also change the selection by using the cursor keys. If the user holds down the cursor key to rapidly scroll through the items, the event handler is not called until the user stops. This results in a performance improvement. This also means that the highlight will appear on several items even though the select event is never fired for those items. The syntax of the onselect
() event handler is shown below. <tree id="treeset" onselect="alert('You selected something!');"> Tree Indices The tree has a property currentIndex, which can be used to get the currently selected item, where the first row is 0. Child items are included in the count just after their parents. This means that if there are 3 top-level items and each has two child items, there will be a total of 9 item...
...ree. From the tree, you can get the selection using the tree's view property and then retrieve the view's selection property. You can use the methods of the selection object to retrieve the set of selected items or modify the selection. Because the selected items in a multiple selection tree are not necessarily contiguous, you can retrieve each block of contigous selections using the getRangeCount
() and getRangeAt
() functions. The first function returns the number of selection ranges there are. If only one value is selected, this value will be 1. You would then write a loop for the number of ranges, calling getRangeAt
() to get the actual indices of the start and end of the range. The getRangeAt
() function takes three arguments. The first is the range index. The second is an object which...
...And 7 more matches
XUL Questions and Answers - Archive of obsolete content
</window> List box handlers can only check for listitems not listcells. If user wants checkbox support for multicolumn lists, then they will have to implement one. Are XUL attributes integers? XUL attributes such as left="100" or top="200", as well as corresponding properties, look as if they're integers but they are actually handled as strings. To convert them to integers use the parseInt
() JavaScript function. While the attributes are always strings per the DOM specification, the properties will eventually be fixed to return the value with the correct type. Using the "icon" attribute on a button From XULPlanet.com reference: This attribute should be used to set the usage for common buttons. Some platforms display these buttons with a small icon indicating their usage. This ...
...ranch interface. Can a XUL template be used for RSS? You should be able to use a XUL template to display feeds, although you may have to write the feed data to an RDF datasource first. Specifying window.onload function To specify a function to run when the window is loaded,add the following code between the script tags in the XUL file: window.addEventListener("load", function(e) { startup
(); }, false); Similarly, for onunload use the code: window.addEventListener("unload", function(e) { shutdown
(); }, false); Is there an event which is called when the Firefox browser is initialized? An event is initiated when the application starts up and when the profile is changed. For more information please look at the following link: nsExtensionManager.js Is nsIVariant fully supported ...
...nsIVariant. ...
...And 7 more matches
NPN_GetURL - Archive of obsolete content
link in a new blank unnamed window. Safest target, even though, when used with a mailto or news URL, this creates an extra blank the browser instance. _self or _current: Load the link into the same window the plug-in instance occupies. Not recommended; if target refers to the window or frame containing the instance, the instance is destroyed and the plug-in may be unloaded. Use with NPN_GetURL
() only if you want to terminate the plug-in. _parent: Load the link into the immediate <frameset> parent of the plug-in instance's document. If the plug-in instance's document has no parent, the default is _self. _top: Load the link into the plug-in instance window. The default is _self, if the plug-in instance's document is already at the top. Use for breaking out of a deep frame nesting. ...
...and delivers the data to the current instance regardless of the MIME type of the URL. In general, if a URL works in the location box of the browser, it works here, except for the _self target. Returns If successful, the function returns NPERR_NO_ERROR. If unsuccessful, the plug-in is not loaded and the function returns an error code. For possible values, see Error codes. Description NPN_GetURL
() is used to load a URL into the current window or another target or stream. Plug-ins can use this capability to provide hyperlinks to other documents or to retrieve data from anywhere on the network. This is especially useful for enabling an existing application to operate on the web. For HTTP URLs, the browser resolves this method as the HTTP server method GET, which requests URL objects. Use NPN...
...oad a URL into the current window or another target or stream. Plug-ins can use this capability to provide hyperlinks to other documents or to retrieve data from anywhere on the network. This is especially useful for enabling an existing application to operate on the web. For HTTP URLs, the browser resolves this method as the HTTP server method GET, which requests URL objects. Use NPN_GetURLNotify
() instead of NPN_GetURL
() in these cases: To request a stream and receive notification of the result. If the buffer contains header information (even a blank line). Make sure that the target matches the URL type sent to it. For example, a null target does not make sense for some URL types (such as mailto). The following recommendations about target choice apply to other methods that handle URLs...
...And 7 more matches
LiveConnect Overview - Archive of obsolete content
lang.String("Hello world"); In the previous example, the variable myString is a JavaObject because it holds an instance of the Java object String. As a JavaObject, myString has access to the public instance methods of java.lang.String and its superclass, java.lang.Object. These Java methods are available in JavaScript as methods of the JavaObject, and you can call them as follows: myString.length
(); // returns 11 Static members can be called directly on the JavaClass object. alert(java.lang.Integer.MAX_VALUE); //alerts 2147483647 The Packages Object If a Java class is not part of the java, sun, or netscape packages, you access it with the Packages object. For example, suppose the Redwood corporation uses a Java package called redwood to contain various Java classes that it implements. To ...
...s Object If a Java class is not part of the java, sun, or netscape packages, you access it with the Packages object. For example, suppose the Redwood corporation uses a Java package called redwood to contain various Java classes that it implements. To create an instance of the HelloWorld class in redwood, you access the constructor of the class as follows: var red = new Packages.redwood.HelloWorld
(); You can also access classes in the default package (that is, classes that don't explicitly name a package). For example, if the HelloWorld class is directly in the CLASSPATH and not in a package, you can access it as follows: var red = new Packages.HelloWorld
(); The LiveConnect java, sun, and netscape objects provide shortcuts for commonly used Java packages. For example, you can use the follo...
... reference such as java.lang.String is a JavaClass object. Most of the time, you don't have to worry about the JavaPackage and JavaClass objects--you just work with Java packages and classes, and LiveConnect creates these objects transparently. There are cases where LiveConnect will fail to load a class, and you will need to manually load it like this: var Widgetry = java.lang.Thread.currentThread
().getContextClassLoader
().loadClass("org.mywidgets.Widgetry"); In JavaScript 1.3 and earlier, JavaClass objects are not automatically converted to instances of java.lang.Class when you pass them as parameters to Java methods--you must create a wrapper around an instance of java.lang.Class. In the following example, the forName method creates a wrapper object theClass, which is then passed to the n...
...And 7 more matches
Old Proxy API - Archive of obsolete content
fined to indicate that no property with name exists in the emulated object. Object.getPropertyDescriptor(proxy, name) getPropertyDescriptor: function(name) -> PropertyDescriptor | undefined This function doesn't exist in ECMAScript 5. Like getOwnPropertyDescriptor, but should also search the prototype chain. Object.getOwnPropertyNames(proxy) getOwnPropertyNames: function
() -> Strings Array Return an array of all own (non-inherited) property names of the emulated object. Object.getPropertyNames(proxy) getPropertyNames: function
() -> Strings Array This function doesn't exist in ECMAScript 5. Like getOwnPropertyNames, but should also return non-overridden inherited properties. Object.defineProperty(proxy,name,pd) defineProperty: function(...
...ertyDescriptor. The return value of this method is ignored. delete proxy.name delete: function(name) -> boolean Delete the named property from the proxy. The boolean return value of this method should indicate whether or not the name property was successfully deleted. ...
...he boolean return value of this method should indicate whether or not the name property was successfully deleted. Object.freeze(proxy) Object.seal(proxy) Object.preventExtensions(proxy) fix: function
() -> PropertyDescriptor map (indexed on property names) | undefined Should return an object that maps property names to property descriptors. After a call to fix
(), the proxy becomes a regular (non-proxy) object with the properties listed in the return value. The handler is no longer used. Moreover, the respective method (freeze
(), seal
(), or preventExtension
()) is immediately called on the fixed object. Note: the fixed object has the same object identity as the proxy object. If fix
() returns undefined, the call throws a TypeError exception. ...
...And 7 more matches
Common causes of memory leaks in extensions - Extensions
r-prone code patterns. For some examples found in real-world add-ons, see bug 712733, bug 725875, and bug 727552. To avoid these issues, references to DOM nodes in foreign document should instead be stored in an object which is specific to that document, and cleaned up when the document is unloaded, or stored as weak references. ...
... For some examples found in real-world add-ons, see bug 712733, bug 725875, and bug 727552. To avoid these issues, references to DOM nodes in foreign document should instead be stored in an object which is specific to that document, and cleaned up when the document is unloaded, or stored as weak references. ...
... setInterval/setTimeout Using window.setInterval
() or window.setTimeout
() can be problematic, too, when it comes to zombie compartments. Consider the following example code that could be part of your browser.xul overlay: gBrowser.addEventListener("DOMContentLoaded", function(evt) { var contentDoc = evt.originalTarget; var i = 0; // Refresh the title once each second setInterval(function
() { contentDoc.title = ++i; }, 1000); }, false); One would normally expect that the interval (or timer) would be destroyed as soon as the document unloads, in the same way that event listeners are automatically destroyed. However, while this is still true, the window.setInterval
() in the example originates from the outer chrome window (browser.xul) and not from the content window. Hence the...
...And 7 more matches
Collision detection - Game development
A collision detection function To kick this all off we want to create a collision detection function that will loop through all the bricks and compare every single brick's position with the ball's coordinates as each frame is drawn. For better readability of the code we will define the b variable for storing the brick object in every loop of the collision detection: function collisionDetection
() { for(var c=0; c<brickColumnCount; c++) { for(var r=0; r<brickRowCount; r++) { var b = bricks[c][r]; // calculations } } } If the center of the ball is inside the coordinates of one of our bricks, we'll change the direction of the ball. For the center of the ball to be inside the brick, all four of the following statements need to be true: The x...
...ts need to be true: The x position of the ball is greater than the x position of the brick. The x position of the ball is less than the x position of the brick plus its width. The y position of the ball is greater than the y position of the brick. The y position of the ball is less than the y position of the brick plus its height. Let's write that down in code: function collisionDetection
() { for(var c=0; c<brickColumnCount; c++) { for(var r=0; r<brickRowCount; r++) { var b = bricks[c][r]; if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) { dy = -dy; } } } } Add the above block to your code, below the keyUpHandler
() function. Making the bricks disappear after they are hit The above code ...
...tialize the bricks, let's add a status property to each brick object. ...
...And 7 more matches
Client-side form validation - Learn web development
therwise. valueMissing: Returns true if the element has a required attribute, but no value, or false otherwise. If true, the element matches the :invalid CSS pseudo-class. willValidate: Returns true if the element will be validated when the form is submitted; false otherwise. The Constraint Validation API also makes the following methods available on the above elements. checkValidity
(): Returns true if the element's value has no validity problems; false otherwise. If the element is invalid, this method also fires an invalid event on the element. setCustomValidity(message): Adds a custom error message to the element; if you set a custom error message, the element is considered to be invalid, and the specified error is displayed. This lets you use JavaScript code to establish a ...
...} }); Here we store a reference to the email input, then add an event listener to it that runs the contained code each time the value inside the input is changed. Inside the contained code, we check whether the email input's validity.typeMismatch property returns true, meaning that the contained value doesn't match the pattern for a well-formed email address. If so, we call the setCustomValidity
() method with a custom message. This renders the input invalid, so that when you try to submit the form, submission fails and the custom error message is displayed. If the validity.typeMismatch property returns false, we call the setCustomValidity
() method an empty string. This renders the input valid, so the form will submit. You can try it out below: Note: You can find this example live on ...
...f the // form fields are valid. if (email.validity.valid) { // In case there is an error message visible, if the field // is valid, we remove the error message. ...
...And 7 more matches
Images in HTML - Learn web development
bel { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode
() { output.innerHTML = textarea.value; } reset.addEventListener('click', function
() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode
(); }); solution.addEventListener('click', function
() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; }...
...area.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode
(); }); solution.addEventListener('click', function
() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Show solution'; } updateCode
(); }); var htmlSolution = '<img src="https://udn.realityripple.com/samples/ec/5a13bd14f6.jpg"\n alt="The head and torso of a dinosaur skeleton; it has a large head with long sharp teeth"\n width="200"\n height="171"\n title="A T-Rex on display in the Manchester University Museum">'; var solutionEntry = htmlSolution; textarea.addEventListener('input', updateCode); window.addEventListener('load', u...
...idth="200"\n height="171"\n title="A T-Rex on display in the Manchester University Museum">'; var solutionEntry = htmlSolution; textarea.addEventListener('input', updateCode); window.addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault
(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur
(); } }; function insertAtCaret(text) { var scrollPos = textarea.scrollTop; var caretPos = textarea.selectionStart; var front = (textarea.value).substring(0, caretPos); var back = (textarea.value).substring(textarea.selectionEnd, textarea.value.length); textarea.value = front + text + back; caretPos = caretP...
...And 7 more matches
What is JavaScript? - Learn web development
So what can it really do? The core client-side JavaScript language...
...is course. JavaScript running order When the browser encounters a block of JavaScript, it generally runs it in order, from top to bottom. This means that you need to be careful what order you put things in. ...
...e block of JavaScript we saw in our first example: const para = document.querySelector('p'); para.addEventListener('click', updateName); function updateName
() { let name = prompt('Enter a new name'); para.textContent = 'Player 1: ' + name; } Here we are selecting a text paragraph (line 1), then attaching an event listener to it (line 3) so that when the paragraph is clicked, the updateName
() code block (lines 5-8) is run. The updateName
() code block (these types of reusable code blocks are called "functions") asks the user for a new name, and then inserts that name into the paragraph to update the display. If you swapped the order of the first two lines of code, it would no longer work -- instead, you'd get an error returned in the browser developer console -- TypeError: para is und...
...And 7 more matches
Working with JSON - Learn web development
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 the new keyword. Add the following below your last line: let request = new XMLHttpRequest
(); Now we need to open the request using the open
() method. Add the following line: request.open('GET', requestURL); This takes at least two parameters -- there are other optional parameters available. We only need the two mandatory ones for this simple example: The HTTP method to use when making the network request. In this case GET is fine, as we are just retrieving some simple dat...
...s we are just retrieving some simple data. The URL to make the request to -- this is the URL of the JSON file that we stored earlier. Next, add the following two lines -- here we are setting the responseType to JSON, so that XHR knows that the server will be returning JSON, and that this should be converted behind the scenes into a JavaScript object. ...
... make the request to -- this is the URL of the JSON file that we stored earlier. Next, add the following two lines -- here we are setting the responseType to JSON, so that XHR knows that the server will be returning JSON, and that this should be converted behind the scenes into a JavaScript object. ...
...And 7 more matches
Displaying Places information using views
nlyBookmarked=1&queryType=1"> <treecols> <treecol id="title" label="My Bookmarks" flex="1" primary="true" /> </treecols> <treechildren /> </tree> The next example does the same as the last but uses JavaScript to set the tree's place attribute: var histServ = Cc["@mozilla.org/browser/nav-history-service;1"]. getService(Ci.nsINavHistoryService); var query = histServ.getNewQuery
(); query.searchTerms = "mozilla"; query.onlyBookmarked = true; var opts = histServ.getNewQueryOptions
(); opts.queryType = opts.QUERY_TYPE_BOOKMARKS; var uri = histServ.queriesToQueryString([query], 1, opts); var tree = document.getElementById("mytree"); tree.place = uri; These two examples use the built-in tree view, but the point is to demonstrate the use of the place attribute and property. In...
... 3 and 4 apply to this object. var treeViewView = treeView.view; Convenience methods Because the built-in tree view is both widely used and complex, several convenience methods are implemented directly on it to make common tasks easier. Warning: Until bug 476952 is fixed, you may experience problems using some of these methods in conjunction with the place attribute and property. applyFilter
() Loads a new empty query with particular search terms and folders. void applyFilter( string filterString, array folderRestrict ); Parameters filterString The new query's searchTerms property will be set to this string. folderRestrict The setFolders function of the new query will be called on this array of folder IDs. Optional. load
() Sets the queries that the view displays. This m...
...ry will be called on this array of folder IDs. Optional. load
() Sets the queries that the view displays. This method may be used as an alternative to setting the tree's place property as described above. void load( array queries, nsINavHistoryQueryOptions options ); Parameters queries An array of nsINavHistoryQuery objects. options An nsINavHistoryQueryOptions object. selectItems
() Selects the first node in the tree that matches each given item ID. It will open any parent nodes that it needs to in order to show the selected items. void selectItems( array aIDs, array aOpenContainers ); Parameters aIDs An array of item IDs. ...
...And 7 more matches
Performance
lized once, which makes them suitable for stateless callbacks. But care must be taken to not leak references to the frame script global when it is passed into a JSM. Alternatively the frame's unload event or weak maps can be used to ensure that frames can be cleaned up when their respective tab is closed. ...
...llbacks. But care must be taken to not leak references to the frame script global when it is passed into a JSM. Alternatively the frame's unload event or weak maps can be used to ensure that frames can be cleaned up when their respective tab is closed. ...
...ed into a JSM. Alternatively the frame's unload event or weak maps can be used to ensure that frames can be cleaned up when their respective tab is closed. Store heavyweight state once per process BAD: // addon.js var main = new MyAddonService
(); main.onChange(stateChange); function stateChange
() { Services.mm.broadcastAsyncMessage("my-addon:update-configuration", {newConfig: main.serialize
()}) } // framescript.js var mainCopy; function onUpdate(message) { mainCopy = MyAddonService.deserialize(message.data.newConfig); } addMessageListener("my-addon:update-configuration", onUpdate) // mainCopy used by other functions The main issue here is that a separate object is kept for each tab. Not only does that increase memory footprint but the deserialization also has to be executed...
...And 7 more matches
How to implement a custom autocomplete search component
lt = searchResult; this._defaultIndex = defaultIndex; this._errorDescription = errorDescription; this._results = results; this._comments = comments; } ProviderAutoCompleteResult.prototype = { _searchString: "", _searchResult: 0, _defaultIndex: 0, _errorDescription: "", _results: [], _comments: [], /** * @return {string} the original search string */ get searchString
() { return this._searchString; }, /** * @return {number} the result code of this result object, either: * RESULT_IGNORED (invalid searchString) * RESULT_FAILURE (failure) * RESULT_NOMATCH (no matches found) * RESULT_SUCCESS (matches found) */ get searchResult
() { return this._searchResult; }, /** * @return {number} the index of the default it...
...t code of this result object, either: * RESULT_IGNORED (invalid searchString) * RESULT_FAILURE (failure) * RESULT_NOMATCH (no matches found) * RESULT_SUCCESS (matches found) */ get searchResult
() { return this._searchResult; }, /** * @return {number} the index of the default item that should be entered if * none is selected */ get defaultIndex
() { return this._defaultIndex; }, /** * @return {string} description of the cause of a search failure */ get errorDescription
() { return this._errorDescription; }, /** * @return {number} the number of matches */ get matchCount
() { return this._results.length; }, /** * @return {string} the value of the result at the given index */ getValueAt: functi...
... */ removeValueAt: function(index, removeFromDb) { this._results.splice(index, 1); if (this._comments) this._comments.splice(index, 1); }, getLabelAt: function(index) { return this._results[index]; }, QueryInterface: XPCOMUtils.generateQI([ Ci.nsIAutoCompleteResult ]) }; /** * @constructor * * @implements {nsIAutoCompleteSearch} */ function ProviderAutoCompleteSearch
() { } ProviderAutoCompleteSearch.prototype = { classID: CLASS_ID, classDescription : CLASS_NAME, contractID : CONTRACT_ID, /** * Searches for a given string and notifies a listener (either synchronously * or asynchronously) of the result * * @param searchString the string to search for * @param searchParam an extra parameter * @param previousResult a previous result to ...
...And 7 more matches
PromiseWorker.jsm
JavaScript files imported into the worker scope and main thread scope which allows posting to the worker and receiving in the form of a promise. 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. The PromiseWorker object is used to deliver all of the OS.File functionality to the main thread. ...
...rs, 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 PromiseWorker.Abs...
... 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). ...
...And 7 more matches
Task.jsm
cript's yield operator. To use it, you first need to import the code module into your JavaScript scope: Components.utils.import("resource://gre/modules/Task.jsm"); Introduction For an introduction to tasks, you may start from the Task.js documentation, keeping in mind that only the core subset is implemented in this module. Tasks are built upon generator functions and promises. The Task.spawn
() function takes a generator function and starts running it as a task. Every time the task yields a promise, it waits until the promise is resolved. Task.spawn
() returns a promise that is resolved when the task completes successfully, or is rejected if an exception occurs. You can use the yield operator inside the generator function to wait on a promise, spawn another task, or propagate a value: ...
..., spawn another task, or propagate a value: let resolutionValue = yield (promise/generator/iterator/value); If you specify a promise, the yield operator returns its resolution value as soon as the promise is resolved. If the promise is rejected, its rejection reason is thrown as an exception. If you specify a generator function or the iterator returned by a generator function, then Task.spawn
() is implicitly called, and the yield operator works on the returned promise. This reduces the syntax overhead of calling Task.spawn
() explicitly when you want to recurse into other task functions. If you specify a function that is not a generator, it is called with no arguments, and the yield operator returns the return value of the function. This comes in handy when iterating over function lists...
...xactly what you specified. Method overview Function async(aTask); Promise spawn(aTask); Properties Attribute Type Description Result Read only Constructor Constructs a special exception that, when thrown inside a legacy generator function, allows the associated task to be resolved with a specific value. Example: Task.spawn( function
() { yield ... ; throw new Task.Result("Value"); } Note: If you want to exit early from a generator function, without returning a value for the task, you can just use the return statement without any arguments. Note: If you want to return a result from a non-legacy generator function, don't use this. Return the value instead: Task.spawn( function*
() { yield ... ; return "Value"; } ...
...And 7 more matches
JSAPI User Guide
, global); // Populate the global object with the standard globals, like Object and // Array. if (!JS_InitStandardClasses(cx, global)) return 1; // Your application code here. This may include JSAPI calls to create your // own custom JS objects and run scripts. return 0; } int main(int argc, const char *argv[]) { // Initialize the JS engine. if (!JS_Init
()) return 1; // Create a JS runtime. JSRuntime *rt = JS_NewRuntime(8L * 1024L * 1024L); if (!rt) return 1; // Create a context. JSContext *cx = JS_NewContext(rt, 8192); if (!cx) return 1; JS_SetErrorReporter(rt, reportError); int status = run(cx); // Shut everything down. JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDo...
... return 1; // Create a JS runtime. JSRuntime *rt = JS_NewRuntime(8L * 1024L * 1024L); if (!rt) return 1; // Create a context. JSContext *cx = JS_NewContext(rt, 8192); if (!cx) return 1; JS_SetErrorReporter(rt, reportError); int status = run(cx); // Shut everything down. JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown
(); return status; } Each JSNative has the same signature, regardless of what arguments it expects to receive from JavaScript. The JavaScript arguments to the function are given in argc and vp. argc tells how many actual arguments the caller passed, and JS_ARGV(cx, vp) returns an array of those arguments. The arguments do not have native C++ types like int and float; rather, they are jsvals,...
...r worse). In the case of JS::Value, the JavaScript garbage collector recycles objects, strings, and numbers that don't appear to be in use, and a JS::Value by itself does not protect its referent from the garbage collector. See Garbage collection below for crucial information on how to use JS::Values safely. JS::Value includes member functions to test the JavaScript data type. These are isObject
(), isNumber
(), isInt32
(), isDouble
(), isString
(), isBoolean
(), isNull
(), and isUndefined
(). If a JS::Value contains a JSObject, double, or JSString, you can cast it to its underlying data type using the toObject
(), toDouble
(), and toString
() member functions, respectively. This is useful in some cases where your application or a JSAPI function requires a variable or argument of a specific data typ...
...And 7 more matches
JS::PersistentRooted
ber of JS::PersistentRooted<T>, typed with T. Method Description void init(JSContext* cx) Initialize with optional initial value (if not provided, it will be initialized with the initial value of the type). Added in SpiderMonkey 38 void init(JSContext* cx, T initial) void init(JSRuntime* rt) void init(JSRuntime* rt, T initial) void reset
() Reset the value to initial value of the type. Added in SpiderMonkey 38 T& get
() Returns ptr. const T& get
() const operator const T&
() const const T& operator->
() const T* address
() Returns a pointer to ptr. const T* address
() const PersistentRooted<T>& operator=(const T& p) Sets the value of ptr. PersistentRooted<...
...ots can be used in heap-allocated data structures, so they are not associated with any particular JSContext or stack. They are registered with the JSRuntime itself, without locking, so they require a full JSContext to be initialized, not one of its more restricted superclasses. Initialization may take place on construction, or in two phases if the no-argument constructor is called followed by init
(). Note that you must not use an PersistentRooted in an object owned by a JS object: Whenever one object whose lifetime is decided by the GC refers to another such object, that edge must be traced only if the owning JS object is traced. This applies not only to JS objects (which obviously are managed by the GC) but also to C++ objects owned by JS objects. If you put a PersistentRooted in such a ...
...ng Heap<T> or TenuredHeap<T> members to make sure their referents get marked when the object itself is marked. JS::PersistentRooted<T> may be automatically coerced to a JS::Handle<T> and JS::MutableHandle<T>. Before SpiderMonkey 38, PersistentRooted<T> itself cannot be a global variable, but from SpiderMonkey38, it can be declared as a global variable, and initialized later with init
() method (bug 1107639). There are typedefs available for the main types: namespace JS { typedef PersistentRooted<JSFunction*> PersistentRootedFunction; typedef PersistentRooted<jsid> PersistentRootedId; typedef PersistentRooted<JSObject*> PersistentRootedObject; typedef PersistentRooted<JSScript*> PersistentRootedScript; typedef PersistentRooted<JSString*> PersistentRootedString; typ...
...And 7 more matches
JS_GetFunctionId
e same as returned by JS_GetFunctionId if the function explicitly has a name listed in the source, or if not it is an intelligently guessed name for the function based on its context in the source. If no smart name could be guessed for the function, then NULL is returned. The returned string is guaranteed to live as long as fun, so the application often does not need to root the string. ...
...unction explicitly has a name listed in the source, or if not it is an intelligently guessed name for the function based on its context in the source. If no smart name could be guessed for the function, then NULL is returned. The returned string is guaranteed to live as long as fun, so the application often does not need to root the string. ...
...rce, or if not it is an intelligently guessed name for the function based on its context in the source. If no smart name could be guessed for the function, then NULL is returned. The returned string is guaranteed to live as long as fun, so the application often does not need to root the string. ...
...And 7 more matches
Avoiding leaks in JavaScript XPCOM components
unction 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 example, in which there are two pairs of function objects, and each pair has an instance of the private_data variable: // This function returns an array containing two functions. ...
... consider the following example, in which there are two pairs of function objects, and each pair has an instance of the private_data variable: // This function returns an array containing two functions. function function_array
() { // Once this function is done running, this variable is still // accessible to the functions created here. ...
...ple, in which there are two pairs of function objects, and each pair has an instance of the private_data variable: // This function returns an array containing two functions. function function_array
() { // Once this function is done running, this variable is still // accessible to the functions created here. ...
...And 7 more matches
An Overview of XPCOM
ontract. Interfaces and Encapsulation Between component boundaries, abstraction is crucial for software maintainability and reusability. Consider, for example, a class that isn't well encapsulated. Using a freely available public initialization method, as the example below suggests, can cause problems. SomeClass Class Initialization class SomeClass { public: // Constructor SomeClass
(); // Virtual Destructor virtual ~SomeClass
(); // init method void Init
(); void DoSomethingUseful
(); }; For this system to work properly, the client programmer must pay close attention to whatever rules the component programmer has established. This is the contractual agreement of this unencapsulated class: a set of rules that define when each method can be called and what ...
...ethingUseful
(); }; For this system to work properly, the client programmer must pay close attention to whatever rules the component programmer has established. This is the contractual agreement of this unencapsulated class: a set of rules that define when each method can be called and what it is expected to do. One rule might specify that DoSomethingUseful may only be called after a call to Init
(). The DoSomethingUseful method may do some kind of checking to ensure that the condition - that Init has been called - has been satisfied. In addition to writing well-commented code that tells the client developer the rules about Init
(), the developer can take a couple steps to make this contract even clearer. First, the construction of an object can be encapsulated, and a virtual class provided ...
...n and initialization can be completely hidden from clients of the class. In this "semi-encapsulated" situation, the only part of the class that is exposed is a well-defined list of callable methods (i.e., the interface). Once the class is encapsulated, the only interface the client will see is this: Encapsulation of SomeInterface class SomeInterface { public: virtual void DoSomethingUseful
() = 0; }; The implementation can then derive from this class and implement the virtual method. Clients of this code can then use a factory design pattern to create the object (see Factories) and further encapsulate the implementation. In XPCOM, clients are shielded from the inner workings of components in this way and rely on the interface to provide access to the needed functionality. The nsISu...
...And 7 more matches
Components.Constructor
Summary Creates a JavaScript function which can be used to create or construct new instances of XPCOM components. Syntax var func = [ new ] Components.Constructor(contractID [, interfaceName [, initializer ] ]); Parameters contractID A string containing the contract ID of the component interfaceName If given, nsISupports.QueryInterface
() will be called on each newly-created instance with the interface named by this string initializer If given, a string containing the name of a function which will be called on the newly-created instance, using the arguments provided to the created function when called Description Components.Constructor
() is a handy shortcut for creating instances of XPCOM components. It eliminates the clutter of typing Components.classes, Components.in...
... for creating instances of XPCOM components. It eliminates the clutter of typing Components.classes, Components.interfaces, createInstance, and so on every time you wish to create an instance. It also gives creation of XPCOM objects more JavaScript-like syntax. Another important benefit is that it precomputes some of the computation it does, so using a function returned from Components.Constructor
() to create XPCOM objects is faster than creating the object from base principles, as demonstrated below. (This benefit is also partly a result of having to travel through the layer between the JavaScript engine and XPCOM fewer times.) The behavior of functions returned by Components.Constructor
() varies depending upon the arguments given to Components.Constructor
() when called. If only one argume...
...ewer times.) The behavior of functions returned by Components.Constructor
() varies depending upon the arguments given to Components.Constructor
() when called. If only one argument is given, that argument is the contract ID of the XPCOM component to create. The component is then returned immediately, with only the base interface nsISupports available on it; you must call nsISupports.QueryInterface
() on it to call methods on the object. ...
...And 7 more matches
nsIAccessible
article. Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Overview This section provides short overview of methods and attributes of this interface. All methods and attributes are grouped by categories. Role, states and name These includes main properties used to describe the accessible. nsIAccessible.role to get the role of the accessible nsIAccessible.getState
() to get states of the accessibe nsIAccessible.name, nsIAccessible.value to get the name and the value of the accessible Tree navigation You can navigate through the accessible tree by the following methods and attributes. nsIAccessible.parent to get the parent accessible nsIAccessible.nextSibling, nsIAccessible.previousSibling to get sibling accessibles nsIAccessible.firstChild, nsIAcces...
...the value of the accessible Tree navigation You can navigate through the accessible tree by the following methods and attributes. nsIAccessible.parent to get the parent accessible nsIAccessible.nextSibling, nsIAccessible.previousSibling to get sibling accessibles nsIAccessible.firstChild, nsIAccessible.lastChild to get first and last child nsIAccessible.children, nsIAccessible.getChildAt
(), nsIAccessible.childCount to navigate through the children by index Accessible position You can use nsIAccessible.indexInParent to get accessible index in its parent. Use nsIAccessible.groupPosition
() to get information about this accessible in its group. Relations Many accessibles are linked with each other, for example, if one accessible gives the accessible name for another accessible (for ex...
...rmation about this accessible in its group. Relations Many accessibles are linked with each other, for example, if one accessible gives the accessible name for another accessible (for example, html:label and html control) then these accessibles are related, please refer to relations documentation for more information. You can get related accessibles by methods nsIAccessible.getAccessibleRelated
() nsIAccessible.getRelations
() nsIAccessible.getRelation
() and nsIAccessible.relationsCount. Focus and selection In order to focus an accessible or get focused child accessible use nsIAccessible.takeFocus
() and nsIAccessible.focusedChild. To select an accessible you can use nsIAccessible.setSelected
(), nsIAccessible.takeSelection
() and nsIAccessible.extendSelection
(). Actions You can prepare a...
...And 7 more matches
nsIAccessibleRetrieval
OMNode aNode); nsIAccessible getAccessibleInShell(in nsIDOMNode aNode, in nsIPresShell aPresShell); nsIAccessible getAccessibleInWeakShell(in nsIDOMNode aNode, in nsIWeakReference aPresShell); Obsolete since Gecko 2.0 nsIAccessible getAccessibleInWindow(in nsIDOMNode aNode, in nsIDOMWindow aDOMWin); Obsolete since Gecko 2.0 nsIAccessible getApplicationAccessible
(); nsIAccessible getAttachedAccessibleFor(in nsIDOMNode aNode); nsIAccessible getCachedAccessible(in nsIDOMNode aNode, in nsIWeakReference aShell); Obsolete since Gecko 2.0 nsIAccessNode getCachedAccessNode(in nsIDOMNode aNode, in nsIWeakReference aShell); Obsolete since Gecko 2.0 nsIDOMNode getRelevantContentNodeFor(in nsIDOMNode aNode); AString getS...
... nsIDOMNode getRelevantContentNodeFor(in nsIDOMNode aNode); AString getStringEventType(in unsigned long aEventType); AString getStringRelationType(in unsigned long aRelationType); AString getStringRole(in unsigned long aRole); nsIDOMDOMStringList getStringStates(in unsigned long aStates, in unsigned long aExtraStates); Methods getAccessibleFor
() Return an nsIAccessible for a DOM node in pres shell 0. Create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it already exists. nsIAccessible getAccessibleFor( in nsIDOMNode aNode ); Parameters aNode The DOM node to get an accessible for. Return value The nsIAccessible for the given DOM node. getAccessibleInShell
() Return an nsIAcce...
...ary, or use one from the accessibility cache if it already exists. nsIAccessible getAccessibleInShell( in nsIDOMNode aNode, in nsIPresShell aPresShell ); Parameters aNode The DOM node to get an accessible for. aPresShell The presentation shell which contains layout info for the DOM node. Return value The nsIAccessible for the given DOM node. getAccessibleInWeakShell
() Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Return an nsIAccessible for a DOM node in the given weak shell. Create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it already exists. nsIAccessible getAccessibleInWeakShell( in nsIDOMNode aNode, in nsIWeakReference aPresShell ); Parameters aNode ...
...And 7 more matches
nsIAccessibleTable
For example, html:c...
...w index of the cell. columnIndex The column index of the cell. Return value An nsIAccessible object. Translate the given row and column indices into the corresponding cell index. long getCellIndexAt( in long rowIndex, in long columnIndex ); Parameters rowIndex The row index of the cell. columnIndex The column index of the cell. Return value A cell index. getColumnDescription
() Return the description text of the specified column in the table. AString getColumnDescription( in long columnIndex ); Parameters columnIndex The column index. Return value The column description. getColumnExtentAt
() Return the number of columns occupied by the accessible cell at the specified row and column in the table. The result differs from 1 if the specified cell spans multip...
...mnExtentAt( in long row, in long column ); Parameters row The row index of the cell. column The column index of the cell. Return value The number of columns the cell spans. Return the index of the column containg the given cell index. long getColumnIndexAt( in long cellIndex ); Parameters cellIndex The cell index. Return value The column index. ...
...And 7 more matches
nsICryptoHash
The values map directly onto the values defined in mozilla/security/nss/lib/cryptohi/hasht.h. Constant Value Description MD2 1 Message Digest Algorithm 2 MD5 2 Message-Digest algorithm 5 SHA1 3 Secure Hash Algorithm 1 SHA256 4 Secure Hash Algorithm 256 SHA384 5...
...mozilla/security/nss/lib/cryptohi/hasht.h. Constant Value Description MD2 1 Message Digest Algorithm 2 MD5 2 Message-Digest algorithm 5 SHA1 3 Secure Hash Algorithm 1 SHA256 4 Secure Hash Algorithm 256 SHA384 5 Secure Hash Algorithm 384 SHA512 6 Secure Hash Algorithm 512 Methods finish
() Completes the hash object and produces the actual hash data. Note: This method may be called any time after " .. manch("init") .. " is called. This call resets the object. ACString finish( in PRBool aASCII ); Parameters aASCII If true then the returned value is a base-64 encoded string. If false, then the returned value is binary data. Return value This method returns a hash of the ...
... the object. ACString finish( in PRBool aASCII ); Parameters aASCII If true then the returned value is a base-64 encoded string. If false, then the returned value is binary data. Return value This method returns a hash of the data that was read by this object. This can be either binary data or a base-64 encoded string. Exceptions thrown NS_ERROR_NOT_INITIALIZED Indicates that init
() or initWithString
() has not been called. init
() Initialize the hashing object. This method may be called multiple times with different algorithm types. Note: This method or " .. manch("initWithString") .. " must be called before any other method on this interface is called. void init( in unsigned long aAlgorithm ); Parameters aAlgorithm The hash algorithm to use. Must be one of the H...
...And 7 more matches
nsIJSON
nterfaces/json/nsIJSON.idlScriptable This interface provides a convenient way to encode and decode JSON strings from JavaScript code. 1.0 66 Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) Note: This interface may only be used from JavaScript code, with the exception of the legacyDecodeToJSVal
() method. However, you should use native JSON instead if at all possible. Implemented by: @mozilla.org/dom/json;1. To create an instance, use: var nativeJSON = Components.classes["@mozilla.org/dom/json;1"] .createInstance(Components.interfaces.nsIJSON); Method overview Note: The IDL file has portions of the IDL commented out because they represent things that can't actually be...
... Note: This method is more flexible than it should be, and accepts some not-correctly-structured JSON. For that reason, it has been removed in Gecko 7.0. JSObject decode( in AString str ); Parameters str The JSON string to dec...
...SON string, returning the JavaScript object it represents. Note: This method is more flexible than it should be, and accepts some not-correctly-structured JSON. For that reason, it has been removed in Gecko 7.0. JSObject decode( in AString str ); Parameters str The JSON string to decode. Return value The original JavaScript object, reconstructed from the JSON string. decodeToJSVal
() Note: This method may only be used from native code, and provides a way to decode a JSON string to a jsval for use in your native code. Don't forget to GCroot the result before using it. jsval decodeToJSVal( in AString str, in JSContext cx ); Parameters str The JSON string to decode. cx The JavaScript runtime context to use to decode the string. Return value The original Java...
...And 7 more matches
nsILivemarkService
long long createLivemark( in long long folder, in AString name, in nsIURI ...
...getLivemarkIdForFeedURI(in nsIURI aFeedURI); nsIURI getSiteURI(in long long container); boolean isLivemark(in long long folder); void reloadAllLivemarks
(); void reloadLivemarkFolder(in long long folderID); void setFeedURI(in long long container, in nsIURI feedURI); void setSiteURI(in long long container, in nsIURI siteURI); void start
(); void stopUpdateLivemarks
(); Methods createLivemark
() Creates a new livemark. long long createLivemark( in long long folder, in AString name, in nsIURI siteURI, in nsIURI feedURI, in long index ); Parameters folder The id of the parent folder. name The name to show when displaying the livemark. siteURI The URI of the site from which the livemark was create...
...URI feedURI, in long index ); Parameters folder The id of the parent folder. name The name to show when displaying the livemark. siteURI The URI of the site from which the livemark was created. feedURI The URI of the actual RSS feed. index The index to insert at, or -1 to append to the end of the list. Return value The ID of the folder for the livemark. createLivemarkFolderOnly
() This method also creates a new livemark but use this method during startup to avoid HTTP traffic. long long createLivemarkFolderOnly( in long long folder, in AString name, in nsIURI siteURI, in nsIURI feedURI, in long index ); Parameters folder The id of the parent folder. name The name to show when displaying the livemark. siteURI The URI of the site from which the livemark...
...And 7 more matches
nsISmsRequestManager
questId, in long aError); void notifySmsSendFailed(in long aRequestId, in long aError); void notifySmsSent(in long aRequestId, in nsIDOMMozSmsMessage aMessage); Constants All SMS related errors that could apply to SmsRequest objects. Constant Value Description SUCCESS_NO_ERROR 0 NO_SIGNAL_ERROR 1 NOT_FOUND_ERROR 2 UNKNOWN_ERROR 3 INTERNAL_ERROR 4 Methods addRequest
() Track an already existing request object. long addRequest( in nsIDOMMozSmsRequest aRequest ); Parameters aRequest An SmsRequest. Return value The request ID. createRequest
() Create a new request object. long createRequest( in nsIDOMMozSmsManager aManager, out nsIDOMMozSmsRequest aRequest ); Parameters aManager An SmsManager. aRequest An SmsRequest. Return value The request ID. notifyC...
...y existing request object. long addRequest( in nsIDOMMozSmsRequest aRequest ); Parameters aRequest An SmsRequest. Return value The request ID. createRequest
() Create a new request object. long createRequest( in nsIDOMMozSmsManager aManager, out nsIDOMMozSmsRequest aRequest ); Parameters aManager An SmsManager. aRequest An SmsRequest. Return value The request ID. notifyCreateMessageList
() void notifyCreateMessageList( in long aRequestId, in long aListId, in nsIDOMMozSmsMessage aMessage ); Parameters aRequestId A number representing the id of the request. aListId A number representing the id of the list. ...
... aRequest ); Parameters aManager An SmsManager. aRequest An SmsRequest. Return value The request ID. notifyCreateMessageList
() void notifyCreateMessageList( in long aRequestId, in long aListId, in nsIDOMMozSmsMessage aMessage ); Parameters aRequestId A number representing the id of the request. aListId A number representing the id of the list. aMessage An SmsMessage. notifyGetSmsFailed
() void notifyGetSmsFailed( in long aRequestId, in long aError ); Parameters aRequestId A number representing the id of the request. aError A number with an error code. See constants. notifyGotNextMessage
() void notifyGotNextMessage( in long aRequestId, in nsIDOMMozSmsMessage aMessage ); Parameters aRequestId A number representing the id of the request. aMessage An SmsMessage. notifyGo...
...And 7 more matches
nsITransferable
The destination URL for a file promise. kFilePromiseMime application/x-moz-file-promise A dataless flavor used to interact with the operating system during file drags. kFilePromiseDirectoryMime application/x-moz-file-promise-dir A synthetic flavor which is added to the transferable once the destination directory for a file drag is known. ...
...ble once the destination directory for a file drag is known. Methods addDataFlavor
() Adds a new data flavor, indicating that this transferable can receive the type of data represented by the specified flavor string. void addDataFlavor( in string aDataFlavor ); Parameters aDataFlavor A string defining a new data flavor that the transferable supports. flavorsTransferableCanExport
() Returns a list of flavors (mime types as nsISupportsCString) that the transferable can export, either through intrinsic knowledge or output data converters. nsISupportsArray flavorsTransferableCanExport
(); Parameters None. ...
...lavor A string defining a new data flavor that the transferable supports. flavorsTransferableCanExport
() Returns a list of flavors (mime types as nsISupportsCString) that the transferable can export, either through intrinsic knowledge or output data converters. nsISupportsArray flavorsTransferableCanExport
(); Parameters None. Return value Missing Description flavorsTransferableCanImport
() Computes a list of flavors (MIME types as nsISupportsCString) that the transferable can accept into it, either through intrinsic knowledge or input data converters. nsISupportsArray flavorsTransferableCanImport
(); Parameters None. ...
...And 7 more matches
nsITreeSelection
layout/xul/base/src/tree/public/nsITreeSelection.idlScriptable This interface is used by the tree widget to get information about what is selected. ...
...sed by the tree widget to get information about what is selected. ...
...tion about what is selected. ...
...And 7 more matches
nsIURI
irefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) See the following RFCs for details: RFC3490: Internationalizing Domain Names in Applications (IDNA) RFC3986: Uniform Resource Identifier (URI): Generic Syntax RFC3987: Internationalized Resource Identifiers Subclasses of nsIURI, such as nsIURL, impose further structure on the URI. ...
...Follows the IDN...
...Follows the IDNA draft specification for converting...
...And 7 more matches
XPCOM primitive
An XPCOM primitive is an XPCOM object that "boxes" a value of a primitive type. All XPCOM primitives are scriptable, and they all implement an XPCOM interface from the table below. Primitives are rarely useful. The main use case is to store primitive values in a data structure that can only store XPCOM objects, such as nsIArray. ...
...nsITransferable.setTransferData
(), require primitives. ...
...illa.org/supports-id;1 [scriptable, uuid(d18290a0-4a1c-11d3-9890-006008962422)] interface nsISupportsID : nsISupportsPrimitive { attribute nsIDPtr data; string toString
(); }; AString nsISupportsString @mozilla.org/supports-string;1 [scriptable, uuid(d79dc970-4a1c-11d3-9890-006008962422)] interface nsISupportsString : nsISupportsPrimitive { attribute AString data; wstring toString
(); }; PRBool nsISupportsPRBool @mozilla.org/supports-PRBool;1 [scriptable, uuid(ddc3b490-4a1c-11d3-9890-006008962422)] interface nsISupportsPRBool : nsISupportsPrimitive { attribute PRBool data; string toString
(); }; PRUint8 nsISupportsPRUint8 @mozilla.org/supports-PRUint8;1 [scriptable, uuid(dec2e4e0-4a1c-11d3-9890-006008962422)] interface nsISupportsPRUint8 : nsISupportsPrimitive { ...
...And 7 more matches
Activity Manager examples
// Step 1: Create a nsIActivityCan...
...ocess.contextType; // optional event.contextObj = process.contextObj; // optional gActivityManager.addActivity(event); Showing a user-defined activity with cancel capability (JavaScript) This sample improves the previous one by providing an nsIActivityCancelHandler to allow the user to cancel the process. // Step 1: Create a nsIActivityCancelHandler implementation function CancelJunkProcess
() { // user stuff here.. } CancelJunkProcess.prototype = { cancel: function(aActivity) { let initiator = aActivity.initiator; if (initiator) { let folder = aActivity.getSubjects({})[0]; .... // assuming that the initiator has some way to cancel // the junk processing for given folder if (initiator.cancelFolderOp(folder)) { aActivity.state = Components.interfa...
...IActivityCancelHandler component ... // assuming that gJunkProcessor is the entity initiating the junk processing // activity, and it has cancelFolderOp method that cancels the operations on folders process.init("Processing folder: " + folder.prettiestName, gJunkProcessor); // folder is being filtered/processed process.addSubject(folder); process.cancelHandler = new CancelJunkProcess
(); ... Since nsIActivityCancelHandler is provided with the activity, the UI will show a cancel button beside the activity. You can extrapolate this sample to nsIActivityRetryHandler and nsIActivityPauseHandler as well. Showing a user-defined activity with undo capability (C++) ..... #include "nsIActivity.h" #include "nsIActivityManager.h" ..... ///////////////////////////////////////////////...
...And 7 more matches
Blob - Web APIs
d as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. Blobs can represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. ...
...rocessing the data. Blobs can represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. Using blobs To construct a Blob from other non-blob objects and data, use the Blob
() constructor. To create a blob that contains a subset of another blob's data, use the slice
() method. To obtain a Blob object for a file on the user's file system, see the File documentation. The APIs accepting Blob objects are also listed in the File documentation. Constructor Blob
() Returns a newly created Blob object which contains a concatenation of all of the data in the array passed into the constructor. Instance properties Blob.prototype.size Read only The size, in byt...
...ontains a concatenation of all of the data in the array passed into the constructor. Instance properties Blob.prototype.size Read only The size, in bytes, of the data contained in the Blob object. Blob.prototype.type Read only A string indicating the MIME type of the data contained in the Blob. If the type is unknown, this string is empty. ...
...And 7 more matches
Manipulating video using canvas - Web APIs
e original video, while c2 is used to display the video after performing the chroma-keying effect; c2 is preloaded with the still image that will be used to replace the green background in the video. The JavaScript code is imported from a script named processor.js. The JavaScript code The JavaScript code in processor.js consists of three methods. ...
...JavaScript code in processor.js consists of three methods. Initializing the chroma-key player The doLoad
() method is called when the XHTML document initially loads. This method's job is to prepare the variables needed by the chroma-key processing code, and to set up an event listener so we can detect when the user starts playing the video. ...
...etect when the user starts playing the video. var processor; processor.doLoad = function doLoad
() { this.video = document.getElementById('video'); this.c1 = document.getElementById('c1'); this.ctx1 = this.c1.getContext('2d'); this.c2 = document.getElementById('c2'); this.ctx2 = this.c2.getContext('2d'); let self = this; this.video.addEventListener('play', function
() { self.width = self.video.videoWidth / 2; self.height = self.video.videoHeight / 2; self.timerCallback
(); }, false); }, This code grabs references to the elements in the XHTML document that are of particular interest, namely the video element and the two canvas elements. It also fetches references to the graphics contexts for each of the two canvases. These wil...
...And 7 more matches
Document.cookie - Web APIs
g-format If neither expires nor max-age specified it will expire at the end of session. When user privacy is a concern, it's important that any web app implementation invalidate cookie data after a certain timeout instead of relying on the browser to do it. Many browsers let users specify that cookies should never expire, which is not necessarily safe. See Date.toUTCString
() for help formatting this value. ;secure Cookie to only be transmitted over secure protocol as https. Before Chrome 52, this flag could appear with cookies from http domains. ;samesite SameSite prevents the browser from sending this cookie along with cross-site requests. Possible values are lax, strict or none. The lax value value will send the cookie for all same-site req...
...ue in modern browsers. The strict value will prevent the cookie from being sent by the browser to the target site in all cross-site browsing contexts, even when following a regular link. The none value explicitly states no restrictions will be applied. The cookie will be sent in all requests--both cross-site and same-site. The cookie value string can use encodeURIComponent
() to ensure that the string does not contain 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 us...
... from the code above, document.cookie is an accessor property with native setter and getter functions, and consequently is not a data property with a value: what you write is not the same as what you read, everything is always mediated by the JavaScript interpreter. ...
...And 7 more matches
Introduction to the DOM - Web APIs
ipt> element or included in the web page by means of a script loading instruction-you can immediately begin using the API for the document or window elements to manipulate the document itself or to get at the children of that document, which are the various elements in the web page. Your DOM programming may be something as simple as the following, which displays an alert message by using the alert
() function from the window object, or it may use more sophisticated DOM methods to actually create new content, as in the longer example below. This following JavaScript will display an alert when the document is loaded (and when the whole DOM is available for use): <body onload="window.alert('Welcome to my home page!');"> Another example. This function creates a new H1 element, adds text to th...
...y an alert when the document is loaded (and when the whole DOM is available for use): <body onload="window.alert('Welcome to my home page!');"> Another example. ...
...he document object. Node Every object located within a document is a node of some kind. In an HTML document, an object can be an element node but also a text node or attribute node. Element The element type is based on node. It refers to an element or a node of type element returned by a member of the DOM API. Rather than saying, for example, that the document.createElement
() method returns an object reference to a node, we just say that this method returns the element that has just been created in the DOM. element objects implement the DOM Element interface and also the more basic Node interface, both of which are included together in this reference. In an HTML document, elements are further enhanced by the HTML DOM API's HTMLElement interface as well as other interf...
...And 7 more matches
FileSystemEntrySync - Web APIs
ccepted and never became standardized. Various browsers implement pieces of the File and Directory Entries API (otherwise known as the File System API) but you should try to avoid using it. Basic concepts The FileSystemEntrySync interface includes methods that you would expect for manipulating files and directories, but it also include a really handy method for getting a URL of the entry: toURL
(). It also introduces a new URL scheme: filesystem:. You can use the filesystem: scheme on Google Chrome to see all the files and folders that are stored in the origin of your app. Just use filesystem: scheme for the root directory of the origin of the app. For example, if your app is in http://ww.html5rocks.com, open filesystem:http://www.html5rocks.com/temporary/ in a tab. Chrome shows a read-on...
...the files and folders that are stored in the origin of your app. Just use filesystem: scheme for the root directory of the origin of the app. For example, if your app is in http://ww.html5rocks.com, open filesystem:http://www.html5rocks.com/temporary/ in a tab. Chrome shows a read-only list of all the files and folders stored the origin of your app. ...
...ist of all the files and folders stored the origin of your app. Method overview Metadata getMetadata
() raises (FileException); FileSystemEntrySync moveTo (in DirectoryEntrySync parent, optional DOMString newName) raises (FileException); FileSystemEntrySync copyTo(in DirectoryEntrySync parent, optional DOMString newName) raises (FileException); DOMString toURL
(); void remove
() raises (FileException); DirectoryEntrySync getParent
(); Attributes Attribute Type Description filesystem readonly FileSystemSync The file system where the entry resides. fullpath readonly DOMString The full absolute path from the root to the entry. An absolute path is a relative path from the root ...
...And 7 more matches
Using the Geolocation API - Web APIs
ocation API is available through the navigator.geolocation object. If the object exists, geolocation services are available. You can test for the presence of geolocation thusly: if('geolocation' in navigator) { /* geolocation is available */ } else { /* geolocation IS NOT available */ } Getting the current position To obtain the user's current location, you can call the getCurrentPosition
() method. This initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information. When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs. A third, optional, parameter is an options object where you can set the maximum age of t...
...ation. When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs. A third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position. Note: By default, getCurrentPosition
() tries to answer as fast as possible with a low accuracy result. It is useful if you need a quick answer regardless of the accuracy. Devices with a GPS, for example, can take a minute or more to get a GPS fix, so less accurate data (IP location or wifi) may be returned to getCurrentPosition
(). navigator.geolocation.getCurrentPosition((position) => { doSomething(position.coords.latitude, positi...
...useful if you need a quick answer regardless of the accuracy. Devices with a GPS, for example, can take a minute or more to get a GPS fix, so less accurate data (IP location or wifi) may be returned to getCurrentPosition
(). navigator.geolocation.getCurrentPosition((position) => { doSomething(position.coords.latitude, position.coords.longitude); }); The above example will cause the doSomething
() function to execute when the location is obtained. Watching the current position If the position data changes (either by device movement or if more accurate geo information arrives), you can set up a callback function that is called with that updated position information. This is done using the watchPosition
() function, which has the same input parameters as getCurrentPosition
(). The callback f...
...And 7 more matches
HTMLFormElement - Web APIs
ether the form should not be validated. Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (e.g. a form with an input named action will have its action property return that input instead of the form's action HTML attribute). Methods This interface also inherits methods from its parent, HTMLElement. checkValidity
() Returns true if the element's child controls are subject to constraint validation and satisfy those contraints; returns false if some controls do not satisfy their constraints. Fires an event named invalid at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled. It is up to the programmer to decide how to respond to false. reportVa...
...rns true if the element's child controls are subject to constraint validation and satisfy those contraints; returns false if some controls do not satisfy their constraints. Fires an event named invalid at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled. It is up to the programmer to decide how to respond to false. ...
...isfy its constraints; such controls are considered invalid if the event is not canceled. It is up to the programmer to decide how to respond to false. reportValidity
() Returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user. requestSubmit
() Requests that the form be submitted using the specified submit button and its corresponding configuration. reset
() Resets the form to its initial state. submit
() Submits the form to the server. ...
...And 7 more matches
HTMLTextAreaElement - Web APIs
performed in the start-to-end direction of the current locale, or "backward" for the opposite direction. This can also be "none" if the direction is unknown. selectionEnd unsigned long: Returns / Sets the index of the end of selected text. If no text is selected, contains the index of the character that follows the input cursor. ...
... tabIndex long: Returns / Sets the position of the element in the tabbing navigation order for the current document. textLength Read only long: Returns the codepoint length of the control's value. ...
... / Sets the wrap HTML attribute, indicating how the control wraps text. HTMLTextAreaElement.labelsRead only NodeList: Returns a list of label elements associated with this element. The two properties tabIndex and accessKey are inherited from HTMLElement from HTML5 on, but were defined on HTMLTextAreaElement in DOM Level 2 HTML and earlier specifications. ...
...And 7 more matches
ImageCapture - Web APIs
The ImageCapture interface of the MediaStream Image Capture API provides methods to enable the capture of images or photos from a camera or other photographic device. It provides an interface for capturing images from a photographic device referenced through a valid MediaStreamTrack. Constructor ImageCapture
() Creates a new ImageCapture object which can be used to capture still frames (photos) from a given MediaStreamTrack which represents a video stream. ...
...an be used to capture still frames (photos) from a given MediaStreamTrack which represents a video stream. Properties ImageCapture.track Read only Returns a reference to the MediaStreamTrack passed to the constructor. Methods The ImageCapture interface is based on EventTarget, so it includes the methods defined by that interface as well as the ones listed below. ...
...amTrack passed to the constructor. Methods The ImageCapture interface is based on EventTarget, so it includes the methods defined by that interface as well as the ones listed below. ImageCapture.takePhoto
() Takes a single exposure using the video capture device sourcing a MediaStreamTrack and returns a Promise that resolves with a Blob containing the data. ImageCapture.getPhotoCapabilities
() Returns a Promise that resolves with a PhotoCapabilities object containing the ranges of available configuration options. ImageCapture.getPhotoSettings
() Returns a Promise that resolves with a PhotoSettings object containing the current photo configuration settings. ImageCapture.grabFrame
() Takes a snapshot of the live video in a MediaStreamTrack, returning an ImageBitmap, if successful. E...
...And 7 more matches
Using the MediaStream Recording API - Web APIs
Both audio and video may be recorded, separately or together. This article aims to provide a basic guide on how to use the MediaRecorder interface, which provides this API. A sample application: Web Dictaphone To demonstrate basic usage of the MediaRecorder API, we have built a web-based dictaphone. It allows you to record snippets of audio and then play them back. ...
...goodies The HTML is pretty simple in this app, so we won't go through it here; there are a couple of slightly more interesting bits of CSS worth mentioning, however, so we'll discuss them below. If you are not interested in CSS and want to get straight to the JavaScript, skip to the Basic app setup section. Keeping the interface constrained to the viewport, regardless of device height, with calc
() The calc
() function is one of those useful little utility features that's cropped up in CSS that doesn't look like much initially, but soon starts to make you think "Wow, why didn't we have this before? Why was CSS2 layout so awkward?" It allows you do a calculation to determine the computed value of a CSS unit, mixing different units in the process. For example, in Web Dictaphone we have three...
...d be the answer here, but it's a bit overkill for such a simple layout. Instead, the problem was solved by making the third container's height equal to 100% of the parent height, minus the heights and padding of the other two: .sound-clips { box-shadow: inset 0 3px 4px rgba(0,0,0,0.7); background-color: rgba(0,0,0,0.1); height: calc(100% - 240px - 0.7rem); overflow: scroll; } Note: calc
() has good support across modern browsers too, even going back to Internet Explorer 9. Checkbox hack for showing/hiding This is fairly well documented already, but we thought we'd give a mention to the checkbox hack, which abuses the fact that you can click on the <label> of a checkbox to toggle it checked/unchecked. In Web Dictaphone this powers the Information screen, which is shown/hidden by ...
...And 7 more matches
MediaStream Recording API - Web APIs
object, specifying the source stream and any desired options (such as the container's MIME type or the desired bit rates of its tracks). Set MediaRecorder.ondataavailable to an event handler for the dataavailable event; this will be called whenever data is available for you. Once the source media is playing and you've reached the point where you're ready to record video, call MediaRecorder.start
() to begin recording. Your dataavailable event handler gets called every time there's data ready for you to do with as you will; the event has a data attribute whose value is a Blob that contains the media data. You can force a dataavailable event to occur, thereby delivering the latest sound to you so you can filter it, save it, or whatever. Recording stops automatically when the source media st...
...there's data ready for you to do with as you will; the event has a data attribute whose value is a Blob that contains the media data. You can force a dataavailable event to occur, thereby delivering the latest sound to you so you can filter it, save it, or whatever. Recording stops automatically when the source media stops playing. You can stop recording at any time by calling MediaRecorder.stop
(). Note: Individual Blobs containing slices of the recorded media will not necessarily be individually playable. The media needs to be reassembled before playback. If anything goes wrong during recording, an error event is sent to the MediaRecorder. You can listen for error events by setting up a onerror event handler. Example here, we use an HTML Canvas as source of the MediaStream, and st...
...iaStream, and stop recording after 9 seconds. var canvas = document.querySelector("canvas"); // Optional frames per second argument. ...
...And 7 more matches
MessageEvent - Web APIs
The MessageEvent interface represents a message received by a target object. This is used to represent messages in: 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 ev...
... Properties This interface also inherits properties from its parent, Event. MessageEvent.data Read only The data sent by the message emitter. MessageEvent.origin Read only A USVString representing the origin of the message emitter. MessageEvent.lastEventId Read only A DOMString representing a unique ID for the event. MessageEvent.source Read only A Mes...
...gePort, or ServiceWorker object) representing the message emitter. MessageEvent.ports Read only An array of MessagePort objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker). Methods This interface also inherits methods from its parent, Event. initMessageEvent
() Initializes a message event. Do not use this anymore -- use the MessageEvent
() constructor instead. Examples In our Basic shared worker example (run shared worker), we have two HTML pages, each of which uses some JavaScript to perform a simple calculation. The different scripts are using the same worker file to perform the calculation -- they can both access it, even if their pages are runn...
...And 7 more matches
OfflineAudioContext - Web APIs
Properties Also inherits properties from its parent interface, BaseAudioContext. OfflineAudioContext.length Read only An integer representing the size of the buffer in sample-frames. Event handlers OfflineAudioContext.oncomplete Is an EventHandler called when processing is terminated, that is when the complete event (of type OfflineAudioC...
...parent interface, BaseAudioContext. OfflineAudioContext.length Read only An integer representing the size of the buffer in sample-frames. Event handlers OfflineAudioContext.oncomplete Is an EventHandler called when processing is terminated, that is when the complete event (of type OfflineAudioCompletionEvent) is raised, after the event-based version of OfflineAudioContext.startRendering
() is used. Methods Also inherits methods from its parent interface, BaseAudioContext. OfflineAudioContext.suspend
() Schedules a suspension of the time progression in the audio context at the specified time and returns a promise. OfflineAudioContext.startRendering
() Starts rendering the audio, taking into account the current connections and the current scheduled changes. This page covers bo...
...xt.suspend
() Schedules a suspension of the time progression in the audio context at the specified time and returns a promise. OfflineAudioContext.startRendering
() Starts rendering the audio, taking into account the current connections and the current scheduled changes. This page covers both the event-based version and the promise-based version. Deprecated methods OfflineAudioContext.resume
() Resumes the progression of time in an audio context that has previously been suspended. Note: The resume
() method is still available -- it is now defined on the BaseAudioContext interface (see BaseAudioContext.resume
()) and thus can be accessed by both the AudioContext and OfflineAudioContext interfaces. ...
...And 7 more matches
Using the Permissions API - Web APIs
issions are concerned. For example, it can query whether permission to use a particular API is granted or denied, and specifically request permission to use an API. At the moment, implementation of the API is at an early stage, so support in browsers is pretty spotty: It can only be found in Chrome 44 and later and Firefox 43 and later. The only supported method right now is Permissions.query
(), which queries permission status. The only two APIs currently recognized by the Permissions API in Chrome are Geolocation and Notification, with Firefox also recognizing Push and WebMIDI. More features will be added as time progresses. A simple example For this article, we have put together a simple demo called Location Finder. It uses Geolocation to query the user's current location and plo...
...e Permissions API-related code, so check the code yourself if you want to study any of the other parts. Accessing the Permissions API The Navigator.permissions property has been added to the browser to allow access to the global Permissions object. This object will eventually include methods for querying, requesting, and revoking permissions, although currently it only contains Permissions.query
(); see below. Querying permission state In our example, the Permissions functionality is handled by one function -- handlePermission
(). This starts off by querying the permission status using Permissions.query
(). Depending on the value of the state property of the PermissionStatus object returned when the promise resolves, it reacts differently: "granted" The "Enable Geolocation" button is h...
...lue of the state property of the PermissionStatus object returned when the promise resolves, it reacts differently: "granted" The "Enable Geolocation" button is hidden, as it isn't needed if Geolocation is already active. "prompt" The "Enable Geolocation" button is hidden, as it isn't needed if the user will be prompted to grant permission for Geolocation. The Geolocation.getCurrentPosition
() function is then run, which prompts the user for permission; it runs the revealPosition
() function if permission is granted (which shows the map), or the positionDenied
() function if permission is denied (which makes the "Enable Geolocation" button appear). "denied" The "Enable Geolocation" button is revealed (this code needs to be here too, in case the permission state is already set to denied...
...And 7 more matches
Hello GLSL - Web APIs
<canvas>Your browser does not seem to support HTML5 canvas.</canvas> body { text-align : center; } canvas { width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } <script type="x-shader/x-vertex" id="vertex-shader"> #version 100 void main
() { gl_Position = vec4(0.0, 0.0, 0.0, 1.0); gl_PointSize = 64.0; } </script> <script type="x-shader/x-fragment" id="fragment-shader"> #version 100 void main
() { gl_FragColor = vec4(0.18, 0.54, 0.34, 1.0); } </script> ;(function
(){ "use strict" window.addEventListener("load", setupWebGL, false); var gl, program; function setupWebGL (evt) { window.removeEventListener(evt.type, setup...
...gl_PointSize = 64.0; } </script> <script type="x-shader/x-fragment" id="fragment-shader"> #version 100 void main
() { gl_FragColor = vec4(0.18, 0.54, 0.34, 1.0); } </script> ;(function
(){ "use strict" window.addEventListener("load", setupWebGL, false); var gl, program; function setupWebGL (evt) { window.removeEventListener(evt.type, setupWebGL, false); if (!(gl = getRenderingContext
())) return; var source = document.querySelector("#vertex-shader").innerHTML; var vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader,source); gl.compileShader(vertexShader); source = document.querySelector("#fragment-shader").innerHTML var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader,source); gl.compileShader(fr...
...rySelector("#vertex-shader").innerHTML; var vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader,source); gl.compileShader(vertexShader); source = document.querySelector("#fragment-shader").innerHTML var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader,source); gl.compileShader(fragmentShader); program = gl.createProgram
(); gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); gl.detachShader(program, vertexShader); gl.detachShader(program, fragmentShader); gl.deleteShader(vertexShader); gl.deleteShader(fragmentShader); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { var linkErrLog = gl.getProgramInfoLog(program); cleanup
(); do...
...And 7 more matches
Raining rectangles - Web APIs
strong>. ...
... background-color : black; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } ;(function
(){ "use strict" window.addEventListener("load", setupAnimation, false); var gl, timer, rainingRect, scoreDisplay, missesDisplay; function setupAnimation (evt) { window.removeEventListener(evt.type, setupAnimation, false); if (!(gl = getRenderingContext
())) return; gl.enable(gl.SCISSOR_TEST); rainingRect = new Rectangle
(); timer = setTimeout(drawAnimation, 17); document.querySelector("canvas") .addEventListener("click", playerClick, false); var displays = document.querySelectorAll("strong"); scoreDisplay = displays[0]; missesDisplay = displays[1]; } var score = 0, misses = 0; function drawAnimation
() { gl.scissor(rai...
...So we reschedule // the timeout to call drawAnimation again in 17ms. // Otherwise we won't get any animation. ...
...And 7 more matches
Animating textures in WebGL - Web APIs
We set it to autoplay, mute the sound, and loop the ...
...We set it to autoplay, mute the sound, and loop the video. We then set up two events to make ...
...We set it to autoplay, mute the sound, and loop the video. We then set up two events to make sure the video is playing and the time has been updated. We need...
...And 7 more matches
WebRTC connectivity - Web APIs
ocess is performed both when a call is first established, but also any time the call's format or other configuration needs to change. ...
... call's format or other configuration needs to change. ...
... new call, or reconfiguring an existing one, these are the basic steps which must occur to exchange the offer and answer, leaving out the ICE layer for the moment: The caller captures local Media via navigator.mediaDevices.getUserMedia
() The caller creates RTCPeerConnection and called RTCPeerConnection.addTrack
() (Since addStream is deprecating) The caller calls RTCPeerConnection.createOffer
() to create an offer. The caller calls RTCPeerConnection.setLocalDescription
() to set that offer as the local description (that is, the description of the local end of the connection). After setLocalDescription
(), the caller asks STUN servers to generate the ice candidates The caller uses the signaling server to transmit the offer to the intended receiver of the call. The recipient receives the...
...And 7 more matches
Using bounded reference spaces - Web APIs
The options specified when requesting the session indicate that at a minimum, the session must be compatible with the local-floor reference space, but that it would be nice if th...
...as usual, exiting at once if a session is already in place, then requesting a new session using immersive-vr mode. The options specified when requesting the session indicate that at a minimum, the session must be compatible with the local-floor reference space, but that it would be nice if the bounded-floor space were supported as well. Once the session has been created, our startSessionAnimation
() function can try to establish a bounded-floor reference space, and if it fails to do so it can then fall back to requesting a local-floor reference space instead (in which we will have to handle boundaries ourselves). This way, our session will start up regardless of whether or not the user's platform is able to provide bounded reference spaces. Creating the reference space Simply requesting s...
...t fails to do so it can then fall back to requesting a local-floor reference space instead (in which we will have to handle boundaries ourselves). This way, our session will start up regardless of whether or not the user's platform is able to provide bounded reference spaces. ...
...And 7 more matches
Functions and classes available to Web Workers - Web APIs
, 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. ...
...ow, implements WindowTimers and WindowBase64. ...
...s Shared workers Service workers Chrome workers Outside workers atob
() yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on Window btoa
() yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on Window clearInterval
() yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on Window clearTimeout
() yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on Window dump
() yes, on WorkerGlobalScope yes, on WorkerGlobalScope yes, on WorkerGlobalScope ...
...And 7 more matches
Window: popstate event - Web APIs
The popstate event of the Window interface is fired when the active history entry changes while the user navigates the session history. It changes the current history entry to that of the last page the user visited or, if history.pushState
() has been used to add a history entry to the history stack, that history entry is used instead. Bubbles Yes Cancelable No Interface PopStateEvent Event handler property onpopstate The history stack If the history entry being activated was created by a call to history.pushState
() or was affected by a call to history.replaceState
(), the popstate event's state property contains a copy of the history entry's state object. These methods and their corresponding events can be used to add data to the hist...
... Browsers tend to handle the popstate event differently on page load. ...
...e event's state property contains a copy of the history entry's state object. These methods and their corresponding events can be used to add data to the history stack which can be used to reconstruct a dynamically generated page, or to otherwise alter the state of the content being presented while remaining on the same Document. Note that just calling history.pushState
() or history.replaceState
() won't trigger a popstate event. The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history.back
() or history.forward
() in JavaScript). Browsers tend to handle the popstate event differently on page load. Chrome (prior to v34) and Safari always emit a popstate event on page load, but Firefox doesn't. Note: When writing functi...
...And 7 more matches
Pseudo-classes - CSS: Cascading Style Sheets
over an element or not). Note: In contrast to pseudo-classes, pseudo-elements can be used to style a specific part of an element. Syntax selector:pseudo-class { property: value; } Like regular classes, you can chain together as many pseudo-classes as you want in a selector. ...
...eudo-class { property: value; } Like regular classes, you can chain together as many pseudo-classes as you want in a selector. ...
...perty: value; } Like regular classes, you can chain together as many pseudo-classes as you want in a selector. ...
...And 7 more matches
<basic-shape> - CSS: Cascading Style Sheets
has its origin at the top-left corner of the reference box, with the x-axis running to the right and the y-axis running downwards. All the lengths expressed in percentages are resolved from the used dimensions of the reference box. Shape functions The following shapes are supported. All <basic-shape> values use functional notation and are defined here using the value definition syntax. inset
() inset( <shape-arg>{1,4} [round <border-radius>]? ) Defines an inset rectangle. When all of the first four arguments are supplied they represent the top, right, bottom and left offsets from the reference box inward that define the positions of the edges of the inset rectangle. These arguments follow the syntax of the margin shorthand, that let you set all four insets with one, two or four v...
...sets with one, two or four values. The optional <border-radius> argument(s) define rounded corners for the inset rectangle using the border-radius shorthand syntax. A pair of insets in either dimension that add up to more than the used dimension (such as left and right insets of 75% apiece) define a shape enclosing no area. For this specification, this results in an empty float area. ...
...Negative values for either radius are invalid. Percentage values here are resolved against the used width (for the rx value) and the used height (for the ry value) of the reference box. ...
...And 7 more matches
DOM onevent handlers - Developer guides
This page focuses on how the latter work. Registering onevent handlers The onevent handlers are properties on certain DOM elements to manage how that element reacts to events. Elements can be interactive (links, buttons, images, forms, and so forth) or non-interactive (such as the base <body> element). Events are actions like: Being clicked Detecting pressed keys Getting focus The onevent handler is usually named with the event it reacts to, like onclick, onkeypress, onfocus, etc. ...
...y> element). Events are actions like: Being clicked Detecting pressed keys Getting focus The onevent handler is usually named with the event it reacts to, like onclick, onkeypress, onfocus, etc. ...
... When an event occurs that applies to an element, each of its event handlers is called to allow them to handle the event, one after another. ...
...And 7 more matches
Constraint validation - Developer guides
h The number of characters (code points) must not exceed the value of the attribute. tooLong constraint violation Constraint validation process Constraint validation is done through the Constraint Validation API either on a single form element or at the form level, on the <form> element itself. The constraint validation is done in the following ways: By a call to the checkValidity
() or reportValidity
() method of a form-associated DOM interface, (HTMLInputElement, HTMLSelectElement, HTMLButtonElement, HTMLOutputElement or HTMLTextAreaElement), which evaluates the constraints only on this element, allowing a script to get this information. The checkValidity
() method returns a Boolean indicating whether the element's value passes its constraints. (This is typically done by the ...
...TMLOutputElement or HTMLTextAreaElement), which evaluates the constraints only on this element, allowing a script to get this information. The checkValidity
() method returns a Boolean indicating whether the element's value passes its constraints. (This is typically done by the user-agent when determining which of the CSS pseudo-classes, :valid or :invalid, applies.) In contrast, the reportValidity
() method reports any constraint failures to the user. By a call to the checkValidity
() or reportValidity
() method on the HTMLFormElement interface. By submitting the form itself. Calling checkValidity
() is called statically validating the constraints, while calling reportValidity
() or submitting the form is called interactively validating the constraints. Note: If the novalidate attribute ...
...method on the HTMLFormElement interface. By submitting the form itself. Calling checkValidity
() is called statically validating the constraints, while calling reportValidity
() or submitting the form is called interactively validating the constraints. Note: If the novalidate attribute is set on the <form> element, interactive validation of the constraints doesn't happen. Calling the submit
() method on the HTMLFormElement interface doesn't trigger a constraint validation. In other words, this method sends the form data to the server even if doesn't satisfy the constraints. Call the click
() method on a submit button instead. Complex constraints using the Constraint Validation API Using JavaScript and the Constraint API, it is possible to implement more complex constraints, for exam...
...And 7 more matches
Default parameters - JavaScript
rn a * b } multiply(5, 2) // 10 multiply(5) // 5 multiply(5, undefined) // 5 Examples Passing undefined vs. other falsy values In the second call in this example, even if the first argument is set explicitly to undefined (though not null or other falsy values), the value of the num argument is still the default. function test(num = 1) { console.log(typeof num) } test
() // 'number' (num is set to 1) test(undefined) // 'number' (num is set to 1 too) // test with other falsy values: test('') // 'string' (num is set to '') test(null) // 'object' (num is set to null) Evaluated at call time The default argument is evaluated at call time. So, unlike (for example) Python, a new object is created each time the function is called. function a...
... (num is set to null) Evaluated at call time The default argument is evaluated at call time. So, unlike (for example) Python, a new object is created each time the function is called. ...
...s evaluated at call time. So, unlike (for example) Python, a new object is created each time the function is called. ...
...And 7 more matches
getter - JavaScript
The get syntax binds an object property to a function that will be called when that property is looked up. 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 {get prop
() { ... } } {get [expression]
() { ... } } Parameters prop The name of the property to bind to the given function. expression Starting with ECMAScript 2015, you can also use expressions for a computed property name to bind to the given function. Description Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring th...
...Note the following when working with the get syntax: It can have an identifier which is either a number or a string; It must have exactly zero parameters (see Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments for more information); It must not appear in an object literal with another get or with a data entry for the same property ({ get x
() { }, get x
() { } } and { x: ..., get x
() { } } are forbidden). Examples Defining a getter on new objects in object initializers This will create a pseudo-property latest for object obj, which will return the last array item in log. const obj = { log: ['example','test'], get latest
() { if (this.log.length === 0) return undefined; return this.log[this.log.length - 1]; } } console...
...log.length - 1]; } } console.log(obj.latest); // "test" Note that attempting to assign a value to latest will not change it. Deleting a getter using the delete operator If you want to remove the getter, you can just delete it: delete obj.latest; Defining a getter on existing objects using defineProperty To append a getter to an existing object later at any time, use Object.defineProperty
(). ...
...And 7 more matches
DataView - JavaScript
r types in a binary ArrayBuffer, without having to care about the platform's endianness. Description Endianness Multi-byte number formats are represented in memory differently depending on machine architecture -- see Endianness for an explanation. DataView accessors provide explicit control of how data is accessed, regardless of the executing computer's endianness. ...
...architecture -- see Endianness for an explanation. DataView accessors provide explicit control of how data is accessed, regardless of the executing computer's endianness. var littleEndian = (function
() { var buffer = new ArrayBuffer(2); new DataView(buffer).setInt16(0, 256, true /* littleEndian */); // Int16Array uses the platform's endianness. return new Int16Array(buffer)[0] === 256; })
(); console.log(littleEndian); // true or false 64-bit Integer Values Because JavaScript does not currently include standard support for 64-bit integer values, DataView does not offer native 64-bit operations. As a workaround, you could implement your own getUint64
() function to obtain a value with precision up to Number.MAX_SAFE_INTEGER, which could suffice for certain cases. function getUint64...
... Instance properties DataView.prototype.buffer The ArrayBuffer referenced by this view. Fixed at construction time and thus read only. DataView.prototype.byteLength The length (in bytes) of this view from the start of its ArrayBuffer. Fixed at construction time and thus read only. DataView.prototype.byteOffset The offset (in bytes) of this view from the st...
...And 7 more matches
Comparing Reflect and Object methods - JavaScript
n Object, which predates ES2015. Although some of the methods appear to be similar in their behavior, there are often subtle differences between them. The table below details the differences between the methods available on the Object and Reflect APIs. Please note that if a method does not exist in an API, it is marked as N/A. Method Name Object Reflect defineProperty
() Object.defineProperty
() returns the object that was passed to the function. Returns a TypeError if the property was not successfully defined on the object. Reflect.defineProperty
() returns true if the property was defined on the object and false if it was not. defineProperties
() Object.defineProperties
() returns the objects that were passed to the function. Returns a TypeError i...
...eturns a TypeError if the property was not successfully defined on the object. Reflect.defineProperty
() returns true if the property was defined on the object and false if it was not. defineProperties
() Object.defineProperties
() returns the objects that were passed to the function. Returns a TypeError if any properties were not successfully defined on the object. N/A set
() N/A Reflect.set
() returns true if the property was set successfully on the object and false if it was not. Throws a TypeError if the target was not an Object. get
() N/A Reflect.get
() returns the value of the property. Throws a TypeError if the target was not an Object. ...
... if any properties were not successfully defined on the object. N/A set
() N/A Reflect.set
() returns true if the property was set successfully on the object and false if it was not. Throws a TypeError if the target was not an Object. get
() N/A Reflect.get
() returns the value of the property. Throws a TypeError if the target was not an Object. deleteProperty
() N/A Reflect.deleteProperty
() returns true if the property was deleted from the object and false if it was not. getOwnPropertyDescriptor
() Object.getOwnPropertyDescriptor
() returns a property descriptor of the given property if it exists on the object argument passed in, and returns undefined if it does not exist. However, if an object is not passed in as the first argument, it w...
...And 7 more matches
Lexical grammar - JavaScript
suggestions, or warnings to JavaScript code. This can make it easier to read and understand. They can also be used to disable code to prevent it from being executed; this can be a valuable debugging tool. JavaScript has two long-standing ways to add comments to code. The first way is the // comment; this makes all text following it on the same line into a comment. ...
...tand. They can also be used to disable code to prevent it from being executed; this can be a valuable debugging tool. JavaScript has two long-standing ways to add comments to code. The first way is the // comment; this makes all text following it on the same line into a comment. For example: function comment
() { // This is a one line JavaScript comment console.log('Hello world!'); } comment
(); The second way is the /* */ style, which is much more flexible. For example, you can use it on a single line: function comment
() { /* This is a one line JavaScript comment */ console.log('Hello world!'); } comment
(); You can also make multiple-line comments, like this: function comment
() { /* This comment spans multiple lines. Notice that we don't need to end the comment until w...
...ore flexible. For example, you can use it on a single line: function comment
() { /* This is a one line JavaScript comment */ console.log('Hello world!'); } comment
(); You can also make multiple-line comments, like this: function comment
() { /* This comment spans multiple lines. Notice that we don't need to end the comment until we're done. ...
...And 7 more matches
for...of - JavaScript
'b', 2] // ['c', 3] for (const [key, value] of iterable) { console.log(value); } // 1 // 2 // 3 Iterating over a Set const iterable = new Set([1, 1, 2, 2, 3, 3]); for (const value of iterable) { console.log(value); } // 1 // 2 // 3 Iterating over the arguments object You can iterate over the arguments object to examine all of the parameters passed into a JavaScript function: (function
() { for (const argument of arguments) { console.log(argument); } })(1, 2, 3); // 1 // 2 // 3 Iterating over a DOM collection Iterating over DOM collections like NodeList: the following example adds a read class to paragraphs that are direct descendants of an article: // Note: This will only work in platforms that have // implemented NodeList.prototype[Symbol.iterator] const articleParag...
... only work in platforms that have // implemented NodeList.prototype[Symbol.iterator] const articleParagraphs = document.querySelectorAll('article > p'); for (const paragraph of articleParagraphs) { paragraph.classList.add('read'); } Closing iterators In for...of loops, abrupt iteration termination can be caused by break, throw or return. In these cases, the iterator is closed. ...
...ototype[Symbol.iterator] const articleParagraphs = document.querySelectorAll('article > p'); for (const paragraph of articleParagraphs) { paragraph.classList.add('read'); } Closing iterators In for...of loops, abrupt iteration termination can be caused by break, throw or return. In these cases, the iterator is closed. ...
...And 7 more matches
var - JavaScript
clared 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 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 i...
...operties to the global object. Unqualified identifier assignments The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global.. So you can just type: function foo
() { String('s') // Note the function `String` is implicitly visible } ...because globalThis.hasOwnProperty('String') // true So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String, you can just type the unqualified String. The corollary, in non-strict mode, is that assignment to unqualified identifiers will, if there is no variabl...
...at the top of their scope (the top of global code and the top of function code) so it's clear which variables are function scoped (local) and which are resolved on the scope chain. It's important to point out that the hoisting will affect the variable declaration, but not its value's initialization. ...
...And 7 more matches
Codecs used by WebRTC - Web media technologies
the potential codecs--and may have multiple profiles or levels supported for a given codec--the first step when configuring codecs for an RTCPeerConnection is to get the list of available codecs. To do this, you first have to establish a connection on which to get the list. There are a couple of ways you can do this. The most efficient way is to use the static method RTCRtpSender.getCapabilities
() (or the equivalent RTCRtpReceiver.getCapabilities
() for a receiver), specifying the type of media as the input parameter. For example, to determine the supported codecs for video, you can do this: codecList = RTCRtpSender.getCapabilities("video").codecs; Now codecList is an array of RTCRtpCodecCapability objects, each describing one codec configuration. Also present in the list will be entries ...
...d error correction (FEC). If the connection is in the process of starting up, you can use the icegatheringstatechange event to watch for the completion of ICE candidate gathering, then fetch the list. let codecList = null; peerConnection.addEventListener("icegatheringstatechange", (event) => { if (peerConnection.iceGatheringState === "complete") { const senders = peerConnection.getSenders
(); senders.forEach((sender) => { if (sender.track.kind === "video") { codecList = sender.getParameters
().codecs; return; } }); } codecList = null; }); The event handler for icegatheringstatechange is established; in it, we look to see if the ICE gathering state is complete, indicating that no further candidates will be collected. The method RTCPeerConnecti...
...s.forEach((sender) => { if (sender.track.kind === "video") { codecList = sender.getParameters
().codecs; return; } }); } codecList = null; }); The event handler for icegatheringstatechange is established; in it, we look to see if the ICE gathering state is complete, indicating that no further candidates will be collected. The method RTCPeerConnection.getSenders
() is called to get a list of all the RTCRtpSender objects used by the connection. With that in hand, we walk through the list of senders, looking for the first one whose MediaStreamTrack indicates that it's track's kind is video, indicating that the track's data is video media. ...
...And 7 more matches
Loading and running WebAssembly code - WebAssembly
ctions directly on the raw stream of bytes coming from the network, cutting out the need for the ArrayBuffer step. So how do we get those bytes into an array buffer and compiled? The following sections explain. Using Fetch Fetch is a convenient, modern API for fetching network resources. ...
... of bytes coming from the network, cutting out the need for the ArrayBuffer step. So how do we get those bytes into an array buffer and compiled? The following sections explain. Using Fetch Fetch is a convenient, modern API for fetching network resources. ...
...bly.instantiateStreaming
() method, which can take a fetch
() call as its first argument, and will handle fetching, compiling, and instantiating the module in one step, accessing the raw byte code as it streams from the server: WebAssembly.instantiateStreaming(fetch('simple.wasm'), importObject) .then(results => { // Do something with the results! }); If we used the older WebAssembly.instantiate
() method, which doesn't work on the direct stream, we'd need an extra step of converting the fetched byte code to an ArrayBuffer, like so: fetch('module.wasm').then(response => response.arrayBuffer
() ).then(bytes => WebAssembly.instantiate(bytes, importObject) ).then(results => { // Do something with the results! ...
...And 7 more matches
page-worker - Archive of obsolete content
Create a permanent, invisible page and access its DOM. Usage The module exports a constructor function Page, which constructs a new page worker. A page worker may be destroyed, after which its memory is freed, and you must create a new instance to load another page. You specify the page to load using the contentURL option to the Page
() constructor. ...
...ption to the Page
() constructor. This can point to a remote file: pageWorker = require("sdk/page-worker").Page({ contentScript: "console.log(document.body.innerHTML);", contentURL: "http://en.wikipedia.org/wiki/Internet" }); It can also point to an HTML file which you've packaged with your add-on. To do this, save the file in your add-on's data directory and create the URL using the data.url
() method of the self module: pageWorker = require("sdk/page-worker").Page({ contentScript: "console.log(document.body.innerHTML);", contentURL: require("sdk/self").data.url("myFile.html") }); From Firefox 34, you can use "./myFile.html" as an alias for self.data.url("myFile.html"). So you can rewrite the above code like this: pageWorker = require("sdk/page-worker").Page({ contentScript: "...
...In the SDK these scripts are called "content scripts" because they're explicitly used for interacting with web content. You can specify one or more content scripts to load into the page using the contentScript or contentScriptFile options to t...
...And 6 more matches
Storing annotations - Archive of obsolete content
This is implemented as a panel that's shown in response to the widget's right-click message. The panel has three new files associated with it: a content-script which builds the pa...
...This is implemented as a panel that's shown in response to the widget's right-click message. The panel has three new files associated with it: a content-script which builds the panel content a simple HTML ...
...mple HTML file used as a template for the panel's content a simple CSS file to provide some basic styling. These three files can all go in a new subdirectory of data which we will call list. ...
...And 6 more matches
Appendix F: Monitoring DOM changes - Archive of obsolete content
eover, mouseout, and friends, which are fired very often while the mouse is moving. Monkey patching In many instances, especially when dealing with chrome code, the best way to modify actions which result in DOM mutations is by wrapping the functions that trigger those changes. ...
...ode, the best way to modify actions which result in DOM mutations is by wrapping the functions that trigger those changes. For instance, when you want to modify the result of DOM mutations that you know are the result of the doAwesomeDOMStuff
() function, you can wrap it as follows: { let originalDoAwesomeDOMStuff = doAwesomeDOMStuff; doAwesomeDOMStuff = function _doAwesomeDOMStuff
() { let res = originalDoAwesomeDOMStuff.apply(this, arguments); doAwesomerDOMStuff(res, arguments); return res; }; } Now, whenever doAwesomeDOMStuff
() is called, the original function will be called, followed by your own doAwesomerDOMStuff
() function, which can then further modify the DOM as needed. Variations on this method include modifying the arguments passed ...
... callback.call(this, event); } style.textContent = ' ' + preamble + selector + '{' + properties + '}'; (doc.head || doc.documentElement).appendChild(style); // This will only work in chrome privileged code. Content code // should make do without weak references. ...
...And 6 more matches
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
: jsonToDOM.namespaces[reElemNameParts[1]], shortName: reElemNameParts[2] }; } // Note that 'elemNameOrArray' is: either the full element name (eg. [html:]div) or an array of elements in JSON notation function tag(elemNameOrArray, elemAttr) { // Array of elements? Parse each one... ...
...When using the jQuery constructor, only empty tags should be specified in order to avoid invoking the DOM parser. var href = "http://www.google.com/"; var text = "Google"; $("body").append( $("<div>", { class: "foo" }) .append($("<a>", { href: href, text: text }) .click(function (event) { a...
... 'here is text of label, click this text will check the box' ] ] ] ]; document.body.appendChild(jsonToDOM(json, document, {})); jQuery Templating For extensions which already use jQuery, it is possible to use its builtin DOM building functions for templating, though care must be taken when passing non-static strings to methods such as .append
() and .html
(). In most cases, .text
() should be used instead of the latter. When using the jQuery constructor, only empty tags should be specified in order to avoid invoking the DOM parser. var href = "http://www.google.com/"; var text = "Google"; $("body").append( $("<div>", { class: "foo" }) .append($("<a>", { href: href, text: text }) .click(function (event) { alert(event.t...
...And 6 more matches
Tabbed browser - Archive of obsolete content
ed to wait until the content has finished loading. // WRONG WAY (the page hasn't finished loading yet) var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/")); alert(newTabBrowser.contentDocument.body.innerHTML); // BETTER WAY var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/")); newTabBrowser.addEventListener("load", function
() { newTabBrowser.contentDocument.body.innerHTML = "<div>hello world</div>"; }, true); (The event target in the onLoad handler will be a 'tab' XUL element). See tabbrowser for getBrowserForTab
(). Note that the code above does not work inside of the Electrolysis (e10s) enabled tabs. Opening a URL in the correct window/tab There are methods available in chrome://browser/content/utilityOverlay.j...
...th the specified URL/URI. function openAndReuseOneTabPerURL(url) { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var browserEnumerator = wm.getEnumerator("navigator:browser"); // Check each browser instance for our URL var found = false; while (!found && browserEnumerator.hasMoreElements
()) { var browserWin = browserEnumerator.getNext
(); var tabbrowser = browserWin.gBrowser; // Check each tab of this browser instance var numTabs = tabbrowser.browsers.length; for (var index = 0; index < numTabs; index++) { var currentBrowser = tabbrowser.getBrowserAtIndex(index); if (url == currentBrowser.currentURI.spec) { // The URL is already opened. Sele...
...umTabs = tabbrowser.browsers.length; for (var index = 0; index < numTabs; index++) { var currentBrowser = tabbrowser.getBrowserAtIndex(index); if (url == currentBrowser.currentURI.spec) { // The URL is already opened. Select this tab. tabbrowser.selectedTab = tabbrowser.tabContainer.childNodes[index]; // Focus *this* browser-window browserWin.focus
(); found = true; break; } } } // Our URL isn't open. Open it now. if (!found) { var recentWindow = wm.getMostRecentWindow("navigator:browser"); if (recentWindow) { // Use an existing browser window recentWindow.delayedOpenTab(url, null, null, null, null); } else { // No browser windows are open, so open a new one. window.open...
...And 6 more matches
XUL user interfaces - Archive of obsolete content
A XUL demonstration Make a new XUL document as a plain text file, doc7.xul. ...
...onstration"/> <vbox> <groupbox class="demo-group"> <caption label="Day of week calculator"/> <grid> <columns> <column/> <column/> </columns> <rows> <row> <label class="text-prompt" value="Date:" accesskey="D" control="date-text"/> <textbox id="date-text" type="timed" timeout="750" oncommand="refresh
();"/> </row> <row> <label value="Day:"/> <hbox id="day-box"> <label class="day" value="Sunday" disabled="true"/> <label class="day" value="Monday" disabled="true"/> <label class="day" value="Tuesday" disabled="true"/> <label class="day" value="Wednesday" disabled="true"/> <label class="day" value="Thur...
...Copy and paste the content from here, making sure that you scroll to get all of it: /*** XUL demonstration ***/ window { -moz-box-align: start; backgro...
...And 6 more matches
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
n, you will need to add the library MozillaInterfaces.jar (located in xulrunner/sdk/lib folder) to your classpath. This library provides the interfaces necessary to bootstrap Mozilla and call XPCOM methods. To start embedding, we use the methods provided by the Mozilla singleton class. ...
...wing FileNotFoundExceptions during the getGREPathWithProperties(...) call, check whether you already registered the GRE on your system: GRE Registration The initEmbedding method kicks off the embedding process, allowing the Java application to work with XPCOM and Mozilla. Once the Java application is done using Mozilla, it needs to terminate the embedding process: try { mozilla.termEmbedding
(); } catch (XPCOMException e) { // this exception is thrown if termEmbedding failed } Working with XPCOM objects Now that Mozilla is embedded, the Java application can work with XPCOM objects. The Mozilla class provides several methods to facilitate this, such as getServiceManager, getComponentManager, and newLocalFile. In addition to retrieving and calling methods on XPCOM objects, JavaXPC...
...Mozilla is embedded, the Java application can work with XPCOM objects. The Mozilla class provides several methods to facilitate this, such as getServiceManager, getComponentManager, and newLocalFile. In addition to retrieving and calling methods on XPCOM objects, JavaXPCOM allows the Java application to pass Java class objects to XPCOM methods. ...
...And 6 more matches
Supporting private browsing mode - Archive of obsolete content
s a browser:purge-session-history notification that is sent when the browser purges private data that extensions can watch in order to know when it's time to do the same. A private browser listener helper object This helper object registers listeners for private browsing mode changes. This handles interacting with the private browsing service so you don't have to. ...
...e-session-history notification that is sent when the browser purges private data that extensions can watch in order to know when it's time to do the same. A private browser listener helper object This helper object registers listeners for private browsing mode changes. This handles interacting with the private browsing service so you don't have to. ...
... object This helper object registers listeners for private browsing mode changes. This handles interacting with the private browsing service so you don't have to. ...
...And 6 more matches
Building accessible custom components in XUL - Archive of obsolete content
aining issue is that when the spreadsheet regains focus (by pressing SHIFT-TAB, or cycling all the way around the tab order and coming back into the spreadsheet), we need to programmatically reset the focus to the previously focused cell. This is handled in the spreadsheet_focus function, which is registered as a handler for the focus event. ...
...<code> <window id="accjax" title="AccJax Spreadsheet" xmlns="http://www.mozilla.org/keymaster/gatekeeper/ther...
...<code> <window id="accjax" title="AccJax Spreadsheet" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:x2="http://www.w3.org/TR/xhtml2" xmlns:wairole="http://www.w3.org/2005/01/wai-...
...And 6 more matches
Sorting and filtering a custom tree view - Archive of obsolete content
of simplicity, strings are not localized and the data loaded is hard coded. Because of bug 340478, this code will only work from privileged script. ...
...ow title="Sorting a custom tree view example" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="init
()"> <script type="application/javascript" src="sort.js"/> <hbox align="center" id="search-box"> <label accesskey="F" control="filter">Filter</label> <textbox id="filter" oninput="inputFilter(event)" flex="1"/> <button id="clearFilter" oncommand="clearFilter
()" label="Clear" accesskey="C" disabled="true"/> </hbox> <tree id="tree" flex="1" persist="sortDirection sortResource" sortDirection="ascending" sortResource="description"> <treecols> <treecol id="name" label="Name" flex="1" persist="width ordinal hidden" onclick="sort(this)" class="sortDirectionIndicator" sortDirection="ascending"/> <splitter class="tree-splitter"/> <treecol id="desc...
...ordinal hidden" onclick="sort(this)" class="sortDirectionIndicator"/> <splitter class="tree-splitter"/> <treecol id="weapon" label="Weapon" flex="1" persist="width ordinal hidden" onclick="sort(this)" class="sortDirectionIndicator"/> </treecols> <treechildren id="tree-children"/> </tree> </window> sort.js var table = null; var data = null; var tree; var filterText = ""; function init
() { tree = document.getElementById("tree"); loadTable
(); } //this function is called every time the tree is sorted, filtered, or reloaded function loadTable
() { //remember scroll position. this is useful if this is an editable table //to prevent the user from losing the row they edited var topVisibleRow = null; if (table) { topVisibleRow = getTopVisibleRow
(); } if (data == null) { //pu...
...And 6 more matches
Install Scripts - Archive of obsolete content
s. The installer script must be called install.js and must be placed at the top level of the installer archive. The script will contain JavaScript code which calls a number of install functions. In an HTML document, or a XUL document, the window object is the root global object. That means that you can call the methods of the window object with the qualifier before it, which means that window.open
() can simply be written open
(). In an install script, there is no associated window, however the global object will be an Install object which contains a number of functions to customize the install process. Some of the Install object's functions will be described below. The install script should take the following steps: Initialize the installation by specifying what package and version is bein...
...kage Name Replace the word Author with your name and replace the Package Name with the name of the package that you are installing. For example: /Xulplanet/Find Files /Netscape/Personal Security Manager The first example is what we'll use for the find files dialog. The second is the key used for the Personal Security Manager. Install Initialization The Install object has a function, initInstall
() which can be used to initialize for the installation. It should be called at the beginning of your installation script. The syntax of this function is as follows: initInstall( ''packageName'' , ''regPackage'' , ''version'' ); An example initInstall("Find Files","/Xulplanet/Find Files","0.5.0.0"); The first argument is the name of the package in user-readable form. The second argument is the ...
...d argument is the version of the package being installed. Next, we need to set the directory where the files will be installed. There are two ways to do this. The simple method assigns an install directory and installs all files into it. The second method allows you to assign a destination on a per-file (or directory) basis. The first method is described below. The function setPackageFolder
() assigns an installation directory. For the find files dialog, we will install the files into the chrome directory. (We could actually put them anywhere though.) The setPackageFolder
() takes one argument, the directory to install to. For maximum portability, you can't specify a string name for the directory. Instead, you specify an identifier of a known directory and get subdirectories of it. Thus...
...And 6 more matches
NPN_GetURLNotify - Archive of obsolete content
const char* target, void* notifyData); Parameters The function has the following parameters: instance Pointer to the current plug-in instance. url Pointer to the URL of the request. Can be of any type, such as HTTP, FTP, news, or mailto. target Name of the target window or frame, or one of several special target names. For values, see NPN_GetURL
(). ...
...unction has the following parameters: instance Pointer to the current plug-in instance. url Pointer to the URL of the request. Can be of any type, such as HTTP, FTP, news, or mailto. target Name of the target window or frame, or one of several special target names. For values, see NPN_GetURL
(). notifyData Plug-in-private value for associating the request with the subsequent NPP_URLNotify
() call, which passes this value (see Description below). ...
...r values, see NPN_GetURL
(). notifyData Plug-in-private value for associating the request with the subsequent NPP_URLNotify
() call, which passes this value (see Description below). Returns If successful, the function returns NPERR_NO_ERROR. If unsuccessful, the plug-in is not loaded and the function returns an error code. For possible values, see Error Codes. Description NPN_GetURLNotify
() works just like NPN_GetURL
(), with one exception: NPN_GetURLNotify
() notifies the plug-in instance upon successful or unsuccessful completion of the request by calling the plug-in's NPP_URLNotify
() function and passing it the notifyData value. NPN_GetURLNotify
() typically handles the URL request asynchronously. It returns immediately and only later handles the request and calls NPP_URLNotify
(). ...
...And 6 more matches
NPN_RequestRead - Archive of obsolete content
Syntax #include <npapi.h> NPError NPN_RequestRead(NPStream* stream, NPByteRange* rangeList); Parameters The function has the following parameters: stream Stream of type NP_SEEK from which to read bytes. ...
...Syntax #include <npapi.h> NPError NPN_RequestRead(NPStream* stream, NPByteRange* rangeList); Parameters The function has the following parameters: stream Stream of type NP_SEEK from which to read bytes. ...
...n the form of a linked list of NPByteRange objects, each of which specifies a request for a range of bytes. Returns If successful, the function returns NPERR_NO_ERROR. If unsuccessful, the function returns an error code. For possible values, see Error Codes. Description For a seekable stream, the browser sends data only in response to requests by the plug-in. The plug-in calls NPN_RequestRead
() to request data from a seekable stream. The plug-in can use this function to make one or more requests for ranges of bytes. These requests result in subsequent calls to NPP_WriteReady
() and NPP_Write
(). For multiple requests, the function creates a linked list of NPByteRange structures, each of which represents a separate request. If the plug-in requests multiple ranges (either through a list of ...
...And 6 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
wsers which do not support the level of JavaScript used in your content to turn off JavaScript in order to be able to use your content. You can do this by providing an error message for users of older browsers as well as alternative content contained in NOSCRIPT tags. <HTML> <HEAD> <TITLE>NOSCRIPT</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> window.onerror = function
() { // redirect user to a page describing the limitations // of their browser and requesting that they turn off // JavaScript in order to view your site. } // Netscape Navigator 4 will throw an error // on any JavaScript which attempts to use // try ... catch exception processing. try { // Code to implement fancy Menu ...
...ar level. For example, it is conceivable that someday there will exist branch tags similar to 2.2.0 and 2.12.36. Since these values are strings, it is not possible to use relative string comparisons to determine which branch tag came later. In our example, branch 2.2.0 was created before 2.12.36 however comparing these values as strings shows '2.2.0' > '2.12.36'. ...
...ne which branch tag came later. In our example, branch 2.2.0 was created before 2.12.36 however comparing these values as strings shows '2.2.0' > '2.12.36'. The JavaScript function geckoGetRv
() provides one solution to this problem by converting the branch tag in the user agent string into a floating point number where each level of the branch tag is considered as a number from 0-99. ...
...And 6 more matches
New in JavaScript 1.8.5 - Archive of obsolete content
The following is a changelog for JavaScript 1.8.5. This version was included in Firefox 4. New features in JavaScript 1.8.5 New functions Function Description Object.create
() Creates a new object with the specified prototype object and properties. ...
...This version was included in Firefox 4. New features in JavaScript 1.8.5 New functions Function Description Object.create
() Creates a new object with the specified prototype object and properties. bug 492840 Object.defineProperty
() Adds the named property described by a given descriptor to an object. Object.defineProperties
() Adds the named properties described by the given descriptors to an object. Object.getOwnPropertyDescriptor
() Returns a property descriptor for a named property on an object. bug 505587 ...
...d property described by a given descriptor to an object. Object.defineProperties
() Adds the named properties described by the given descriptors to an object. Object.getOwnPropertyDescriptor
() Returns a property descriptor for a named property on an object. bug 505587 Object.keys
() Returns an array of all enumerable properties on an object. bug 307791 Object.getOwnPropertyNames
() Returns an array of all enumerable and non-enumerable properties on an object. bug 518663 Object.preventExtensions
() Prevents any extensions of an object. bug 492849 O...
...And 6 more matches
Building up a basic demo with the PlayCanvas engine - Game development
. Before reading on, copy this code to a new text file and save it in your working directory as index.html. PlayCanvas application To begin developing our game we have to create the PlayCanvas application first (using the given <canvas> element), and then start the update loop. Add the following code to the bottom of your second <script> element: var app = new pc.Application(canvas); app.start
(); The pc global object contains all the PlayCanvas functions available in the engine. Next, we'll set the Canvas to fill the window, and automatically change its resolution to be the same as the Canvas size. Again, add the following lines at the bottom of your script. app.setCanvasFillMode(pc.FILLMODE_FILL_WINDOW); app.setCanvasResolution(pc.RESOLUTION_AUTO); Camera Now when the setup code ...
...d the following lines at the bottom of your script. app.setCanvasFillMode(pc.FILLMODE_FILL_WINDOW); app.setCanvasResolution(pc.RESOLUTION_AUTO); Camera Now when the setup code is in place we need to think about implementing the standard scene components: camera, lights and objects. Let's start with the camera -- add these lines to your code, below the previous ones. var camera = new pc.Entity
(); camera.addComponent("camera", { clearColor: new pc.Color(0.8, 0.8, 0.8) }); app.root.addChild(camera); camera.setPosition(0, 0, 7); The code above will create a new Entity. Note: An Entity is any object used in the scene -- it can be an object like a box, cylinder or cone, but it can also be a camera, light or sound source. Then it adds a camera component to it with the light gray cle...
...itives that you can use to create shapes instantly in a single line of code. There are cubes, spheres, cylinders and more complicated shapes available. Drawing everything for given shape is taken care of by the engine, so we can focus on the high level coding. Let's start by defining the geometry for a cube shape -- add the following new code below your previous additions: var box = new pc.Entity
(); box.addComponent("model", { type: "box" }); app.root.addChild(box); box.rotate(10, 15, 0); It will create an Entity with the box model component and add it to the root of the application, our scene. We also rotate the box a bit to show that it's actually a 3D cube and not a square. The cube is visible, but it is completely. To make it look better we need to shine some light onto it. Lights ...
...And 6 more matches
Building up a basic demo with Three.js - Game development
enderer.setSize(WIDTH, HEIGHT); renderer.setClearColor(0xDDDDDD, 1); document.body.appendChild(renderer.domElement); We are creating a new WebGL renderer, setting its size to fit the whole available space on the screen, and appending the DOM structure to the page. You might have noticed the antialias parameter in the first line -- this renders the edges of shapes more smoothly. The setClearColor
() method sets our background to a light gray colour, instead of the default black one. Add this code into our second <script> element, just below the JavaScript comment. Scene A scene is the place where everything happens. When creating new objects in the demo, we add them all inside the scene to become visible on the screen. In three.js, the scene is represented by a Scene object. Let's create ...
...Add this code into our second <script> element, just below the JavaScript comment. Scene A scene is the place where everything happens. When creating new objects in the demo, we add them all inside the scene to become visible on the screen. In three.js, the scene is represented by a Scene object. Let's create it, by adding the following line below our previous lines: var scene = new THREE.Scene
(); Later, we will be using the .add
() method, to add objects to this scene. Camera We have the rendered scene, but we still need to add a camera to view our handiwork -- imagine a movie set without any cameras. The following lines put the camera in place in the 3D coordinate system, and point it in the direction of our scene, so we can finally see something: var camera = new THREE.PerspectiveC...
...e values and see how they change what you see in the scene. Note: The distance values (e.g. for the camera z position) are unitless, and can be anything you deem suitable for your scene: milimeters, meters, feet, or miles. It's up to you. Rendering the scene Everything is ready, but we still can't see anything. Although we've set-up the renderer, we still need to render everything. Our render
() function will do this job, with a little help from requestAnimationFrame
(), which causes the scene to be re-rendered constantly on every frame: function render
() { requestAnimationFrame(render); renderer.render(scene, camera); } render
(); On every new frame the render function is invoked, and the renderer renders the scene and the camera. Right after the function declaration, we're invoking ...
...And 6 more matches
Finishing up - Game development
sh the game. We could also improve our code rendering. Giving the player some lives Implementing lives is quite straightforward. ...
...ve our code rendering. Giving the player some lives Implementing lives is quite straightforward. ...
...below the drawScore
() function: function drawLives
() { ctx.font = "16px Arial"; ctx.fillStyle = "#0095DD"; ctx.fillText("Lives: "+lives, canvas.width-65, 20); } Instead of ending the game immediately, we will decrease the number of lives until they are no longer available. We can also reset the ball and the paddle positions when the player begins with their next life. ...
...And 6 more matches
Embedding Tips
ge? Get thensIWebNavigation interface on your webbrowser and call the loadURI method with the appropriate URI and flags. This interface also has methods for reloading, stopping a load and going back and forward in the history. How do I block a load? Implement the nsIWebProgressListener interface and register it with the appropriate web browser object via the nsIWebBrowser::addWebBrowserListener
() method. Use the callbacks for after-the-fact cancellation. Alternatively, implement a nsIURIContentListener as described below. How do I watch/intercept a load before it happens? Implement the nsIURIContentListener interface, and register it with the appropriate web browser object via the nsIWebBrowser::parentURIContentListener attribute. Watch for changes in nsIURIContentListener::OnStartURIOp...
...ethod. Use the callbacks for after-the-fact cancellation. Alternatively, implement a nsIURIContentListener as described below. How do I watch/intercept a load before it happens? Implement the nsIURIContentListener interface, and register it with the appropriate web browser object via the nsIWebBrowser::parentURIContentListener attribute. Watch for changes in nsIURIContentListener::OnStartURIOpen
(). You can abort the URI load at this point if you don't want it to proceed. If necessary you may also implement the nsIURIContentListener::IsPreferred
(), returning PR_TRUE to ensure you are always the preferred URI handler and are called no matter what the content type. How do I copy items to the clipboard? Obtain the nsIClipboardCommands interface from the appropriate web browser object via ns...
...t want it to proceed. If necessary you may also implement the nsIURIContentListener::IsPreferred
(), returning PR_TRUE to ensure you are always the preferred URI handler and are called no matter what the content type. How do I copy items to the clipboard? Obtain the nsIClipboardCommands interface from the appropriate web browser object via nsIServiceProvider::GetInterface (or the do_GetInterface
() helper method). How do I save a document or data to disk? Query for the nsIWebBrowserPersist interface implemented on the web browser object and call the saveURI
() or saveDocument
() methods on that. Alternatively, create a standalone webbrowser persist object and call the nsIWebBrowserPersist interface on that to save URIs and documents. This is recommended if you intend anything other than th...
...And 6 more matches
Infallible memory allocation
ays successfully return the requested block of memory. This is in contrast to a traditional, fallible memory allocator that can return null indicating that the request failed. Currently, while code is transitioned to be compatible with infallible memory allocators, you have to explicitly decide whether to use infallible allocation or not. Eventually, however, the generic memory allocators (malloc
() and realloc
()) will become infallible. How can memory allocation be infallible? The term "infallible" means that your memory allocation request is guaranteed to succeed: your code can never see a failed request, and so doesn't need to check for failure. Inside the allocation routine, the situation is different. Under extreme memory conditions, it's possible that the allocation will fail; howev...
...ory management system will do everything it can to find the memory you've asked for. ...
...ng malloc
() for example), and check the result to be sure it's not null. You should do this for large memory allocations because in extremely low memory conditions, as described in How can memory allocation be infallible?, the application may terminate if an infallible allocator can't find the memory you requested. If you don't know whether or not the memory will be large, use the standard malloc
() routine. Be sure to check the result for null. Be warned that any allocation that's controlled by the user or web content may grow bigger than you expect; people and pages do surprising things all the time! When instantiating objects, the new operator creates them infallibly by default. If you want to allocate them fallibly, use the syntax new (fallible) Foo
(). When in doubt, use the infallible...
...And 6 more matches
Downloads.jsm
load, you can use this to verify if ex instanceof Downloads.Error, before reading the exception properties with the error details. Example (using Task.jsm): try { yield Downloads.fetch(sourceUri, targetFile); } catch (ex if ex instanceof Downloads.Error && ex.becauseTargetFailed) { console.log("Unable to write to the target file, ignoring the error."); } Methods createDownload
() Creates a new Download object. Promise<Download> createDownload( Object aProperties ); Parameters aProperties Provides the initial properties for the newly created download. This matches the serializable representation of a Download object. Some of the most common properties in this object include: source: String containing the URI for the download source. Alternatively, may be an n...
...IFile, a DownloadTarget object, or an object with the following properties: path: String containing the path of the target file. saver: Optional String representing the class of the download operation. If omitted, defaults to "copy". Alternatively, may be the serializable representation of a DownloadSaver object. Promise resolves to The newly created Download object. fetch
() Downloads data from a remote network location to a local file. This download method does not provide user interface or the ability to cancel or restart the download programmatically. For that, you should obtain a reference to a Download object using the createDownload
() function. Since the download cannot be restarted, any partially downloaded data will not be kept in case the download fails. ...
... of this function. You may pass an object with a subset of the following fields: isPrivate: Optional Indicates whether the download originated from a private window. If omitted, the download is public. Promise resolves to undefined when the download has finished successfully and you can access the target file. Promise can be rejected with DownloadError if the download failed. getList
() Retrieves the specified type of DownloadList object. There is one download list for each type, and this method always retrieves a reference to the same download list when called with the same argument. Calling this function may cause the download list to be reloaded from the previous session, if it wasn't loaded already. Promise<DownloadList> getList(aType); Parameters aType This can be ...
...And 6 more matches
Interfacing with the Add-on Repository
_RESULTS%/%OS%/%VERSION%?src=firefox"); prefsService.savePrefFile(null); } This fetches the value of the extensions.getAddons.recommended.url preference, and, if the preference doesn't exist or has no value, sets the value of the preference to the correct one for the AMO site. Starting a request To start a search of the repository, you can use either of the following methods: searchAddons
() Queries the add-on repository for add-ons matching given search criteria. retrieveRecommendedAddons
() Retrieves a list of recommended add-ons, as determined by the AMO site administrators. This example will use the latter, in order to randomly select a recommended add-on and offer to install it. However, the code to perform a search term based query would be very similar. When the user clic...
...request: AddonRepository.retrieveRecommendedAddons(10, this); This asks the repository to fetch up to 10 add-ons, using the object this as the target for callbacks. The callback object needs to implement the SearchCallback interface, providing the methods that get called when a search either fails or completes successfully. ...
...ither fails or completes successfully. Handling failed requests The callback object must have a searchFailed
() method; this gets called when a repository search fails to execute. The most common cause of failure (other than the search URL preference being incorrect) is if there is already a pending request, since only one request can be in progress at a time. For example: searchFailed: function
() { this.showNotification("I have no recommendations for you right now!", "Oh noes!", null); }, Here, we call a showNotification
() method with some parameters that we'll look at shortly when we get to our showNotification
() method below. ...
...And 6 more matches
Index
ce, Reference, Reference(2), SpiderMonkey JS::Construct calls a specified function as a constructor, fun. 36 JS::CreateError JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::CreateError creates an Error object with specified properties. 37 JS::CurrentGlobalOrNull JSAPI Reference, Reference, Reference(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...
... JS_GetArrayLength gets the .length property of obj as though by calling JS_GetProperty and converts it to a 32-bit unsigned integer. If obj is an array (see JS_IsArrayObject), this is guaranteed to succeed, because the .length property of an array is always a number and can't be deleted or redefined. 279 JS_GetArrayPrototype JSAPI Reference, SpiderMonkey JS_GetArrayPrototype
() retrieves the original Array.prototype of a specified object, obj. If an error occurs, it returns NULL. 280 JS_GetClass JSAPI Reference, SpiderMonkey JS_GetClass returns a pointer to the JSClass associated with a specified JS object, obj. The application must treat the JSClass as read-only. If obj has no JSClass, this returns NULL. 281 JS_GetClassObject JSAPI ...
...the name of a function, or the string "anonymous", which indicates that the function was not assigned a name when created. 300 JS_GetFunctionObject JSAPI Reference, SpiderMonkey JS_GetFunctionObject returns the JavaScript Function object for a specified function pointer, fun. 301 JS_GetFunctionPrototype JSAPI Reference, SpiderMonkey JS_GetFunctionPrototype
() retrieves the original Function.prototype of a specified object, obj. If an error occurs, it returns NULL. 302 JS_GetFunctionScript JSAPI Reference, Reference, Reference(2), SpiderMonkey JS_GetFunctionScript returns a pointer to JSScript for the specified function, fun. If fun is a native function, it returns NULL. 303 JS_GetGCParameter JSAPI Reference, Spider...
...And 6 more matches
JS::CompileOptions
Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. version JSVersion JavaScript version used to compile the script. ...
...equires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. version JSVersion JavaScript version used to compile the script. Methods Some methods of JS::OwningCompileOptions and JS::CompileOptions return the instance itself to allow method chain. Methods of JS::ReadOnlyCompileOptions Method Description bool mutedErrors
() const Determines if errors are muted. The Web Platform allows scripts to be loaded from arbitrary cross-origin sources. This allows an attack by which a malicious website loads a sensitive file (say, a bank statement) cross-origin (using the user's cookies), and sniffs the generated syntax errors (via a window.onerror handler) for juicy morsels of its contents. To counter this a...
...nerror handler) for juicy morsels of its contents. To counter this attack, HTML5 specifies that script errors should be sanitized ("muted") when the script is not same-origin with the global for which it is loaded. Callers should set this flag for cross-origin scripts, and it will be propagated appropriately to child scripts and passed back in JSErrorReports. ...
...And 6 more matches
Querying Places
laces queries have several basic parts: The query object: nsINavHistoryQuery, holds the search parameters The query options: nsINavHistoryQueryOptions, allows configuration of the search result The history service: nsINavHistoryService, executes the query The first first step is to create the query and options, and fill them with the parameters you want. Use nsINavHistoryService.getNewQuery
() and nsINavHistoryService.getNewQueryOptions
() to retrieve empty objects. The defaults for these objects will result in a query that returns all of your browser history in a flat list: ChromeUtils.defineModuleGetter(this, "PlacesUtils", "resource://gre/modules/PlacesUtils.jsm"); // No query options set will get all history, sorted in database order, // which is nsI...
...r these objects will result in a query that returns all of your browser history in a flat list: ChromeUtils.defineModuleGetter(this, "PlacesUtils", "resource://gre/modules/PlacesUtils.jsm"); // No query options set will get all history, sorted in database order, // which is nsINavHistoryQueryOptions.SORT_BY_NONE. let options = PlacesUtils.history.getNewQueryOptions
(); // No query parameters will return everything let query = PlacesUtils.history.getNewQuery
(); // execute the query let result = PlacesUtils.history.executeQuery(query, options); Result types nsINavHistoryQueryOptions has a resultType property that allows configuration of the grouping and level of detail to be returned in the results. The different values for this property are listed below. ...
...ttribute boolean includeHidden attribute boolean showSessions attribute unsigned long maxResults const unsigned short QUERY_TYPE_HISTORY = 0 const unsigned short QUERY_TYPE_BOOKMARKS = 1 const unsigned short QUERY_TYPE_UNIFIED = 2 (Not yet implemented -- see bug 378798) attribute unsigned short queryType Complex Queries You can pass one or more nsINavHistoryQuery objects to executeQueries
(). Within one query object, all parameters are ANDed together. The conditions for different query objects are then ORed together. This allows for a simpler implementation and interface than a full logical operation with nested clauses while still being expressive. Example of querying for any pages I've visited that contain the word "firefox" in the title/URL or that I've visited today from mozilla...
...And 6 more matches
Using XPCOM Utilities to Make Things Easier
face2) NS_IMPL_ISUPPORTSn(classname, interface1, ..., interfacen) These macros automatically add the nsISupports entry for you, so you don't need to do something like this: NS_IMPL_ISUPPORTS2(classname, interface1, nsISupports) Take a close look at the above example. Note that it uses the actual name of the interface and not an IID. Inside the macro, the interface name expands to NS_GET_IID
(), which is another macro that extracts the IID from the generated header of the interface. When an interface is written in XPIDL, the headers include static declarations of their IIDs. On any interface that is generated by XPIDL, you can call NS_GET_IID
() to obtain the IID which is associated with that interface. // returns a reference to a shared nsIID object\ static const nsIID iid1 = NS_GET_II...
...terface name in all caps will declare all of the methods of that interface for you. For example, NS_DECL_NSIFOO will declare all of the methods of nsIFoo provided that it exists and that nsIFoo.h was generated by the XPIDL compiler. Consider the following real class: class myEnumerator : public nsISimpleEnumerator { public: NS_DECL_ISUPPORTS NS_DECL_NSISIMPLEENUMERATOR myEnumerator
(); virtual ~myEnumerator
() {} }; The declaration of this nsISimpleEnumerator class doesn't include any methods other than the contructor and destructor. Instead, the class uses the NS_DECL_ macro[nsISupports-warning]. Using these declaration macros not only saves a tremendous amount of time when you're writing the code, it can also save time if you make changes to your IDL file, since the C+...
...ros included appears in weblock2.cpp. ...
...And 6 more matches
Components.utils.exportFunction
. A function exported from privileged to less-privileged code can be called from the less privileged code's context. The function has access to its surrounding closure just as if it were being called in the privileged context. 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 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 functio...
...n 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 to assign the return value of exportFunction
() to an object in the target scope. allowCallbacks: deprecated/redundant from Firefox 34. This option allows the exported function to accept callbacks as arguments. Boolean, defaulting to false. This option is new in Firefox 33. From Firefox 34 onwards this option has no effect: the exported function is always able to accept callbacks as arguments. allowCrossOriginArguments: do not check that arg...
... Xray filtering and waiving Xrays provide a filtered view of the original object. For the full details refer ...
...And 6 more matches
nsAString (External)
perator> operator!= EqualsLiteral LowerCaseEqualsLiteral Find RFind FindChar RFindChar AppendInt ToInteger Data Members No public members. Methods BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
...Literal Find RFind FindChar RFindChar AppendInt ToInteger Data Members No public members. Methods BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
... @param newSize Size the string to this length. ...
...And 6 more matches
nsCString external
mpare Equals operator< operator<= operator== operator>= operator> operator!= EqualsLiteral Find RFind FindChar RFindChar AppendInt ToInteger Base Classes nsCStringContainer Data Members No public members. ...
...external(const nsCString_external&) - source Parameters nsCString_external& aString void nsCString_external(const nsACString&) - source Parameters nsACString& aReadable void nsCString_external(const char*, PRUint32) - source Parameters char* aData PRUint32 aLength get char* get
() const - source operator= nsCString_external& operator=(const nsCString_external&) - source Parameters nsCString_external& aString nsACString& operator=(const nsACString&) - source Parameters nsACString& aString nsACString& operator=(const char*) - source Parameters char* aPtr ...
... Adopt void Adopt(const char*, PRUint32) - source Parameters char* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 6 more matches
nsDependentCString external
Equals operator< operator<= operator== operator>= operator> operator!= EqualsLiteral Find RFind FindChar RFindChar AppendInt ToInteger Base Classes nsCString_external Data Members No public members. ...
... Constructors void nsDependentCString_external
() - source void nsDependentCString_external(const char*, PRUint32) - source Parameters char* aData PRUint32 aLength Rebind void Rebind(const char*, PRUint32) - source Parameters char* aData PRUint32 aLength get char* get
() const - source operator= nsCString_external& operator=(const nsCString_external&) - source Parameters nsCString_external& aString nsACString& operator=(const nsACString&) - source Parameters nsACString& aString nsACString& operator=(const char*) - source Parameters char* aPtr ...
... Adopt void Adopt(const char*, PRUint32) - source Parameters char* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 6 more matches
nsDependentString external
< operator<= operator== operator>= operator> operator!= EqualsLiteral LowerCaseEqualsLiteral Find RFind FindChar RFindChar AppendInt ToInteger Base Classes nsString_external Data Members No public members. ...
... void nsDependentString_external
() - source void nsDependentString_external(const PRUnichar*, PRUint32) - source Parameters PRUnichar* aData PRUint32 aLength Rebind void Rebind(const PRUnichar*, PRUint32) - source Parameters PRUnichar* aData PRUint32 aLength get PRUnichar* get
() const - source operator= nsString_external& operator=(const nsString_external&) - source Parameters nsString_external& aString nsAString& operator=(const nsAString&) - source Parameters nsAString& aString nsAString& operator=(const PRUnichar*) - source Parameters PRUnichar* aPtr ...
...st PRUnichar*, PRUint32) - source Parameters PRUnichar* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 6 more matches
nsString external
operator< operator<= operator== operator>= operator> operator!= EqualsLiteral LowerCaseEqualsLiteral Find RFind FindChar RFindChar AppendInt ToInteger Base Classes nsStringContainer Data Members No public members. ...
...const nsString_external&) - source Parameters nsString_external& aString void nsString_external(const nsAString&) - source Parameters nsAString& aReadable void nsString_external(const PRUnichar*, PRUint32) - source Parameters PRUnichar* aData PRUint32 aLength get PRUnichar* get
() const - source operator= nsString_external& operator=(const nsString_external&) - source Parameters nsString_external& aString nsAString& operator=(const nsAString&) - source Parameters nsAString& aString nsAString& operator=(const PRUnichar*) - source Parameters PRUnichar* aPtr ...
...st PRUnichar*, PRUint32) - source Parameters PRUnichar* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 6 more matches
IAccessibleEditableText
strings used with this interface are specified as follows: If startOffset is less than endOffset, the substring starts with the character at startOffset and ends with the character just before endOffset. If endOffset is lower than startOffset, the result is the same as a call with the two arguments exchanged. The whole text can be defined by passing the indices zero and IAccessibleText.nCharacters
(). If both indices have the same value, an empty string is defined. Refer to the @ref _specialOffsets "Special Offsets for use in the IAccessibleText and IAccessibleEditableText Methods" for information about a special offset constant that can be used in IAccessibleEditableText methods. Method overview HRESULT copyText([in] long startOffset, [in] long endOffset ); HRESULT cutText([in] long sta...
...The specified text between the two given indices is copied into the system clipboard. HRESULT copyText( [in] long startOffset, [in] long endOffset ); Parameters startOffset Start index of the text to moved into the clipboard. The valid range is 0..length. endOffset End index of the text to moved into the clipboard. The valid range is 0..length. Ret...
... text between the two given indices is copied into the system clipboard. HRESULT copyText( [in] long startOffset, [in] long endOffset ); Parameters startOffset Start index of the text to moved into the clipboard. The valid range is 0..length. endOffset End index of the text to moved into the clipboard. The valid range is 0..length. Return value E_INVALIDARG if bad [in] passed. S_OK. cutText
() Deletes a range of text and copies it to the clipboard. The text between the two given indices is deleted from the text represented by this object and copied to the clipboard. HRESULT cutText( [in] long startOffset, [in] long endOffset ); Parameters startOffset Start index of the text to be deleted. The valid range is 0..length. endOffset End index of the text to be deleted. The valid range...
...And 6 more matches
imgIDecoderObserver
code only!onDataAvailable Decode notification. Called when there is more to paint. void onDataAvailable( in imgIRequest aRequest, in boolean aCurrentFrame, [const] in nsIntRect aRect ); Parameters aRequest The request on which data is available, or null if being called for an imgIDecoder object. aCurrentFrame Missing Description aRect Missing Description onDiscard
() Called when the decoded image data is discarded. This means that the frames no longer exist in decoded form, and any attempt to access or draw the image will initiate a new series of progressive decode notifications. void onDiscard( in imgIRequest aRequest ); Parameters aRequest The request on which data is available, or null if being called for an imgIDecoder object. onImageIsAnimat...
...alled when the decoded image data is discarded. This means that the frames no longer exist in decoded form, and any attempt to access or draw the image will initiate a new series of progressive decode notifications. void onDiscard( in imgIRequest aRequest ); Parameters aRequest The request on which data is available, or null if being called for an imgIDecoder object. ...
...By the time this callback is been called, the size has been set on the container and STATUS_SIZE_AVAILABLE has been set on the associated imgRequest. ...
...And 6 more matches
nsIApplicationCache
netwerk/base/public/nsIApplicationCache.idlScriptable This interface represents an application cache, which stores resources for offline use. ...
...CacheService.openSession
() method, to access the cache's entries. Each entry in the cache can be marked with a set of types, specified in the Constants section. All application caches with the same group ID belong to a cache group. Each group has one "active" cache that will service future loads. Inactive caches are removed from the cache when no longer referenced. ...
.... Each entry in the cache can be marked with a set of types, specified in the Constants section. All application caches with the same group ID belong to a cache group. Each group has one "active" cache that will service future loads. Inactive caches are removed from the cache when no longer referenced. ...
...And 6 more matches
nsICategoryManager
The category and/or entry are created if they do not exist. string addCategoryEntry( in string aCategory, in string aEntry, in string aValue, ...
...The category and/or entry are created if they do not exist. ...
...ation sessions. You must pass false for this parameter. aReplace A flag indicating whether or not to overwrite the value of an existing category entry. Return value The previous value for the given category entry (if any). Exceptions thrown NS_ERROR_INVALID_ARG This error is returned if aReplace is false and the category entry already has a value, or if aPersist is true. deleteCategory
() Delete a category and all entries. Note: If the category does not exist, then this method does nothing. void deleteCategory( in string aCategory ); Parameters aCategory The name of the category being deleted. deleteCategoryEntry
() Delete an entry from the category. Note: If the category does not exist, then this method does nothing. void deleteCategoryEntry( in string aCategory,...
...And 6 more matches
nsIClipboard
The kSelectionClipboard is peculiar to the X Windows System, where it refers to the PRIMARY selection, which is the one that simple mouse selection and middle-click paste operations are using. ...
... The kSelectionClipboard is peculiar to the X Windows System, where it refers to the PRIMARY selection, which is the one that simple mouse selection and middle-click paste operations are using. Constant Value Description ...
...dows System, where it refers to the PRIMARY selection, which is the one that simple mouse selection and middle-click paste operations are using. Constant Value Description kSelectionClipboard 0 Clipboard for selection. kGlobalClipboard 1 Clipboard for global use. kFindClipboard 2 Clipboard for find strings. ...
...And 6 more matches
nsIContentPrefService
addObserver(in AString aName, in nsIContentPrefObserver aObserver); nsIVariant getPref(in nsIVariant aGroup, in AString aName, [optional] in nsIContentPrefCallback aCallback); nsIPropertyBag2 getPrefs(in nsIVariant aGroup); nsIPropertyBag2 getPrefsByName(in AString aName); boolean hasPref(in nsIVariant aGroup, in AString aName); void removeGroupedPrefs
(); void removeObserver(in AString aName, in nsIContentPrefObserver aObserver); void removePref(in nsIVariant aGroup, in AString aName); void removePrefsByName(in AString aName); void setPref(in nsIVariant aGroup, in AString aName, in nsIVariant aValue); Attributes Attribute Type Description DBConnection mozIStorageConnection ...
...s should generally be added to this unfrozen interface. Also useful for testing the database creation and migration code. Read only. grouper nsIContentURIGrouper The component that the service uses to determine the groups to which URIs belong. By default, this is the "hostname grouper," which groups URIs by full hostname (in otherwords, by site). Read only. Methods addObserver
() Adds an observer that monitors a preference for changes. void addObserver( in AString aName, in nsIContentPrefObserver aObserver ); Parameters aName The name of the preference to observe. You may specify null to add a generic observer that is notified of all preference changes. aObserver The name of an object implementing nsIContentPrefObserver that will receive notification...
... changes. void addObserver( in AString aName, in nsIContentPrefObserver aObserver ); Parameters aName The name of the preference to observe. You may specify null to add a generic observer that is notified of all preference changes. aObserver The name of an object implementing nsIContentPrefObserver that will receive notifications of changes to the preference's value. getPref
() Returns the value of a preference saved for a particular site. Note: Prior to Gecko 2.0, the site could only be specified by nsIURI. Now a string can be used as well. nsIVariant getPref( in nsIVariant aGroup, in AString aName, in nsIContentPrefCallback aCallback Optional ); Parameters aGroup The group for which to retrieve a preference; this may be specified as either a URI or ...
...And 6 more matches
nsIDOMElement
ring localName) void setAttribute(in DOMString name, in DOMString value) nsIDOMAttr setAttributeNode(in nsIDOMAttr newAttr) nsIDOMAttr setAttributeNodeNS(in nsIDOMAttr newAttr) void setAttributeNS(in DOMString namespaceURI, in DOMString qualifiedName, in DOMString value) Attributes Attribute Type Description tagName DOMString The element tag name. Read only. ...
...) void setAttributeNS(in DOMString namespaceURI, in DOMString qualifiedName, in DOMString value) Attributes Attribute Type Description tagName DOMString The element tag name. Read only. Methods getAttribute
() Get an attribute value. DOMString getAttribute( in DOMString name ); Parameters name Attribute name Return value A DOMString containing the attribute value. getAttributeNode
() Get an attribute node. nsIDOMAttr getAttributeNode( in DOMString name ); Parameters name Attribute name Return value A nsIDOMAttr corresponding to the attribute. getAttributeNodeNS
() Get an attribute node in a given namespace. nsIDOMAttr getAttributeNodeNS( in DOMString namespaceURI, in DOMString localName ); Parameters namespaceURI Namespace URI localName Attribute name Return value ...
...OMString name ); Parameters name Attribute name Return value A nsIDOMAttr corresponding to the attribute. getAttributeNodeNS
() Get an attribute node in a given namespace. nsIDOMAttr getAttributeNodeNS( in DOMString namespaceURI, in DOMString localName ); Parameters namespaceURI Namespace URI localName Attribute name Return value A nsIDOMAttr corresponding to the attribute. getAttributeNS
() Get an attribute value in a given namespace. DOMString getAttributeNS( in DOMString namespaceURI, in DOMString localName ); Parameters namespaceURI Namespace URI localName Attribute name Return value A DOMString containing the attribute value. getElementsByTagName
() Get all descendants of a tag name. nsIDOMNodeList getElementsByTagName( in DOMString name ); Parameters name Tag name Re...
...And 6 more matches
nsIMemoryReporterManager
.org/memory-reporter-manager;1"] .getService(Components.interfaces.nsIMemoryReporterManager); Each memory reporter object, which implements nsiMemoryReporter interface, provides information for a given code area. Each code area is identified by a unique path string, which is displayed in about:memory. ...
...Service(Components.interfaces.nsIMemoryReporterManager); Each memory reporter object, which implements nsiMemoryReporter interface, provides information for a given code area. Each code area is identified by a unique path string, which is displayed in about:memory. ...
....nsIMemoryReporterManager); Each memory reporter object, which implements nsiMemoryReporter interface, provides information for a given code area. Each code area is identified by a unique path string, which is displayed in about:memory. ...
...And 6 more matches
nsIPromptService
uttons flags Constant Value Description STD_OK_CANCEL_BUTTONS 513 selects the standard set of OK/Cancel buttons. (BUTTON_TITLE_OK *BUTTON_POS_0) +(BUTTON_TITLE_CANCEL * BUTTON_POS_1) STD_YES_NO_BUTTONS 1027 selects the standard set of Yes/No buttons. (BUTTON_TITLE_YES *BUTTON_POS_0) +(BUTTON_TITLE_NO * BUTTON_POS_1) Methods alert
() alert shows an alert dialog with an OK button. It works the same way as window.alert, but accepts a title for the dialog. You should use this method instead of window.alert in chrome code. void alert( in nsIDOMWindow aParent, in wstring aDialogTitle, in wstring aText ); Parameters aParent The parent window for the dialog, or null, in which case the parent window will be nsIWindowW...
...ome code. void alert( in nsIDOMWindow aParent, in wstring aDialogTitle, in wstring aText ); Parameters aParent The parent window for the dialog, or null, in which case the parent window will be nsIWindowWatcher.activeWindow. aDialogTitle Text to appear in the title of the dialog. aText Text to appear in the body of the dialog. See also the alert_example. alertCheck
() Shows an alert dialog with an OK button and a labeled checkbox. void alertCheck( in nsIDOMWindow aParent, in wstring aDialogTitle, in wstring aText, in wstring aCheckMsg, inout boolean aCheckState ); Parameters aParent The parent window for the dialog. If set to null the parent window will be nsIWindowWatcher.activeWindow. aDialogTitle Text to appear in the title of th...
... aCheckMsg Text to appear with the checkbox. aCheckState Contains the initial checked state of the checkbox when this method is called and the final checked state after this method returns. If you call this method from JavaScript you need to wrap this argument in an object with its 'value' property set to a boolean (or use an empty object). See also the alertCheck_example. confirm
() Shows a dialog with OK and cancel buttons. boolean confirm( in nsIDOMWindow aParent, in wstring aDialogTitle, in wstring aText ); Parameters aParent The parent window for the dialog. If set to null the parent window will be nsIWindowWatcher.activeWindow. aDialogTitle Text to appear in the title of the dialog. aText Text to appear in the body of the dialog. Return ...
...And 6 more matches
nsIScrollable
Scrollbar states Visibility states of a scrollbar. Constant Value Description Scrollbar_Auto 1 Scrollbars visible only when needed. Scrollbar_Never 2 Scrollbars never visible, even when scrolling is still possible. Scrollbar_Always 3 Scrollbars always visible, even when scrolling is not possible. ...
... 3 Scrollbars always visible, even when scrolling is not possible. Methods getCurScrollPos
() Obsolete since Gecko 29.0 (Firefox 29.0 / Thunderbird 29.0 / SeaMonkey 2.26) long getCurScrollPos( in long scrollOrientation ); Parameters scrollOrientation An integer representing the orientation of the scrollbar. Return value getDefaultScrollbarPreferences
() long getDefaultScrollbarPreferences( in long scrollOrientation ); Parameters scrollOrientation An integer representing the orientation of the scrollbar. Return value An integer representing the state of the scrollbar. ...
...); Parameters scrollOrientation An integer representing the orientation of the scrollbar. Return value getDefaultScrollbarPreferences
() long getDefaultScrollbarPreferences( in long scrollOrientation ); Parameters scrollOrientation An integer representing the orientation of the scrollbar. Return value An integer representing the state of the scrollbar. getScrollbarVisibility
() void getScrollbarVisibility( out boolean verticalVisible, out boolean horizontalVisible ); Parameters verticalVisible Boolean specifying the visibility of the vertical scrollbar. ...
...And 6 more matches
nsIXULWindow
efox 4 / Thunderbird 3.3 / SeaMonkey 2.1) An nsIXULWindow is created as part of the creation of a top-level chrome window. When the window is destroyed, it will fire a "xul-window-destroyed" notification through the global observer service. This signals the application in case it needs to quit. ...
...created as part of the creation of a top-level chrome window. When the window is destroyed, it will fire a "xul-window-destroyed" notification through the global observer service. This signals the application in case it needs to quit. ...
... contextFlags PRUint32 contextFlags are from nsIWindowCreator2. docShell nsIDocShell The docshell owning the XUL for this window. Read only. ...
...And 6 more matches
Getting Started Guide
ecause XPCOM interfaces are expressed as abstract C++ base classes, you may be tempted to let C++ handle the differences, or to use C++ casts to navigate between interface types. This is wrong. The only sanctioned way to get between XPCOM types is with QueryInterface. ...
...A given nsCOMPtr does not, however, cooperate in making other owning pointers. ...
...y provides one. // |nsCOMPtr| produces a raw pointer when needed... nsCOMPtr<nsIFoo> foo = ...; // 1. Assigning into a raw pointer nsIFoo* raw_foo = foo; // 2. Assigning into another |nsCOMPtr| nsCOMPtr<nsIFoo> foo2 = foo; // 3. As a parameter SetFoo(foo); // 4. Testing the value in an |if| expression // 5. Calling a member function if ( foo ) foo->DoSomething
(); In all of these cases, pretty much the exact same code is executed (case 2 is slightly different, but the intent is the same). In each case, you are essentially extracting the raw pointer value for your own purpose. If the nsCOMPtr AddRefed the value each time you did that, cases 4 and 5 would obviously always generate leaks. SetFoo, from case 3, would have to be written two differen...
...And 6 more matches
Declaring types
pes that represent a single value in memory, as opposed to arrays, structures, or functions. You can define values of these types without declaring new types. For example, to define a new 32-bit integer variable with the value 5: var i = ctypes.int32_t(5); You can then pass a pointer to this value to a C function that requires a pointer to a 32-bit integer, like this: some_c_function(i.address
()); Declaring new primitive types There are times when you want to create new types that are simply new names for existing primitive types. For example, on Windows, you may wish to be able to use the Windows-standard DWORD type name for unsigned 32-bit integers. To declare this type, you can simply do: const DWORD = ctypes.uint32_t; After doing this, DWORD is a CType that can then be used to ...
...y new names for existing primitive types. For example, on Windows, you may wish to be able to use the Windows-standard DWORD type name for unsigned 32-bit integers. To declare this type, you can simply do: const DWORD = ctypes.uint32_t; After doing this, DWORD is a CType that can then be used to represent 32-bit unsigned integers. Structures Structures are declared using the ctypes.StructType
() constructor. This method accepts as input the name of the structure and an array of field descriptors, each describing one field in the structure. You can, optionally, leave out the field descriptor array; this creates an opaque structure whose contents are not defined. Note: At present, there isn't a way to specify that an array's C equivalent was declared as a packed structure; that is, using ...
...pes.int }, { "tm_year": ctypes.int }, { "tm_wday": ctypes.int }, { "tm_yday": ctypes.int }, { "tm_isdst": ctypes.int } ]); To find other types see here: Predefined Types - Primitive Types. ...
...And 6 more matches
CData
A CData object represents a C value or function located in memory. Method overview Methods available on all CData objects CData address
() String toSource
() String toString
() Properties Properties of all CData objects Property Type Description constructor CType The data type of the CData object, as a CType. Read only. Note: This is never ctypes.void_t or an array type with an unspecified length. value object The JavaScript equivalent of the CData object's value. This will throw a TypeError exception if the value can't be converted. ...
...ription constructor CType The data type of the CData object, as a CType. Read only. Note: This is never ctypes.void_t or an array type with an unspecified length. value object The JavaScript equivalent of the CData object's value. This will throw a TypeError exception if the value can't be converted. Methods available on all CData objects address
() Returns a CData object of the pointer type ctypes.PointerType(dataObject.constructor) whose value points to the C object referred to by the object. This provides a way to get a pointer to the actual data of the C value represented by the CData object. CData address
() Parameters None. Return value A CData object of the pointer type ctypes.PointerType(dataObject.constructor) whose value poin...
...nterType(dataObject.constructor) whose value points to the C object referred to by the object. This provides a way to get a pointer to the actual data of the C value represented by the CData object. CData address
() Parameters None. Return value A CData object of the pointer type ctypes.PointerType(dataObject.constructor) whose value points to the C object referred to by the object. toSource
() Returns the string "t(arg)", where t and arg are 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 t...
...And 6 more matches
Debugger.Script - Firefox Developer Tools
his is the script's display name, if it has one. If the script has no display name -- for example, if it is a top-level eval script -- this is undefined. If the script's function has a given name, its display name is the same as its function's given name. If the script's function has no name, SpiderMonkey attempts to infer an appropriate name for it given its context. ...
...o display name -- for example, if it is a top-level eval script -- this is undefined. If the script's function has a given name, its display name is the same as its function's given name. If the script's function has no name, SpiderMonkey attempts to infer an appropriate name for it given its context. For example: function f
() {} // display name: f (the given name) var g = function
() {}; // display name: g o.p = function
() {}; // display name: o.p var q = { r: function
() {} // display name: q.r }; Note that the display name may not be a proper JavaScript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property. Thus, we use a/b to refer to theb defined ...
... Note that the display name may not be a proper JavaScript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property. Thus, we use a/b to refer to theb defined withina, and a< to refer to a function that occurs somewhere within an expression that is assigned toa. For example: function h
() { var i = function
() {}; // display name: h/i f(function
() {}); // display name: h/< } var s = f(function
() {}); // display name: s< If the instance refers to WebAssembly code, throw a TypeError. url If the instance refers to a JSScript, the filename or URL from which this script's code was loaded. For scripts created by eval or the Function constructor, this may be a syn...
...And 6 more matches
Flame Chart - Firefox Developer Tools
We'll use the same example as in the Call Tree page: a program that compares three different sorting algorithms. There's a separate page that gives an overview of this program's structure. We'll use the same profile file as that used in the Call Tree page. ...
...page: a program that compares three different sorting algorithms. There's a separate page that gives an overview of this program's structure. We'll use the same profile file as that used in the Call Tree page. ...
... algorithms. There's a separate page that gives an overview of this program's structure. We'll use the same profile file as that used in the Call Tree page. ...
...And 6 more matches
AudioWorkletProcessor.process - Web APIs
Important: Currently, audio data blocks are always 128 frames long--that is, they contain 128 32-bit floating-point samples for each of the inputs' channels. ...
... Important: Currently, audio data blocks are always 128 frames long--that is, they contain 128 32-bit floating-point samples for each of the inputs' channels. ...
... Important: Currently, audio data blocks are always 128 frames long--that is, they contain 128 32-bit floating-point samples for each of the inputs' channels. ...
...And 6 more matches
Cache - Web APIs
s workers. 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. Items in a Cache do not get updated unless explicitly requested; they don't expire unless deleted. Use CacheStorage.open
() to open a specific named Cache object and then call any of the Cache methods to maintain the Cache. You are also responsible for periodically purging cache entries. Each browser has a hard limit on the amount of cache storage that a given origin can use. Cache quota usage estimates are available via the StorageEstimate API. The browser does its best to manage disk space, but it may delete the Ca...
...ptions) Returns a Promise that resolves to the response associated with the first matching request in the Cache object. Cache.matchAll(request, options) Returns a Promise that resolves to an array of all matching requests in the Cache object. Cache.add(request) Takes a URL, retrieves it and adds the resulting response object to the given cache. This is functionally equivalent to calling fetch
(), then using put
() to add the results to the cache. Cache.addAll(requests) Takes an array of URLs, retrieves them, and adds the resulting response objects to the given cache. Cache.put(request, response) Takes both a request and its response and adds it to the given cache. Cache.delete(request, options) Finds the Cache entry whose key is the request, returning a Promise that resolves to true...
...y is the request, returning a Promise that resolves to true if a matching Cache entry is found and deleted. If no Cache entry is found, the promise resolves to false. Cache.keys(request, options) Returns a Promise that resolves to an array of Cache keys. Examples This code snippet is from the service worker selective caching sample. (see selective caching live) The code uses CacheStorage.open
() to open any Cache objects with a Content-Type header that starts with font/. The code then uses Cache.match
() to see if there's already a matching font in the cache, and if so, returns it. If there isn't a matching font, the code fetches the font from the network and uses Cache.put
() to cache the fetched resource. The code handles exceptions thrown from the fetch
() operation. Note that an HTTP ...
...And 6 more matches
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 ...
...on 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 one clipboard item at a time. Constructor ClipboardItem.ClipboardItem
() Creates a new ClipboardItem object, with the MIME type as the key and Blob as the value Properties This interface provides the following properties. ...
...n only pass in one clipboard item at a time. Constructor ClipboardItem.ClipboardItem
() Creates a new ClipboardItem object, with the MIME type as the key and Blob as the value Properties This interface provides the following properties. types Read only Returns an Array of MIME types available within the ClipboardItem. Methods This interface defines the following methods. getType
() Returns a Promise that resolves with a Blob of the requested MIME type, or an error if the MIME type is not found. ...
...And 6 more matches
DOMMatrix - Web APIs
Properties This interface inherits properties from DOMMatrixReadOnly, though some of these properties are altered to be mutable. ...
... These are aliases for specific components of a 4x4 matrix, as shown below. 2D 3D equivalent a m11 b m12 c m21 d m22 e m41 f m42 Methods This interface includes the following methods, as well as the methods it inherits from DOMMatrixReadOnly. DOMMatrix.invertSelf
() Modifies the matrix by inverting it. If the matrix can't be inverted, its components are all set to NaN, and is2D returns false. DOMMatrix.multiplySelf
() Modifies the matrix by post-multiplying it with the specified DOMMatrix. This is equivalent to the dot product A?B, where matrix A is the source matrix and B is the matrix given as an input to the method. Returns itself. DOMMatrix.preMultipl...
...ifies the matrix by inverting it. If the matrix can't be inverted, its components are all set to NaN, and is2D returns false. DOMMatrix.multiplySelf
() Modifies the matrix by post-multiplying it with the specified DOMMatrix. This is equivalent to the dot product A?B, where matrix A is the source matrix and B is the matrix given as an input to the method. Returns itself. DOMMatrix.preMultiplySelf
() Modifies the matrix by pre-multiplying it with the specified DOMMatrix. This is equivalent to the dot product B?A, where matrix A is the source matrix and B is the matrix given as an input to the method. Returns itself. ...
...And 6 more matches
In depth: Microtasks and the JavaScript runtime environment - Web APIs
d JavaScript has become one of the most prolifically-used languages in the computing world. A vast number of the most popular applications are based at least in part on JavaScript code. To support this, it was necessary to find ways to allow for projects to escape the limitations of a single-threaded language. Starting with the addition of timeouts and intervals as part of the Web API (setTimeout
() and setInterval
()), the JavaScript environment provided by Web browsers has gradually advanced to include powerful features that enable scheduling of tasks, multi-threaded application development, and so forth. To understand where queueMicrotask
() comes into play here, it's helpful to understand how the JavaScript runtime operates when scheduling and running code. JavaScript execution contexts ...
...runs, it runs inside an execution context. There are three types of code that create a new execution context: The global context is the execution context created to run the main body of your code; that is, any code that exists outside of a JavaScript function. 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", "Ter...
... three execution contexts, some of which are created and destroyed several times over the course of the program's execution. As each context is created, it is placed on the execution context stack. When it exits, the context is removed from the context stack. Upon starting the program, the global context is created. ...
...And 6 more matches
HTML Drag and Drop API - Web APIs
The DataTransferItem object also has methods to get the drag item's data. The DataTransferItemList object is a list of DataTransferItem objects. The list object has methods to add a drag item to the list, remove a drag item from the list, and clear the list of all drag items. A key difference between the DataTransfer and DataTransferItem interfaces is that the former uses the synchronous getData
() method to access a drag item's data, but the latter instead uses the asynchronous getAsString
() method. Note: DragEvent and DataTransfer are broadly supported on desktop browsers. However, the DataTransferItem and DataTransferItemList interfaces have limited browser support. See Interoperability for more information about drag-and-drop interoperability. Gecko-specific interfaces Mozilla and Fi...
...tion. ...
...ference Drag operations guide Define the drag's data The application is free to include any number of data items in a drag operation. Each data item is a string of a particular type -- typically a MIME type such as text/html. Each drag event has a dataTransfer property that holds the event's data. This property (which is a DataTransfer object) also has methods to manage drag data. The setData
() method is used to add an item to the drag data, as shown in the following example. function dragstart_handler(ev) { // Add different types of drag data ev.dataTransfer.setData("text/plain", ev.target.innerText); ev.dataTransfer.setData("text/html", ev.target.outerHTML); ev.dataTransfer.setData("text/uri-list", ev.target.ownerDocument.location.href); } For a list of common data types ...
...And 6 more matches
History API - Web APIs
The DOM Window object provides access to the browser's session history (not to be confused for WebExtensions history) through the history object. It exposes useful methods and properties that let you navigate back and forth through the user's history, and manipulate the contents of the history stack. ...
...dow object provides access to the browser's session history (not to be confused for WebExtensions history) through the history object. It exposes useful methods and properties that let you navigate back and forth through the user's history, and manipulate the contents of the history stack. ...
... provides access to the browser's session history (not to be confused for WebExtensions history) through the history object. It exposes useful methods and properties that let you navigate back and forth through the user's history, and manipulate the contents of the history stack. Concepts and usage Moving backward and forward through the user's history is done using the back
(), forward
(), and go
() methods. ...
...And 6 more matches
IDBIndex - Web APIs
re. When the object store changes, all indexes that refers to the object store are automatically updated. You can grab a set of keys within a range. To learn more, see IDBKeyRange. Note: This feature is available in Web Workers. Properties IDBIndex.isAutoLocale Read only Returns a Boolean indicating whether the index had a locale value of auto specified upon its creation (see createIndex
()'s optionalParameters.) IDBIndex.locale Read only Returns the locale of the index (for example en-US, or pl) if it had a locale value specified upon its creation (see createIndex
()'s optionalParameters.) IDBIndex.name The name of this index. IDBIndex.objectStore Read only The name of the object store referenced by this index. IDBIndex.keyPath Read only The key path of this index. If n...
...Read only Affects how the index behaves when the result of evaluating the index's key path yields an array. If true, there is one record in the index for each item in an array of keys. If false, then there is one record for each key that is an array. IDBIndex.unique Read only If true, this index does not allow duplicate values for a key. ...
...e is one record in the index for each item in an array of keys. If false, then there is one record for each key that is an array. IDBIndex.unique Read only If true, this index does not allow duplicate values for a key. Methods Inherits from: EventTarget IDBIndex.count
() Returns an IDBRequest object, and in a separate thread, returns the number of records within a key range. ...
...And 6 more matches
Performance - Web APIs
ormance.memory Read only A non-standard extension added in Chrome, this property provides an object with basic memory usage information. You should not use this non-standard API. Performance.timeOrigin Read only Returns the high resolution timestamp of the start time of the performance measurement. Methods The Performance interface doesn't inherit any methods. ...
...bject with basic memory usage information. You should not use this non-standard API. Performance.timeOrigin Read only Returns the high resolution timestamp of the start time of the performance measurement. Methods The Performance interface doesn't inherit any methods. Performance.clearMarks
() Removes the given mark from the browser's performance entry buffer. Performance.clearMeasures
() Removes the given measure from the browser's performance entry buffer. ...
... Read only Returns the high resolution timestamp of the start time of the performance measurement. Methods The Performance interface doesn't inherit any methods. Performance.clearMarks
() Removes the given mark from the browser's performance entry buffer. Performance.clearMeasures
() Removes the given measure from the browser's performance entry buffer. Performance.clearResourceTimings
() Removes all performance entries with a entryType of "resource" from the browser's performance data buffer. Performance.getEntries
() Returns a list of PerformanceEntry objects based on the given filter. ...
...And 6 more matches
ReadableStream - Web APIs
The ReadableStream interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. Constructor ReadableStream
() Creates and returns a readable stream object from the given handlers. Properties ReadableStream.locked Read only The locked getter returns whether or not the readable stream is locked to a reader. Methods ReadableStream.cancel
() Cancels the stream, signaling a loss of interest in the stream by a consumer. The supplied reason argument will be given to the underlying source, which may or may not use it. ReadableStream.getIterator
() Creates a ReadableStream async iterator instance and locks the stream to it. While the stream is locked, no other r...
...cels the stream, signaling a loss of interest in the stream by a consumer. The supplied reason argument will be given to the underlying source, which may or may not use it. ReadableStream.getIterator
() Creates a ReadableStream async iterator instance and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ReadableStream.getReader
() Creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ...
... use it. ReadableStream.getIterator
() Creates a ReadableStream async iterator instance and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ReadableStream.getReader
() Creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ReadableStream.pipeThrough
() Provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. ReadableStream.pipeTo
() Pipes the current ReadableStream to a given WritableStream and returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. ...
...And 6 more matches
USBDevice - Web APIs
properties are USBDevice.usbVersionMajor and USBDevice.usbVersionSubminor. USBDevice.usbVersionSubminor Read only One of three properties that declare the USB protocol version supported by the device. The other two properties are USBDevice.usbVersionMajor and USBDevice.usbVersionMinor. USBDevice.vendorId Read only The official usg.org-assigned vendor ID. ...
...ne of three properties that declare the USB protocol version supported by the device. The other two properties are USBDevice.usbVersionMajor and USBDevice.usbVersionMinor. USBDevice.vendorId Read only The official usg.org-assigned vendor ID. Methods USBDevice.claimInterface
() Returns a Promise that resolves when the requested interface is claimed for exclusive access. USBDevice.clearHalt
() Returns a Promise that resolves when a halt condition is cleared. ...
...o properties are USBDevice.usbVersionMajor and USBDevice.usbVersionMinor. USBDevice.vendorId Read only The official usg.org-assigned vendor ID. Methods USBDevice.claimInterface
() Returns a Promise that resolves when the requested interface is claimed for exclusive access. USBDevice.clearHalt
() Returns a Promise that resolves when a halt condition is cleared. USBDevice.controlTransferIn
() Returns a Promise that resolves with a USBTransferInResult when a command or status operation has been transmitted to the USB device. ...
...And 6 more matches
Color masking - Web APIs
You can think of the color masking operation as if looking at the colored canvas through some tinted glass or color filter. ...
...ed, would give us shades of green. Masking only the blue channel would give us shades of yellow (including shades of orange, brown, olive and yellow-green), the complementary of blue. Similarly, masking only green would give us shades of magenta (also purples, crimsons, and so on), and masking only red would give shades of cyan (also sea greens, blues, and so on). Note that the calls to colorMask
() only occur when the user clicks on one of the toggle buttons. But rendering is done every second, using the timer. The color mask state of WebGL is preserved, so we do not need to call colorMask
() every frame to set up the color mask. This is an important aspect of the WebGL state machine. It allows us to setup WebGL in a single initialization phase, and then just execute drawing commands for eac...
... << PreviousNext >> ...
...And 6 more matches
Textures from code - Web APIs
HTML5 canvas.</canvas> body { text-align : center; } canvas { width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } <script type="x-shader/x-vertex" id="vertex-shader"> #version 100 precision highp float; attribute vec2 position; void main
() { gl_Position = vec4(position, 0.0, 1.0); gl_PointSize = 128.0; } </script> <script type="x-shader/x-fragment" id="fragment-shader"> #version 100 precision mediump float; void main
() { vec2 fragmentPosition = 2.0*gl_PointCoord - 1.0; float distance = length(fragmentPosition); float distanceSqrd = distance * distance; gl_FragColor = vec4( 0.2/distanceSqrd, 0.1/distanceSqrd, ...
....0); gl_PointSize = 128.0; } </script> <script type="x-shader/x-fragment" id="fragment-shader"> #version 100 precision mediump float; void main
() { vec2 fragmentPosition = 2.0*gl_PointCoord - 1.0; float distance = length(fragmentPosition); float distanceSqrd = distance * distance; gl_FragColor = vec4( 0.2/distanceSqrd, 0.1/distanceSqrd, 0.0, 1.0 ); } </script> ;(function
(){ "use strict" window.addEventListener("load", setupWebGL, false); var gl, program; function setupWebGL (evt) { window.removeEventListener(evt.type, setupWebGL, false); if (!(gl = getRenderingContext
())) return; var source = document.querySelector("#vertex-shader").innerHTML; var vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader,source); gl.compil...
...rySelector("#vertex-shader").innerHTML; var vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader,source); gl.compileShader(vertexShader); source = document.querySelector("#fragment-shader").innerHTML var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader,source); gl.compileShader(fragmentShader); program = gl.createProgram
(); gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); gl.detachShader(program, vertexShader); gl.detachShader(program, fragmentShader); gl.deleteShader(vertexShader); gl.deleteShader(fragmentShader); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { var linkErrLog = gl.getProgramInfoLog(program); cleanup
(); do...
...And 6 more matches
Writing a WebSocket server in Java - Web APIs
OutputStream Methods: write(byte[] b, int off, int len) Writes len bytes from the specified byte array starting at offset off to this output stream. InputStream Methods:...
...ttern; public class WebSocket { public static void main(String[] args) throws IOException, NoSuchAlgorithmException { ServerSocket server = new ServerSocket(80); try { System.out.println("Server has started on 127.0.0.1:80.\r\nWaiting for a connection..."); Socket client = server.accept
(); System.out.println("A client connected."); Socket Methods: java.net.Socket getInputStream
() Returns an input stream for this socket. java.net.Socket getOutputStream
() Returns an output stream for this socket. OutputStream Methods: write(byte[] b, int off, int len) Writes len bytes from the specified byte array starting at offset off to this output stream. InputStream Methods: read(byte[] b, int off, int len) Reads up to len bytes of data from the input stream into an array...
...eturns an output stream for this socket. OutputStream Methods: write(byte[] b, int off, int len) Writes len bytes from the specified byte array starting at offset off to this output stream. InputStream Methods: read(byte[] b, int off, int len) Reads up to len bytes of data from the input stream into an array of bytes. Let us extend our example. ...
...And 6 more matches
Using the Web Audio API - Web APIs
lar design, you can create complex audio functions with dynamic effects. Audio context To be able to do anything with the Web Audio API, we need to create an instance of the audio context. This then gives us access to all the features and functionality of the API. // for legacy browsers const AudioContext = window.AudioContext || window.webkitAudioContext; const audioContext = new AudioContext
(); So what's going on when we do this? A BaseAudioContext is created for us automatically and extended to an online audio context. We'll want this because we're looking to play live sound. Note: If you just want to process audio data, for instance, buffer and stream it but not play it, you might want to look into creating an OfflineAudioContext. Loading sound Now, the audio context we've cre...
..., which handles the situation for you: track.connect(audioContext.destination); A good way to visualise these nodes is by drawing an audio graph so you can visualize it. This is what our current audio graph looks like: Now we can add the play and pause functionality. ...
...raph so you can visualize it. This is what our current audio graph looks like: Now we can add the play and pause functionality. // select our play button const playButton = document.querySelector('button'); playButton.addEventListener('click', function
() { // check if context is in suspended state (autoplay policy) if (audioContext.state === 'suspended') { audioContext.resume
(); } // play or pause track depending on state if (this.dataset.playing === 'false') { audioElement.play
(); this.dataset.playing = 'true'; } else if (this.dataset.playing === 'true') { audioElement.pause
(); this.dataset.playing = 'false'; } }, false); We also need to take into account what to do when the track finishes playing. Our HTMLMediaEl...
...And 6 more matches
HTML in XMLHttpRequest - Web APIs
TP error pages (which often have a text/html response body). Usage Retrieving an HTML resource as a DOM using XMLHttpRequest works just like retrieving an XML resource as a DOM using XMLHttpRequest, except you can't use the synchronous mode and you have to explicitly request a document by assigning the string "document" to the responseType property of the XMLHttpRequest object after calling open
() but before calling send
(). var xhr = new XMLHttpRequest
(); xhr.onload = function
() { console.log(this.responseXML.title); } xhr.open("GET", "file.html"); xhr.responseType = "document"; xhr.send
(); Feature detection Method 1 This method relies on the "force async" nature of the feature. When you try to set responseType of an XMLHttpRequest object after it is opened as "sync". This throws an...
...nsole.log(this.responseXML.title); } xhr.open("GET", "file.html"); xhr.responseType = "document"; xhr.send
(); Feature detection Method 1 This method relies on the "force async" nature of the feature. When you try to set responseType of an XMLHttpRequest object after it is opened as "sync". This throws an error in the browsers that implement the feature and works on others. ...
...ument"; xhr.send
(); Feature detection Method 1 This method relies on the "force async" nature of the feature. When you try to set responseType of an XMLHttpRequest object after it is opened as "sync". This throws an error in the browsers that implement the feature and works on others. function HTMLinXHR
() { if (!window.XMLHttpRequest) return false; var req = new window.XMLHttpRequest
(); req.open('GET', window.location.href, false); try { req.responseType = 'document'; } catch(e) { return true; } return false; } View on JSFiddle This method is synchronous, does not rely on external assets though it may not be as reliable as method 2 described below since it does not check the actual feature but an indication of that feature. Method 2 There are two challen...
...And 6 more matches
Sending and Receiving Binary Data - Web APIs
body according to responseType, as an ArrayBuffer, Blob, Document, JSON, or string. This is null if the request is not complete or was not successful. This example reads an image as a binary file and creates an 8-bit unsigned integer array from the raw bytes. Note that this will not decode the image and read the pixels. You will need a png decoding library for that. ...
...rrayBuffer = oReq.response; // Note: not oReq.responseText if (arrayBuffer) { var byteArray = new Uint8Array(arrayBuffer); for (var i = 0; i < byteArray.byteLength; i++) { // do something with each byte in the array } } }; oReq.send(null); You can also read a binary file as a Blob by setting the string "blob" to the responseType property. ...
...teArray.byteLength; i++) { // do something with each byte in the array } } }; oReq.send(null); You can also read a binary file as a Blob by setting the string "blob" to the responseType property. var oReq = new XMLHttpRequest
(); oReq.open("GET", "/myfile.png", true); oReq.responseType = "blob"; oReq.onload = function(oEvent) { var blob = oReq.response; // ... ...
...And 6 more matches
background - CSS: Cascading Style Sheets
bottom | <length-percentage> ] | [ center | [ left | right ] <length-percentage>? ] && [ center | [ top | bottom ] <length-percentage>? ] ]<bg-size> = [ <length-percentage> | auto ]{1,2} | cover | contain<repeat-style> = repeat-x | repeat-y | [ repeat | space | round | no-repeat ]{1,2}<attachment> = scroll | fixed | local<box> = border-box | padding-box | content-boxwhere <image> = <url> | <image
()> | <image-set
()> | <element
()> | <paint
()> | <cross-fade
()> | <gradient><length-percentage> = <length> | <percentage>where <image
()> = image( <image-tags>? [ <image-src>? , <color>? ]! )<image-set
()> = image-set( <image-set-option># )<element
()> = element( <id-selector> )<paint
()> = paint( <ident>, <declaration-value>? )<cross-fade
()> = cross-fade( <cf-mixing-image> , <cf-final-image>? )<gradient...
...[ <image-src>? ...
...[ <image-src>? , <color>? ...
...And 6 more matches
mask-image - CSS: Cascading Style Sheets
lue used as mask image layer. ...
... image layer. ...
... Formal definition Initial valuenoneApplies toall elements; In SVG, it applies to container elements excluding the defs element and all graphics elementsInheritednoComputed valueas specified, but with <url> values made absoluteAnimation typediscrete Formal syntax <mask-reference>#where <mask-reference> = none | <image> | <mask-source>where <image> = <url> | <image
()> | <image-set
()> | <element
()> | <paint
()> | <cross-fade
()> | <gradient><mask-source> = <url>where <image
()> = image( <image-tags>? [ <image-src>? , <color>? ]! )<image-set
()> = image-set( <image-set-option># )<element
()> = element( <id-selector> )<paint
()> = paint( <ident>, <declaration-value>? )<cross-fade
()> = cross-fade( <cf-mixing-image> , <cf-final-image>? )<gradient> = <linear-gradient
()> | <repeating-linear-gradient
()...
...And 6 more matches
mask - CSS: Cascading Style Sheets
e> ] && [ [ top | bottom ] <length-percentage> ] ]<bg-size> = [ <length-percentage> | auto ]{1,2} | cover | contain<repeat-style> = repeat-x | repeat-y | [ repeat | space | round | no-repeat ]{1,2}<geometry-box> = <shape-box> | fill-box | stroke-box | view-box<compositing-operator> = add | subtract | intersect | exclude<masking-mode> = alpha | luminance | match-sourcewhere <image> = <url> | <image
()> | <image-set
()> | <element
()> | <paint
()> | <cross-fade
()> | <gradient><mask-source> = <url><length-percentage> = <length> | <percentage><shape-box> = <box> | margin-boxwhere <image
()> = image( <image-tags>? [ <image-src>? , <color>? ]! )<image-set
()> = image-set( <image-set-option># )<element
()> = element( <id-selector> )<paint
()> = paint( <ident>, <declaration-value>? )<cross-fade
()> = cross-f...
...[ <image-src>? , <color>? ]! ...
...[ <image-src>? , <color>? ]! ...
...And 6 more matches
Event reference
gh The browser estimates it can play the media up to its end without stopping for content buffering. complete The rendering of an OfflineAudioContext is terminated. durationchange The duration attribute has been updated. emptied The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load
() method is called to reload it. ended Playback has stopped because the end of the media was reached. loadeddata The first frame of the media has finished loading. loadedmetadata The metadata has been loaded. pause Playback has been paused. play Playback has begun. playing Playback is ready to start after having been paused or ...
...ing downloading error noupdate obsolete updateready Value change events broadcast CheckboxStateChange hashchange input RadioStateChange readystatechange ValueChange Uncategorized events invalid message message open show Less common and non-standard events Abortable Fetch events Event name Fired when abort A DOM request is aborted, i.e. using AbortController.abort
(). SVG events SVGAbort SVGError SVGLoad SVGResize SVGScroll SVGUnload SVGZoom Database events abort blocked complete error success upgradeneeded versionchange Script events afterscriptexecute beforescriptexecute Menu events DOMMenuItemActive DOMMenuItemInactive Window events close Popup events popuphidden popuphiding popupshowing popupshown Tab events visibilitychange Batter...
...ts dragging an element or text selection. drop DragEvent HTML5 An element is dropped on a valid drop target. durationchange Event HTML5 media The duration attribute has been updated. emptied Event HTML5 media The media has become empty. For example, this event is triggered if the media has already been loaded (or partially loaded), and the load
() method is called to reload it. end Event Web Speech API The speech recognition service has disconnected. end SpeechSynthesisEvent Web Speech API The utterance has finished being spoken. ended Event HTML5 media Playback has stopped because the end of the media was reached. ended Event Web Audio API Playback has stopped bec...
...And 6 more matches
Making content editable - Developer guides
you have to do is set the contenteditable attribute on nearly any HTML element to make it editable. Here's a simple example which creates a <div> element whose contents the user can edit. <div contenteditable="true"> This text can be edited by the user. ...
... Differences in markup generation Use of contenteditable across different browsers has been painful for a long time because of the differences in generated markup between browsers. ...
...ability.policy.allowclipboard.sites", "https://www.mozilla.org"); user_pref("capability.policy.allowclipboard.Clipboard.cutcopy", "allAccess"); user_pref("capability.policy.allowclipboard.Clipboard.paste", "allAccess"); Example: A simple but complete rich text editor <!doctype html> <html> <head> <title>Rich Text Editor</title> <script type="text/javascript"> var oDoc, sDefTxt; function initDoc
() { oDoc = document.getElementById("textBox"); sDefTxt = oDoc.innerHTML; if (document.compForm.switchMode.checked) { setDocMode(true); } } function formatDoc(sCmd, sValue) { if (validateMode
()) { document.execCommand(sCmd, false, sValue); oDoc.focus
(); } } function validateMode
() { if (!document.compForm.switchMode.checked) { return true ; } alert("Uncheck \"Show HTML\"."); oDoc.foc...
...And 6 more matches
Concurrency model and the event loop - JavaScript
e as an input parameter. As always, calling a function creates a new stack frame for that function's use. The processing of functions continues until the stack is once again empty. Then, the event loop will process the next message in the queue (if there is one). Event loop The event loop got its name because of how it's usually implemented, which usually resembles: while (queue.waitForMessage
()) { queue.processNextMessage
() } queue.waitForMessage
() waits synchronously for a message to arrive (if one is not already available and waiting to be handled). "Run-to-completion" Each message is processed completely before any other message is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-em...
...d the stack is empty, the message is processed right after the delay. However, if there are messages, the setTimeout message will have to wait for other messages to be processed. For this reason, the second argument indicates a minimum time--not a guaranteed time. ...
...s empty, the message is processed right after the delay. However, if there are messages, the setTimeout message will have to wait for other messages to be processed. For this reason, the second argument indicates a minimum time--not a guaranteed time. ...
...And 6 more matches
Atomics - JavaScript
erties and methods of Atomics are static (as is the case with the Math object, for example). Atomic operations When memory is shared, multiple threads can read and write the same data in memory. Atomic operations make sure that predictable values are written and read, that operations are finished before the next operation starts and that operations are not interrupted. ...
...thods of Atomics are static (as is the case with the Math object, for example). Atomic operations When memory is shared, multiple threads can read and write the same data in memory. Atomic operations make sure that predictable values are written and read, that operations are finished before the next operation starts and that operations are not interrupted. ...
... that predictable values are written and read, that operations are finished before the next operation starts and that operations are not interrupted. Wait and notify The wait
() and notify
() methods are modeled on Linux futexes ("fast user-space mutex") and provide ways for waiting until a certain condition becomes true and are typically used as blocking constructs. Static methods Atomics.add
() Adds the provided value to the existing value at the specified index of the array. Returns the old value at that index. Atomics.and
() Computes a bitwise AND on the value at the specified index of the array with the provided value. Returns the old value at that index. Atomics.compareExchange
() Stores a value at the specified index of the array, if it equals a value. Returns the old value. At...
...And 6 more matches
Set - JavaScript
ator. Specifically, for Sets, +0 (which is strictly equal to -0) and -0 were different values. However, this was changed in the ECMAScript 2015 specification. See "Key equality for -0 and 0" in the browser compatibility table for details. NaN and undefined can also be stored in a Set. All NaN values are equated (i.e. NaN is considered the same as NaN, even though NaN !== NaN). Constructor Set
() Creates a new Set object. Static properties get Set[@@species] The constructor function that is used to create derived objects. Instance properties Set.prototype.size Returns the number of values in the Set object. Instance methods Set.prototype.add(value) Appends value to the Set object. Returns the Set object. Set.prototype.clear
() Removes all elements from the Set object. ...
...bject. Set.prototype.delete(value) Removes the element associated to the value and returns the value that Set.prototype.has(value) would have previously returned. Set.prototype.has(value) will return false afterwards. Set.prototype.has(value) Returns a boolean asserting whether an element is present with the given value in the Set object or not. ...
...) would have previously returned. Set.prototype.has(value) will return false afterwards. Set.prototype.has(value) Returns a boolean asserting whether an element is present with the given value in the Set object or not. Iteration methods Set.prototype[@@iterator]
() Returns a new Iterator object that yields the values for each element in the Set object in insertion order. Set.prototype.keys
() Returns a new Iterator object that yields the values for each element in the Set object in insertion order. ...
...And 6 more matches
WebAssembly - JavaScript
is not a constructor (it is not a function object). You can compare it to Math, which is also a namespace object for mathematical constants and functions, or to Intl which is the namespace object for internationalization constructors and other language-sensitive functions. Description The primary uses for the WebAssembly object are: Loading WebAssembly code, using the WebAssembly.instantiate
() function. Creating new memory and table instances via the WebAssembly.Memory
()/WebAssembly.Table
() constructors. Providing facilities to handle errors that occur in WebAssembly via the WebAssembly.CompileError
()/WebAssembly.LinkError
()/WebAssembly.RuntimeError
() constructors. Constructor properties WebAssembly.CompileError
() Indicates an error during WebAssembly decoding or validation. W...
...ing new memory and table instances via the WebAssembly.Memory
()/WebAssembly.Table
() constructors. Providing facilities to handle errors that occur in WebAssembly via the WebAssembly.CompileError
()/WebAssembly.LinkError
()/WebAssembly.RuntimeError
() constructors. Constructor properties WebAssembly.CompileError
() Indicates an error during WebAssembly decoding or validation. WebAssembly.Global
() Represents a global variable instance, accessible from both JavaScript and importable/exportable across one or more WebAssembly.Module instances. This allows dynamic linking of multiple modules. WebAssembly.Instance
() Is a stateful, executable instance of a WebAssembly.Module WebAssembly.LinkError
() Indicates an error during module instantiation (besides traps from the start function). WebA...
... global variable instance, accessible from both JavaScript and importable/exportable across one or more WebAssembly.Module instances. This allows dynamic linking of multiple modules. WebAssembly.Instance
() Is a stateful, executable instance of a WebAssembly.Module WebAssembly.LinkError
() Indicates an error during module instantiation (besides traps from the start function). WebAssembly.Memory
() An object whose buffer property is a resizable ArrayBuffer that holds the raw bytes of memory accessed by a WebAssembly Instance. ...
...And 6 more matches
Destructuring assignment - JavaScript
nguages, the XOR-swap trick). let a = 1; let b = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); // 1 const arr = [1,2,3]; [arr[2], arr[1]] = [arr[1], arr[2]]; console.log(arr); // [1,3,2] Parsing an array returned from a function It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise. ...
... const arr = [1,2,3]; [arr[2], arr[1]] = [arr[1], arr[2]]; console.log(arr); // [1,3,2] Parsing an array returned from a function It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise. In this example, f
() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring. ...
...r[1], arr[2]]; console.log(arr); // [1,3,2] Parsing an array returned from a function It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise. In this example, f
() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring. ...
...And 6 more matches
Object initializer - JavaScript
Objects can be initialized using new Object
(), Object.create
(), or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). 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. ...
... 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 o = {} let o = {a: 'foo', b: 42, c: {}} let a = 'foo', b = 42, c = {} let o = {a: a, b: b, c: c} let o = { property: function (parameters) {}, get property
() {}, set property(value) {} }; New notations in ECMAScript 2015 Please see the compatibility table for support for these notations. In non-supporting environments, these notations will lead to syntax errors. // Shorthand property names (ES2015) let a = 'foo', b = 42, c = {}; let o = {a, b, c} // Shorthand method names (ES2015) let o = { property(parameters) {} } // Computed property name...
...n them: JSON permits only property definition using "property": value syntax. The property name must be double-quoted, and the definition cannot be a shorthand. In JSON the values can only be strings, numbers, arrays, true, false, null, or another (JSON) object. A function value (see "Methods" above) can not be assigned to a value in JSON. Objects like Date will be a string after JSON.parse
(). JSON.parse
() will reject computed property names and an error will be thrown. Examples Creating objects An empty object with no properties can be created like this: let object = {} However, the advantage of the literal or initializer notation is, that you are able to quickly create objects with properties inside the curly braces. You simply notate a list of key: value pairs delimited by c...
...And 6 more matches
await - JavaScript
ontinues by returning to the function's caller a pending Promise for the completion of the await's function and resuming execution of that caller. Examples Awaiting a promise to be fulfilled If a Promise is passed to an await expression, it waits for the Promise to be fulfilled and returns the fulfilled value. ...
...or the completion of the await's function and resuming execution of that caller. Examples Awaiting a promise to be fulfilled If a Promise is passed to an await expression, it waits for the Promise to be fulfilled and returns the fulfilled value. ...
...ler. Examples Awaiting a promise to be fulfilled If a Promise is passed to an await expression, it waits for the Promise to be fulfilled and returns the fulfilled value. function resolveAfter2Seconds(x) { return new Promise(resolve => { setTimeout(
() => { resolve(x); }, 2000); }); } async function f1
() { var x = await resolveAfter2Seconds(10); console.log(x); // 10 } f1
(); Thenable objects Thenable objects will be fulfilled just the same. ...
...And 6 more matches
import - JavaScript
to import read only live bindings which are exported by another module. Imported modules are in strict mode whether you declare them as such or not. The import statement cannot be used in embedded scripts unless such script has a type="module". Bindings imported are called live bindings because they are updated by the module that exported the binding. There is also a function-like dynamic import
(), which does not require scripts of type="module". Backward compatibility can be ensured using attribute nomodule on the <script> tag. Syntax import defaultExport from "module-name"; import * as name from "module-name"; import { export1 } from "module-name"; import { export1 as alias1 } from "module-name"; import { export1 , export2 } from "module-name"; import { foo , bar } from "module-name/p...
...t 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 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 ...
...port { reallyReallyLongModuleExportName as shortName, anotherLongModuleName as short } from '/modules/my-module.js'; Import a module for its side effects only Import an entire module for side effects only, without importing anything. This runs the module's global code, but doesn't actually import any values. import '/modules/my-module.js'; This works with dynamic imports as well: (async
() => { if (somethingIsTrue) { // import module for side effects await import('/modules/my-module.js'); } })
(); If your project uses packages that export ESM, you can also import them for side effects only. This will run the code in the package entry point file (and any files it imports) only. Importing defaults It is possible to have a default export (whether it is an object, a func...
...And 6 more matches
JavaScript reference - JavaScript
This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more about this reference. Built-ins JavaScript standard built-in objects, along with their methods and properties. ...
... This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more about this reference. Built-ins JavaScript standard built-in objects, along with their methods and properties. ...
... This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more about this reference. Built-ins JavaScript standard built-in objects, along with their methods and properties. ...
...And 6 more matches
Autoplay guide for media and Web Audio APIs - Web media technologies
ly requesting that playback begin. This includes both the use of HTML attributes to autoplay media as well as the user of JavaScript code to start playback outside the context of handling user input. That means that both of the following are considered autoplay behavior, and are therefore subject to the browser's autoplay blocking policy: <audio src="/music.mp4" autoplay> and audioElement.play
(); The following web features and APIs may be affected by autoplay blocking: The HTML <audio> and <video> elements The Web Audio API From the user's perspective, a web page or app that spontaneously starts making noise without warning can be jarring, inconvenient, or off-putting. Because of that, browsers generally only allow autoplay to occur successfully under specific circumstances. Auto...
...means that the first time the play event is fired, you know your media is being started for the first time after the page is opened. Consider this HTML for a media element: <video src="myvideo.mp4" autoplay onplay=handleFirstPlay(event)"> Here we have a <video> element whose autoplay attribute is set, with an onplay event handler set up; the event is handled by a function called handleFirstPlay
(), which receives as input the play event. handleFirstPlay
() looks like this: function handleFirstPlay(event) { let vid = event.target; vid.onplay = null; // Start whatever you need to do after playback has started } After getting a reference to the video element from the Event object's target, the element's onplay handler is set to null. This will prevent any future play events from bei...
...eing delivered to the handler. That could happen if the video is paused and resumed by the user or automatically by the browser when the document is in a background tab. At this point, your site or app can begin whatever it needs to do that relies upon the video having been started up. Note: This approach doesn't differentiate between autoplay and the user starting playback manually. The play
() method The term "autoplay" also refers to scenarios in which a script tries to trigger the playback of media that includes audio, outside the context of handling a user input event. This is done by calling the media element's play
() method. Note: It is strongly recommended that you use the autoplay attribute whenever possible, because support for autoplay preferences are more widespread for th...
...And 6 more matches
XUL Migration Guide - Archive of obsolete content
f the DOM directly access the tabbrowser object Modifying the Browser Chrome This example uses the action button API, which is only available from Firefox 29 onwards. The window/utils module gives you direct access to chrome windows, including the browser's chrome window. ...
...hrome This example uses the action button API, which is only available from Firefox 29 onwards. The window/utils module gives you direct access to chrome windows, including the browser's chrome window. ...
...ack Wiki's collection of third party modules. Accessing tabbrowser This example uses the action button API, which is only available from Firefox 29 onwards. The tabs/utils module gives you direct access to the tabbrowser object and the XUL tab objects it contains. ...
...And 5 more matches
page-mod - Archive of obsolete content
1>Page matches ruleset</h1>";' }); You can supply the content script(s) in one of two ways: as a string literal, or an array of string literals, assigned to the contentScript option, as above as separate files supplied in your add-on's "data" directory. ...
...n approved on AMO. Instead, keep the script in a separate file and load it using contentScriptFile. This makes your code easier to maintain, secure, debug and review. A page-mod only attaches scripts to documents loaded in tabs. It will not attach scripts to add-on panels, page-workers, sidebars, or Firefox hidden windows. To stop a page-mod from making any more modifications, call its destroy
() method. The PageMod constructor takes a number of other options to control its behavior: contentStyle Lists stylesheets to attach, supplied as strings. contentStyleFile Lists stylesheets to attach, supplied in separate files. contentScriptOptions Defines read-only values accessible to content scripts. attachTo Controls whether to attach scripts to...
...For example, here's an add-on that attaches a script to every page the user loads: var data = require("sdk/self").data; var pageMod = re...
...And 5 more matches
event/target - Archive of obsolete content
Usage Many objects in the SDK can broadcast events. For example, a panel instance emits an show event when the panel is shown. With this module you can create your own objects that emit events. This module provides an exemplar EventTarget object, that implements an interface for adding and removing event listeners of a specific type. EventTarget is the base class for all objects in SDK on which events are emitted. Also see the tutorial on implementing event targets to get started with this API. ...
...ace for adding and removing event listeners of a specific type. EventTarget is the base class for all objects in SDK on which events are emitted. Also see the tutorial on implementing event targets to get started with this API. Instantiation It's easy to create event target objects, no special arguments are required. const { EventTarget } = require("sdk/event/target"); let target = EventTarget
(); For a convenience though optional options arguments may be used, in which case all the function properties with keys like: onMessage, onMyEvent... will be auto registered for associated 'message', 'myEvent' events on the created instance. All other properties of options will be ignored. Adding listeners EventTarget interface defines on method, that can be used to register event listeners on t...
...ated 'message', 'myEvent' events on the created instance. All other properties of options will be ignored. ...
...And 5 more matches
Displaying annotations - Archive of obsolete content
asking it to show or hide the annotation. Like the selector, the matcher also listens for the window's unload event and on unload sends a detach message to the main module, so the add-on can clean it up. ...
...elf.on('message', function onMessage(annotations) { annotations.forEach( function(annotation) { if(annotation.url == document.location.toString
()) { createAnchor(annotation); } }); $('.annotated').css('border', 'solid 3px yellow'); $('.annotated').bind('mouseenter', function(event) { self.port.emit('show', $(this).attr('annotation')); event.stopPropagation
(); event.preventDefault
(); }); $('.annotated').bind('mouseleave', function
() { self.port.emit('hide'); }); }); function createAnchor(annotation) { annotationAnchorAncestor = $('#' + annotation.ancestorId); annotationAnchor = $(annotationAnchorAncestor).parent
().find( ':contains(' + annotation.anchorText + ')').last
(); $(annotationAnchor).addClass('annotate...
...This function: initializes the content script instance with the current set of annotations ...
...And 5 more matches
Modifying the Page Hosted by a Tab - Archive of obsolete content
To follow this tutorial you'll need to have learned the basics of jpm. To modify the page hosted by a particular tab, load one or more content scripts into it using attach
() method of tab object. The job of these scripts is to interact with web content. Here's a simple example: var button = require("sdk/ui/button/action").ActionButton({ id: "style-tab", label: "Style Tab", icon: "./icon-16.png", onClick: function
() { require("sdk/tabs").activeTab.attach({ contentScript: 'document.body.style.border = "5px solid red";' }); } }); To run this example, save an icon file named "icon-16.png" in add-on's "data" directory. You could download this icon: . This add-on creates a button with Mozilla favicon as an icon. It has a click handler which fetches the active tab a...
...de option contentScriptFile not contentScript, whose value is a URL pointing to one or more content script files. For example, if we save the script above under the add-on's data directory in a file called my-script.js: var self = require("sdk/self"); var button = require("sdk/ui/button/action").ActionButton({ id: "style-tab", label: "Style Tab", icon: "./icon-16.png", onClick: function
() { require("sdk/tabs").activeTab.attach({ contentScriptFile: self.data.url("my-script.js") }); } }); You can load more than one script, and the scripts can interact directly with each other. So you can load jQuery, and then your content script can use that. Loading several content script files The data assigned to contentScriptFile can be a vector. Scripts will be loaded in the...
...e loading two scripts, first.js & second.js. Both scripts will be executed in the same context, so everything publicly defined in first.js will be accessible from second.js. // index.js var self = require("sdk/self"); var tabs = require("sdk/tabs"); require("sdk/ui/button/action").ActionButton({ id: "load-several", label: "load several scripts", icon: "./icon-16.png", onClick: function
() { tabs.activeTab.attach({ contentScriptFile: [self.data.url('first.js'), self.data.url('second.js')] }); } }); Communicating With the Content Scripts Your add-on script and content scripts can't directly access each other's variables or call each other's functions, but they can send each other messages. To send a message from one side to the other, se...
...And 5 more matches
Bootstrapped extensions - Archive of obsolete content
p and shutdown tasks it requires. This article discusses how bootstrapped extensions work. See this tutorial on converting from an overlay extension to restartless for a practical step by step guide to migrating. The startup and shutdown process A key feature of bootstrapped extensions is that they must be able to start up and shut down on demand by the application. ...
...rlay extension to restartless for a practical step by step guide to migrating. The startup and shutdown process A key feature of bootstrapped extensions is that they must be able to start up and shut down on demand by the application. When the extension's startup
() function is called, it must manually inject its user interface and other behavior into the application. Similarly, when its shutdown
() function is called, it must remove anything that it has added to the application, as well as all references to any of its objects. There are several scenarios in which the startup
() function may be called; for example: When the extension is first installed, assuming that it's both compatible with the application and is enabled. When the extension becomes enabled using the add-ons manager win...
... When the extension becomes disabled. When the user quits the application, if the extension is enabled. ...
...And 5 more matches
Dialogs and Prompts - Archive of obsolete content
imple dialog code The following XUL code defines a simple dialog with two buttons, OK and Cancel (buttons="accept,cancel" attribute on dialog). <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/global.css" type="text/css"?> <dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="..." title="..." buttons="accept,cancel" ondialogaccept="return onAccept
();" ondialogcancel="return onCancel
();"> <script src="chrome://..."/> <!-- Content --> </dialog> You need to implement onAccept and onCancel functions in your script. If they return anything but false, the dialog will be closed. Buttons in <dialog> Predefined There are six button types you can use in the buttons attribute of dialog. They are: accept -- OK button. cancel -- Cancel button...
...can set their label, accesskey and oncommand handler by adding buttonlabel<buttonname>, buttonaccesskey<buttonname> and ondialog<buttonname> attributes to the dialog element. For example, to add an Apply button to your dialog, use the following code: <dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="..." buttons="accept,cancel,extra1" ondialogaccept="onAccept
();" ondialogextra1="onApply
();" buttonlabelextra1="Apply" buttonaccesskeyextra1="A"> <!-- Content --> </dialog> You can even get the element object for any of predefined buttons with gDialog.getButton(dlgtype);, where gDialog is the <dialog> element and dlgtype is one of the six button types listed above. Explicit If you are not satisfied with the layout of predefined buttons in dialog, ...
...s how to pass custom arguments to a dialog, process those arguments in the dialog, and return user-modified arguments to the caller. ...
...And 5 more matches
Downloading Files - Archive of obsolete content
The following methods of downloading files may not work as expected after Firefox 26, and should no longer be used. Please use Downloads.jsm instead. Downloading files To download a file, create an instance of nsIWebBrowserPersist and call its nsIWebBrowserPersist.saveURI
() method, passing it a URL to download and an nsIFile instance representing the local file name/path. ...
...If, and only if, the URL is not // related to a window, null should be used instead. ...
.... Downloading Binary Files with a Progress Listener To download a binary file with custom progress listener: Components.utils.import("resource://gre/modules/PrivateBrowsingUtils.jsm"); const WebBrowserPersist = Components.Constructor("@mozilla.org/embedding/browser/nsWebBrowserPersist;1", "nsIWebBrowserPersist"); var persist = WebBrowserPersist
(); var targetFile = Services.dirsvc.get("Desk", Ci.nsIFile); targetFile.append("file.bin"); var obj_URI = Services.io.newURI(aURLToDownload, null, null); // Obtain the privacy context of the browser window that the URL // we are downloading comes from. If, and only if, the URL is not // related to a window, null should be used instead. var privacy = PrivateBrowsingUtils.privacyContextFromWindow(...
...And 5 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
e1") + "/" + evt.target.getAttribute("attribute2")); } } document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); // The last value is a Mozilla-specific value to indicate untrusted content is allowed to trigger the event. The data from the web page (unprivileged code) will be the values of attribute1 and attribute2. ...
...(privileged code) where your listener catches it and reads the attribute values from the DOM element where the event originated. ...
...rface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIDOMWindow); mainWindow.document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); If you need to to pass lots of data, consider using CDATA sections instead of the simple attributes on a custom element. Note: If you're using HTML5's postMessage
() to send a message from unprivileged code to privileged code, adding 'true' to the end of your event listener in your privileged chrome code will allow the message to be received. document.addEventListener("message", function(e) { yourFunction(e); }, false, true); Sending data from chrome to unprivileged document To "answer" the web page (e.g., return code), your extension can set an attribut...
...And 5 more matches
Drag and Drop JavaScript Wrapper - Archive of obsolete content
unction should be defined when something should happen on a drag exit. It has two arguments, the event object and the drag session. onDrop(event, dropData, session) This function should be defined when you want something to happen when an object is dropped. The first argument is the event object and the second is the data being dragged. The third argument is the drag session. getSupportedFlavours
() This function should return a list of flavors that the object being dragged over can accept. This function takes no arguments. This function is necessary so that the wrapper can determine the best flavour to pass to the other functions. For an observer that is observing an element that can start a drag, you should define at least the onDragStart function. For elements that can have objects drop...
...ged. To do this, add data and flavours to the transferData object, which is the second argument to onDragStart. An example should help here. The onDragStart function adds data to the transferData object. var textObserver = { onDragStart: function (event, transferData, action) { var htmlText = "<strong>Cabbage</strong>"; var plainText = "Cabbage"; transferData.data = new TransferData
(); transferData.data.addDataForFlavour("text/html",htmlText); transferData.data.addDataForFlavour("text/unicode",plainText); } } Here, an observer has been declared and stored in the variable textObserver. It has one property called onDragStart. (In JavaScript, properties can be declared with the syntax name : value). This property is a function which sets the data that is being dragged.
...ch. In this case above, the HTML flavour (text/html) comes first and then the text flavour (text/unicode). The example below shows how to set the data to be dragged from the element's label attribute. In this case we only provide the data in one flavour. var textObserver = { onDragStart: function (event) { var txt = event.target.getAttribute("label"); transferData.data = new TransferData
(); transferData.data.addDataForFlavour("text/unicode",txt); } } This might be useful when implementing drag and drop for cells in a tree. You can use the value of a cell, or some resource from an RDF file if the tree is built from a template, as the value of a drag. If you store it as a string, any object that accepts strings dragged onto it can grab the dragged data. If you want to send mor...
...And 5 more matches
Using microformats - Archive of obsolete content
efined microformats Firefox 3 provides definitions implementing several common microformats: adr Represents an address (such as a street or mailing address). geo Represents a geographical location using latitude and longitude. hCard Represents contact information for a person. hCalendar Represents a calendar appointment entry. tag Used to add tags to other microformats. ...
... var numMicroformats = Microformats.count(name, rootElement, options); Parameters name The name of the microformat to count. rootElement Required. The DOM element at which to begin the search. If you want to search the entire document, specify content.document. options Optional. ...
...rseExternalFrames If true, child frames are included in the search. The default is true. showHidden If true, hidden microformats are added; otherwise they're left out. The default is false. debug Specify true if debug mode is in use; otherwise, specify false. The default is false. Return value An integer value indicating the number of microformats that match the specified criteria. ...
...And 5 more matches
Twitter - Archive of obsolete content
r, is a very simple, lightweight layer on top of Twitter's REST API. In fact it's hardly more than syntactic sugar for doing XMLHttpRequests. To use this library, you therefore need to be familiar with Twitter's own API. (It's easy!) Methods Each method in Twitter's API maps to a method here. For example, the Twitter method for tweeting, statuses/update, maps to jetpack.lib.twitter.statuses.update
(). To call trends/current, use jetpack.lib.twitter.trends.current
(). For search, jetpack.lib.twitter.search
(). Replace slashes with dots. Most of Twitter's methods are supported, but not all. List methods, spam reporting methods, and OAuth are not currently supported. If something is not supported but you would like it to be, please file a bug. (Or write a patch!) Arguments Each and every meth...
... so you would define an id property and set its value to a user's ID. (You can read about the parameters of the various methods at Twitter's API reference.) There are two special, optional properties: success and error. success is a function that's called when the request successfully completes, and error is a function called when it fails to complete. The library simply passes them to jQuery.ajax
(), and so they are called like so: success(data, textStatus) data is Twitter's decoded JSON response. textStatus is a simple string describing the status. error(xmlHttpRequest, textStatus, errorThrown) xmlHttpRequest is the XHR used in the request. textStatus is a simple string describing the type of error. errorThrown is an exception object, if one was thrown. The examples below all use th...
... JSON response. textStatus is a simple string describing the status. error(xmlHttpRequest, textStatus, errorThrown) xmlHttpRequest is the XHR used in the request. textStatus is a simple string describing the type of error. errorThrown is an exception object, if one was thrown. The examples below all use this first, simpler style. The second style will be familiar if you have used jQuery.ajax
() -- in fact the object is passed as-is (almost) to it. In other words, define a data property that is itself an object whose properties correspond to the parameters of the Twitter method. With this style you can use any of the various jQuery.ajax
() options in your request: data, success, complete, etc. Example: jetpack.lib.twitter.statuses.update({ data: { status: "O frabjous day!" }, us...
...And 5 more matches
Simple Storage - Archive of obsolete content
a jetpack can set whatever properties it wants on it. To manipulate its persistent data, a jetpack therefore need only use the various standard JavaScript functions and operators. The jetpack.simple.storage object is automatically and periodically flushed to disk. How and when it is flushed is an implementation detail. Jetpacks can flush it manually, however, by calling jetpack.storage.simple.sync
(). The object can also be forced to reload its data from disk by calling jetpack.storage.simple.open
(), although the data comes loaded automatically. Don't abuse these methods, since they cause Firefox -- all of Firefox -- to drop what it's doing to make a trip to the disk. If you call them too often, Firefox may become unresponsive for some of your users. Unless you are doing something strange, le...
...s, since they cause Firefox -- all of Firefox -- to drop what it's doing to make a trip to the disk. If you call them too often, Firefox may become unresponsive for some of your users. Unless you are doing something strange, let Jetpack flush your data for you. The namespace currently lives in the future and must be imported before it is used: jetpack.future.import("storage.simple"); Methods sync
()As described above, the jetpack.storage.simple object is automatically written to disk, but a feature may force flush by calling jetpack.storage.simple.sync
(). Don't abuse this method. open
()As described above, the jetpack.storage.simple object is automatically populated when a feature is loaded, but a feature may force the object to read from disk by calling jetpack.storage.simple.open
(). Don't a...
...rage.simple");// Create the persistent notes array if it doesn't already exist.jetpack.storage.simple.notes = jetpack.storage.simple.notes || [];var notes = jetpack.storage.simple.notes;// Updates the Jetpack menu with the current notes. We'll add a Notes menu with// a submenu, which lists all the notes. If there are no notes, we'll show a// disabled "(Empty)" menuitem.function updateJetpackMenu
() { jetpack.menu.set({ label: "Notes", menu: new jetpack.Menu(notes.length > 0 ? notes : [{ label: "(Empty)", disabled: true }]) });}// Modify the page's context menu by sneaking in before it's shown. If there's// a selection, add a Note menuitem that makes a new note. Otherwise, don't// modify the menu at all. We'll limit the number of...
...And 5 more matches
Simple Storage - Archive of obsolete content
a jetpack can set whatever properties it wants on it. To manipulate its persistent data, a jetpack therefore need only use the various standard JavaScript functions and operators. The jetpack.simple.storage object is automatically and periodically flushed to disk. How and when it is flushed is an implementation detail. Jetpacks can flush it manually, however, by calling jetpack.storage.simple.sync
(). The object can also be forced to reload its data from disk by calling jetpack.storage.simple.open
(), although the data comes loaded automatically. Don't abuse these methods, since they cause Firefox -- all of Firefox -- to drop what it's doing to make a trip to the disk. If you call them too often, Firefox may become unresponsive for some of your users. Unless you are doing something strange, le...
...s, since they cause Firefox -- all of Firefox -- to drop what it's doing to make a trip to the disk. If you call them too often, Firefox may become unresponsive for some of your users. Unless you are doing something strange, let Jetpack flush your data for you. The namespace currently lives in the future and must be imported before it is used: jetpack.future.import("storage.simple"); Methods sync
()As described above, the jetpack.storage.simple object is automatically written to disk, but a feature may force flush by calling jetpack.storage.simple.sync
(). Don't abuse this method. open
()As described above, the jetpack.storage.simple object is automatically populated when a feature is loaded, but a feature may force the object to read from disk by calling jetpack.storage.simple.open
(). Don't a...
...le"); // Create the persistent notes array if it doesn't already exist. jetpack.storage.simple.notes = jetpack.storage.simple.notes || []; var notes = jetpack.storage.simple.notes; // Updates the Jetpack menu with the current notes. We'll add a Notes menu with // a submenu, which lists all the notes. If there are no notes, we'll show a // disabled "(Empty)" menuitem. function updateJetpackMenu
() { jetpack.menu.set({ label: "Notes", menu: new jetpack.Menu(notes.length > 0 ? notes : [{ label: "(Empty)", disabled: true }]) }); } // Modify the page's context menu by sneaking in before it's shown. If there's // a selection, add a Note menuitem that makes a new note. Otherwise, don't // modify the menu at all. We'll limit th...
...And 5 more matches
Focus and Selection - Archive of obsolete content
the focus is removed from an element. You can respond to focus changes by adding an onfocus or onblur attribute on an element. They work just like their HTML counterparts. You might use these event handlers to highlight the element or display text on a status bar. The following example can be used to apply a function to handle a focus event. Example 2 : Source View <script> function displayFocus
(){ var elem=document.getElementById('sbar'); elem.setAttribute('value','Enter your phone number.'); } </script> <textbox id="tbox1"/> <textbox id="tbox2" onfocus="displayFocus
();"/> <description id="sbar" value=""/> The focus event, when it occurs, will call the displayFocus function. This function will change the value of the text label. We could extend this example to remove the text when ...
...r now, we'll look at some of the focus related features of the command dispatcher. You can retrieve the command dispatcher from a window using the document's commandDispatcher property. From there, you can get the focused element with the dispatcher's focusedElement property. The example below shows this. ...
...mand dispatcher from a window using the document's commandDispatcher property. From there, you can get the focused element with the dispatcher's focusedElement property. The example below shows this. ...
...And 5 more matches
Tree View Details - Archive of obsolete content
the next sibling's row index would be in such a case. Example of Hierarchical Custom View Let's put this together into a simple example that takes an array and constructs a tree from it. This tree will only support a single parent level with an inner child level, but it could be extended to support additional levels without too much effort. We'll examine it piece by piece. <window onload="init
();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <tree id="elementList" flex="1"> <treecols> <treecol id="element" label="Element" primary="true" flex="1"/> </treecols> <treechildren/> </tree> </window> We use a simple tree here with no data in the treechildren. The 'init' function is called when the window is loaded to initialize the tree. It simply ...
...cols> <treecol id="element" label="Element" primary="true" flex="1"/> </treecols> <treechildren/> </tree> </window> We use a simple tree here with no data in the treechildren. The 'init' function is called when the window is loaded to initialize the tree. It simply sets the custom view by retrieving the tree and setting its 'view' property. We will define 'treeView' next. function init
() { document.getElementById("elementList").view = treeView; } The custom tree view will need to implement a number of methods, of which the important ones will be examined individually. First we'll define two structures to hold the data for the tree, the first will hold a map between parents and the children they contain, and the second will hold an array of the visible items. Remember that a c...
...e array size by one. The two booleans in each row in the visibleData structure indicate whether a row is a container and whether it is open respectively. Obviously, the new inserted child items will have both values set to false. Implement the Tree View Interface Next, we need to implement the tree view interface. ...
...And 5 more matches
-moz-border-bottom-colors - Archive of obsolete content
e is dashed or dotted. to tables with border-collapse: collapse. Syntax Values Accepts a white-space separated list of color values. <color> Specifies the color of a line of pixels of the bottom border. transparent is valid. See <color> values for possible units. none Default, no colors are drawn or border-color is used, if specified. ...
... or dotted. to tables with border-collapse: collapse. Syntax Values Accepts a white-space separated list of color values. <color> Specifies the color of a line of pixels of the bottom border. transparent is valid. See <color> values for possible units. none Default, no colors are drawn or border-color is used, if specified. ...
.... to tables with border-collapse: collapse. Syntax Values Accepts a white-space separated list of color values. <color> Specifies the color of a line of pixels of the bottom border. transparent is valid. See <color> values for possible units. none Default, no colors are drawn or border-color is used, if specified. ...
...And 5 more matches
-moz-border-left-colors - Archive of obsolete content
yle is dashed or dotted. to tables with border-collapse: collapse. Syntax Values Accepts a white-space separated list of color values. <color> Specifies the color of a line of pixels of the left border. transparent is valid. See <color> values for possible units. none Default, no colors are drawn or border-color is used, if specified. ...
...ed or dotted. to tables with border-collapse: collapse. Syntax Values Accepts a white-space separated list of color values. <color> Specifies the color of a line of pixels of the left border. transparent is valid. See <color> values for possible units. none Default, no colors are drawn or border-color is used, if specified. ...
...ed. to tables with border-collapse: collapse. Syntax Values Accepts a white-space separated list of color values. <color> Specifies the color of a line of pixels of the left border. transparent is valid. See <color> values for possible units. none Default, no colors are drawn or border-color is used, if specified. ...
...And 5 more matches
-moz-border-right-colors - Archive of obsolete content
le is dashed or dotted. to tables with border-collapse: collapse. Syntax Values Accepts a white-space separated list of color values. <color> Specifies the color of a line of pixels of the right border. transparent is valid. See <color> values for possible units. none Default, no colors are drawn or border-color is used, if specified. ...
...d or dotted. to tables with border-collapse: collapse. Syntax Values Accepts a white-space separated list of color values. <color> Specifies the color of a line of pixels of the right border. transparent is valid. See <color> values for possible units. none Default, no colors are drawn or border-color is used, if specified. ...
...d. to tables with border-collapse: collapse. Syntax Values Accepts a white-space separated list of color values. <color> Specifies the color of a line of pixels of the right border. transparent is valid. See <color> values for possible units. none Default, no colors are drawn or border-color is used, if specified. ...
...And 5 more matches
-moz-border-top-colors - Archive of obsolete content
tyle is dashed or dotted. to tables with border-collapse: collapse. Syntax Values Accepts a white-space separated list of color values. <color> Specifies the color of a line of pixels of the top border. transparent is valid. See <color> values for possible units. none Default, no colors are drawn or border-color is used, if specified. ...
...hed or dotted. to tables with border-collapse: collapse. Syntax Values Accepts a white-space separated list of color values. <color> Specifies the color of a line of pixels of the top border. transparent is valid. See <color> values for possible units. none Default, no colors are drawn or border-color is used, if specified. ...
...ted. to tables with border-collapse: collapse. Syntax Values Accepts a white-space separated list of color values. <color> Specifies the color of a line of pixels of the top border. transparent is valid. See <color> values for possible units. none Default, no colors are drawn or border-color is used, if specified. ...
...And 5 more matches
-ms-scrollbar-3dlight-color - Archive of obsolete content
soft extension specifying the color of the top and left edges of the scroll box and scroll arrows of a scroll bar. Initial valuedepends on user agentApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the top and left edges of the scroll box and scroll arrows of the scroll bar. ...
...ion specifying the color of the top and left edges of the scroll box and scroll arrows of a scroll bar. Initial valuedepends on user agentApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the top and left edges of the scroll box and scroll arrows of the scroll bar. ...
...ying the color of the top and left edges of the scroll box and scroll arrows of a scroll bar. Initial valuedepends on user agentApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the top and left edges of the scroll box and scroll arrows of the scroll bar. ...
...And 5 more matches
-ms-scrollbar-arrow-color - Archive of obsolete content
The -ms-scrollbar-arrow-color CSS property is a Microsoft extension that specifies the color of the arrow elements of a scroll arrow. Initial valueButtonTextApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the scroll arrows of the scroll bar. ...
... The -ms-scrollbar-arrow-color CSS property is a Microsoft extension that specifies the color of the arrow elements of a scroll arrow. Initial valueButtonTextApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the scroll arrows of the scroll bar. ...
... The -ms-scrollbar-arrow-color CSS property is a Microsoft extension that specifies the color of the arrow elements of a scroll arrow. Initial valueButtonTextApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the scroll arrows of the scroll bar. ...
...And 5 more matches
-ms-scrollbar-base-color - Archive of obsolete content
The -ms-scrollbar-base-color CSS property is a Microsoft extension that specifies the base color of the main elements of a scroll bar. Initial valuedepends on user agentApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The base color of the main elements of a scroll bar. ...
... The -ms-scrollbar-base-color CSS property is a Microsoft extension that specifies the base color of the main elements of a scroll bar. Initial valuedepends on user agentApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The base color of the main elements of a scroll bar. ...
... -ms-scrollbar-base-color CSS property is a Microsoft extension that specifies the base color of the main elements of a scroll bar. Initial valuedepends on user agentApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The base color of the main elements of a scroll bar. ...
...And 5 more matches
-ms-scrollbar-darkshadow-color - Archive of obsolete content
The -ms-scrollbar-darkshadow-color CSS property is a Microsoft extension that specifies the color of a scroll bar's gutter. Initial valueThreeDDarkShadowApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the scroll bar's gutter. ...
... The -ms-scrollbar-darkshadow-color CSS property is a Microsoft extension that specifies the color of a scroll bar's gutter. Initial valueThreeDDarkShadowApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the scroll bar's gutter. ...
... The -ms-scrollbar-darkshadow-color CSS property is a Microsoft extension that specifies the color of a scroll bar's gutter. Initial valueThreeDDarkShadowApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the scroll bar's gutter. ...
...And 5 more matches
-ms-scrollbar-face-color - Archive of obsolete content
The -ms-scrollbar-face-color CSS property is a Microsoft extension that specifies the color of the scroll box and scroll arrows of a scroll bar. Initial valueThreeDFaceApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the scroll box and scroll arrows. ...
... The -ms-scrollbar-face-color CSS property is a Microsoft extension that specifies the color of the scroll box and scroll arrows of a scroll bar. Initial valueThreeDFaceApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the scroll box and scroll arrows. ...
... The -ms-scrollbar-face-color CSS property is a Microsoft extension that specifies the color of the scroll box and scroll arrows of a scroll bar. Initial valueThreeDFaceApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the scroll box and scroll arrows. ...
...And 5 more matches
-ms-scrollbar-highlight-color - Archive of obsolete content
of the slider tray, the top and left edges of the scroll box, and the scroll arrows of a scroll bar. Initial valueThreeDHighlightApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the slider tray, the top and left edges of the scroll box, and the scroll arrows of a scroll bar. ...
...er tray, the top and left edges of the scroll box, and the scroll arrows of a scroll bar. Initial valueThreeDHighlightApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the slider tray, the top and left edges of the scroll box, and the scroll arrows of a scroll bar. ...
...he top and left edges of the scroll box, and the scroll arrows of a scroll bar. Initial valueThreeDHighlightApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the slider tray, the top and left edges of the scroll box, and the scroll arrows of a scroll bar. ...
...And 5 more matches
-ms-scrollbar-shadow-color - Archive of obsolete content
extension that specifies the color of the bottom and right edges of the scroll box and scroll arrows of a scroll bar. Initial valueThreeDDarkShadowApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the bottom and right edges of the scroll box and scroll arrows of a scroll bar. ...
...hat specifies the color of the bottom and right edges of the scroll box and scroll arrows of a scroll bar. Initial valueThreeDDarkShadowApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the bottom and right edges of the scroll box and scroll arrows of a scroll bar. ...
...ies the color of the bottom and right edges of the scroll box and scroll arrows of a scroll bar. Initial valueThreeDDarkShadowApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the bottom and right edges of the scroll box and scroll arrows of a scroll bar. ...
...And 5 more matches
-ms-scrollbar-track-color - Archive of obsolete content
The -ms-scrollbar-track-color CSS property is a Microsoft extension that specifies the color of the track element of a scrollbar. Initial valueScrollbarApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the track element. ...
... The -ms-scrollbar-track-color CSS property is a Microsoft extension that specifies the color of the track element of a scrollbar. Initial valueScrollbarApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the track element. ...
... The -ms-scrollbar-track-color CSS property is a Microsoft extension that specifies the color of the track element of a scrollbar. Initial valueScrollbarApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Syntax Values <color> The color of the track element. ...
...And 5 more matches
E4X for templating - Archive of obsolete content
of JavaScript 1.8 expression closures), the templates can function more dynamically, offering the power and readability of templating languages such as Smarty for PHP (though admittedly without the currently wider cross-browser support of XSLT or the strictly-XML approach of PHPTAL or Seethrough templating). ...
... ...
...e(msg); } For example, <toolbarbutton label={$S('myToolbar.label')}/> Conditionals function _if (cond, h, _else) { if (cond && cond != undefined) { // We need undefined condition for E4X return h(cond); } else if (_else) { return _else(cond); } return ''; // Empty string allows conditions in attribute as well as element content } For example: {_if(elems.length
(), function
() <description>{elems[0]}</description>, function _else
() <label>No data</label> )} Note that the simple XMLList
() constructor (<></>) may be useful to still be able to use an expression closure (i.e., without needing return statements and braces): {_if(elems.length
(), function
() <> <markup/> <markup/> </>)} Note that, while it is convenient to store such...
...And 5 more matches
New in JavaScript 1.2 - Archive of obsolete content
NGUAGE="JavaScript1.2"> <!-- JavaScript for Navigator 4.0. --> New features in JavaScript 1.2 New objects You can create objects using literal notation (inspired by dictionary literal syntax from Python 1.x). Arrays can now be created using literal notation (inspired by list literal syntax from Python 1.x). ...
...!-- JavaScript for Navigator 4.0. --> New features in JavaScript 1.2 New objects You can create objects using literal notation (inspired by dictionary literal syntax from Python 1.x). Arrays can now be created using literal notation (inspired by list literal syntax from Python 1.x). ...
...0. --> New features in JavaScript 1.2 New objects You can create objects using literal notation (inspired by dictionary literal syntax from Python 1.x). Arrays can now be created using literal notation (inspired by list literal syntax from Python 1.x). ...
...And 5 more matches
XForms Custom Controls - Archive of obsolete content
ut xbl:inherits="ref=ref1" anonid="ref1"/> <xf:input xbl:inherits="ref=ref2" anonid="ref2"/> </content> <implementation> <method name="refresh"> <body> // Here we should refresh custom control. </body> </method> <constructor> // We should redirect calls of input's 'refresh' method to custom control 'refresh' method. ...
... anonid="ref1"/> <xf:input xbl:inherits="ref=ref2" anonid="ref2"/> </content> <implementation> <method name="refresh"> <body> // Here we should refresh custom control. </body> </method> <constructor> // We should redirect calls of input's 'refresh' method to custom control 'refresh' method. ...
...fresh method will be called by the processor. Below is the structure of the interface. As always, please refer directly to the source code to be sure that you are using the latest, up-to-date version: extensions/xforms/nsIXFormsUIWidget.idl. interface nsIXFormsUIWidget : nsIDOMElement { /** * Is called when control should be updated to reflect the value of the bound node. ...
...And 5 more matches
Parsing microformats in JavaScript - Archive of obsolete content
Firefox 3 introduces a new API for managing and parsing microformats. This article examines the generic microformat parsing API, which handles the heavy lifting of pulling data out of a microformat. This API is primarily intended to be used when implementing new microformats. Methods dateTimeGetter
() Specifically retrieves a date from a microformat node. After getting the text, it is normalized into an ISO 8601 date. ...
...ext, it is normalized into an ISO 8601 date. normalizedDate = Microformats.parser.dateTimeGetter(propnode, parentnode); Parameters propnode The DOM node to check. parentnode The property's parent node. If it is a subproperty, this is the parent property node. Otherwise this is the microformat node. Return value A string containing the normalized date. defaultGetter
() Uses the microformat patterns to decide what the correct text for a given microformat property is. This includes looking at thing such as abbr, img and alt, area and alt, and value excerpting. propertyValue = Microformats.parser.defaultGetter(propnode, parentnode, datatype); Parameters propnode The DOM node to check. parentnode The property's parent node. If it is ...
...and alt, and value excerpting. propertyValue = Microformats.parser.defaultGetter(propnode, parentnode, datatype); Parameters propnode The DOM node to check. parentnode The property's parent node. If it is a subproperty, this is the parent property node. Otherwise this is the microformat node. datatype "HTML" if the search should be done using innerHTML
(), or "text" to use innerText
(). The default is "text". Return value A string containing the property's value. emailGetter
() Specifically retrieves an email address from a microformat node. This removes the subject if one is specified, as well as the mailto: prefix. email = Microformats.parser.emailGetter(propnode, parentnode); Parameters propnode The DOM node to check. pare...
...And 5 more matches
GLSL Shaders - Game development
PU. This allows the CPU to focus its processing power on other tasks, like executing code. Vertex shaders Vertex shaders manipulate coordinates in a 3D space and are called once per vertex. The purpose of the vertex shader is to set up the gl_Position variable -- this is a special, global, and built-in GLSL variable. gl_Position is used to store the position of the current vertex. The void main
() function is a standard way of defining the gl_Position variable. Everything inside void main
() will be executed by the vertex shader. A vertex shader yields a variable containing how to project a vertex's position in 3D space onto a 2D screen. Fragment shaders Fragment (or texture) shaders define RGBA (red, blue, green, alpha) colors for each pixel being processed -- a single fragment shader ...
...haders. Go to the cube.html file on GitHub, copy all the JavaScript code from inside the second <script> element, and paste it into the third <script> element of the current example. Save and load index.html in your browser -- you should see a blue cube. The vertex shader code Let's continue by writing a simple vertex shader -- add the code below inside the body's first <script> tag: void main
() { gl_Position = projectionMatrix * modelViewMatrix * vec4(position.x+10.0, position.y, position.z+5.0, 1.0); } The resulting gl_Position is calculated by multiplying the model-view and the projection matrices by each vector to get the final vertex position, in each case. Note: You can learn more about model, view, and projection transformations from the vertex processing paragraph, and you c...
...ts along the x axis and 5 units along the z axis, translated via a shader. We can ignore the fourth parameter and leave it with the default 1.0 value; this is used to manipulate the clipping of the vertex position in the 3D space, but we don't need in our case. The texture shader code Now we'll add the texture shader to the code -- add the code below to the body's second <script> tag: void main
() { gl_FragColor = vec4(0.0, 0.58, 0.86, 1.0); } This will set an RGBA color to recreate the current light blue one -- the first three float values (ranging from 0.0 to 1.0) represent the red, green, and blue channels while the fourth one is the alpha transparency (ranging from 0.0 -- fully transparent -- to 1.0 -- fully opaque). Applying the shaders To actually apply the newly created shaders...
...And 5 more matches
Extra lives - Game development
ostText; These respectively will store the number of lives, the text label that displays the number of lives that remain, and a text label that will be shown on screen when the player loses one of their lives. Defining the new text labels Defining the texts look like something we already did in the score lesson. ...
...font: '18px Arial', fill: '#0095DD' }); lifeLostText.anchor.set(0.5); lifeLostText.visible = false; The livesText and lifeLostText objects look very similar to the scoreText one -- they define a position on the screen, the actual text to display, and the font styling. The former is anchored on its top right edge to align properly with the screen, and the latter is centered, both using anchor.set
(). The lifeLostText will be shown only when the life is lost, so its visibility is initially set to false. Making our text styling DRY As you probably noticed we're using the same styling for all three texts: scoreText, livesText and lifeLostText. If we ever want to change the font size or color we will have to do it in multiple places. To make it easier for us to maintain in the future we can c...
...eLostText.anchor.set(0.5); lifeLostText.visible = false; This way changing the font in one variable will apply the changes to every place it is used. The lives handling code To implement lives in our game, let's first change the ball's function bound to the onOutOfBounds event. ...
...And 5 more matches
First-class Function - MDN Web Docs Glossary: Definitions of Web-related terms
A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. Example | Assign a function to a variable JavaScript const foo = function
() { console.log("foobar"); } // Invoke it using the variable foo
(); We assigned an Anonymous Function in a Variable, then we used that variable to invoke the function by adding parentheses
() at the end. Even if your function was named, you can use the variable name to invoke it. Naming it will be helpful when debugging your code. But it won't affect the way we invoke it. Example | Pass a function as...
...variable foo
(); We assigned an Anonymous Function in a Variable, then we used that variable to invoke the function by adding parentheses
() at the end. Even if your function was named, you can use the variable name to invoke it. Naming it will be helpful when debugging your code. But it won't affect the way we invoke it. Example | Pass a function as an Argument JavaScript function sayHello
() { return "Hello, "; } function greeting(helloMessage, name) { console.log(helloMessage
() + name); } // Pass `sayHello` as an argument to `greeting` function greeting(sayHello, "JavaScript!"); We are passing our sayHello
() function as an argument to the greeting
() function, this explains how we are treating the function as a value. The function that we pass as an argument to another funct...
... A function that returns a function is called a Higher-Order Function. ...
...And 5 more matches
Browser chrome 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="content" in browser.xul). Note: Be careful when naming ...
...t harness. Using a descriptive file name is strongly encouraged instead of just using a bug number. You can collect common utils and helpers in a file called head.js, that must live in the same folder as the browser-chrome tests. This file will be injected into the test scope for each test living in the same folder. Notice that any function call in head.js main scope will run before the main test
() method. Asynchronous tests When writing async tests, you can use the add_task method with Promises. The test suite also supports asynchronous tests, using the same function names as Mochitest. Call waitForExplicitFinish
() from test
() if you want to delay reporting a result until after test
() has returned. Call finish
() once the test is complete. Be aware that the test harness will mark tests t...
... Promises. The test suite also supports asynchronous tests, using the same function names as Mochitest. Call waitForExplicitFinish
() from test
() if you want to delay reporting a result until after test
() has returned. Call finish
() once the test is complete. Be aware that the test harness will mark tests that take too long to complete as FAILED (the current timeout is 30 seconds). function test
() { waitForExplicitFinish
(); setTimeout(completeTest, 1000); } function completeTest
() { ok(true, "Timeout ran"); finish
(); } If your test is randomly timing out and you think that's just due to it taking too long, you can extend the timeout. Be aware that this is not a solution; you should investigate why your test is taking so long, since it's most likely due to a bad test desig...
...And 5 more matches
Addon
consumers should take care to verify the existence of these methods or properties before relying on them. ...
...erify the existence of these methods or properties before relying on them. Overview of required methods void isCompatibleWith(in string appVersion, in string platformVersion) void findUpdates(in UpdateListener listener, in integer reason, in string appVersion, in string platformVersion) Overview of optional methods void uninstall
() void cancelUninstall
() boolean hasResource(in string path) nsIURI getResourceURI(in string path) void getDataDirectory(in DataDirectoryCallback callback) Required properties Attribute Type Description appDisabled Read only boolean True if this add-on cannot be used in the application based on version compatibility, dependencies, and blocklisting. ...
...nly 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 Description aboutURL Read only string The URL of the about dialog to display for this add-on. This is passed to window.openDialog
() when presenting the about dialog. If you don't provide an aboutURL, a generic about dialog is displayed. The dialog receives the Addon object representing your add-on as a parameter. applyBackgroundUpdates integer Indicates whether updates found in the background for this add-on will be applied automatically. See auto update values. The user is provided a UI for this in the add-ons...
...And 5 more matches
PopupNotifications.jsm
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. ...
...ge
(); Notification getNotification(id, browser); void remove(notification); Notification show(browser, id, message, anchorID, mainAction, secondaryActions, options); Properties Attribute Type Description isPanelOpen Boolean Returns true if the notification panel is currently visible, false if it is not. Methods locationChange
() The consumer can call this method to let the popup notification module know that the current browser's location has changed. This lets the notification service update the active notifications as appropriate. Note: You shouldn't need to call this when using the PopupNotifications object in Firefox windows; Firefox code takes care of this automatically. ...
... Notification getNotification( string id XULElement browser ); Parameters id The Notification ID to search for. browser The XUL <xul:browser> element whose notifications should be searched. ...
...And 5 more matches
Promise
A Promise object represents a value that may not be available yet. A reference to an existing promise may be received by different means, for example as the return value of a call into an asynchronous API. Once you have a reference to a promise, you can call its then
() method to execute an action when the value becomes available, or when an error occurs. Promises may also be created using the new Promise
() constructor. You don't need to import the Promise.jsm module to use a Promise object to which you already have a reference. Internally, a promise can be in one of three states: Pending, when the final value is not available yet. This is the only state that may transition to one of the other two states. Fulfilled, when and if the final value becomes available. A fulfillment v...
...lving functions as its two arguments: executor(resolve, reject); The constructor will not return until the executor has completed. The resolving functions can be used at any time, before or after the executor has completed, to control the final state of the promise. If the executor throws an exception, its value will be passed to the reject resolving function. Resolving functions resolve
() Fulfills the associated promise with the specified value, or propagates the state of an existing promise. If the associated promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. Note: Calling this method with a pending promise as the aValue argument, and then calling it again with another value before the promise is fulfilled or rejecte...
... already resolved to the pending promise. void resolve( aValue ); Parameters aValue Optional If this value is not a promise, including undefined, it becomes the fulfillment value of the associated promise. If this value is a promise, then the associated promise will be resolved to the passed promise, and follow the state as the provided promise (including any future transitions). reject
() Rejects the associated promise with the specified reason. If the promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. void reject( aReason ); Parameters aReason Optional The rejection reason for the associated promise. Although the reason can be undefined, it is generally an Error object, like in exception handling. Note: T...
...And 5 more matches
Using JavaScript code modules
sed 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, objects, constants, and any other JavaScript type. The module also defi...
...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. ...
...odule, be sure to change the application's build ID (e.g., the version) before your next test run; otherwise, you may find yourself running the previous version of your module's code. The URL for a code module As you can see from the example above, you need a URL to import a code module. (The URL in the example is "resource://app/my_module.jsm".) Code modules can only be loaded using a chrome:
(), resource:, or file: URL. If you're writing an extension for Firefox 4 and already have a chrome.manifest with a content instruction in it, you can put the code module in your content folder and reference it like your other content files via chrome://<yourextension>/content/<yourmodule>.jsm. If your extension or application needs to support Mozilla 1.9.x (Firefox 3.x), you should register a n...
...And 5 more matches
Webapps.jsm
The Webapps.jsm modules exposes the DOMApplicationRegistry, which is responsible for managing all of the Open Web Apps. ...
... The Webapps.jsm modules exposes the DOMApplicationRegistry, which is responsible for managing all of the Open Web Apps. ...
... The Webapps.jsm modules exposes the DOMApplicationRegistry, which is responsible for managing all of the Open Web Apps. ...
...And 5 more matches
Creating localizable web applications
come from an early version of the getpersonas.com website. In some cases, the code snippets were slightly changed to better illustrate the recommendations or for clarity. Cheatsheet Don't hardcode English text, formats (numbers, dates, addresses, etc.), word order or sentence structure. Don't put text or numbers in images. Don't forget about right-to-left locales. Take advantage of printf
() (or equivalents) and use variables in the English strings. Write semantic code (e.g. don't use text and <img/> for decorations; instead, use CSS). Document your code so that localizers know what they're translating (e.g. in gettext use comments and contexts). App Logic Detect the locale correctly Be smart about detecting the user's locale correctly. You can use one or more of the following ...
...text on some pages (e.g. because they contain a lot of text and localizing source HTML is easier), make sure to keep the code responsible for application logic separate from the localizable content. The logic of the website should not be exposed directly in the localization files, to avoid any accidental changes by localizers. Snippet 1. Bad: require_once('lib/user.php'); $user = new PersonaUser
(); Snippet 2. Good: require_once('templates/footer.php'); If it's not possible to remove the app logic code, you should consider using gettext. Gettext extracts localizable content form the source files, thus making it impossible for localizers to accidentally change them. You can learn more about the choice of the format for your project at File formats. Text messages Don't hardcode English c...
... is as easy as localizing any other string. Just let the localizers localize the format specification string. Snippet 1. Bad: $persona['date'] = date("n/j/Y", strtotime($persona['approve'])); Snippet 2. ...
...And 5 more matches
MathML Demo: <mspace> - space
ellow for easier viewing. You can set the width ? x y height ? x y and depth [ x y ] of mspace elements (click the math text to view the numeric values that are set). Interactive Sizing HTML Content <p> Use the control buttons below to adjust the parameters of the <code>mspace</code> element and see the effects. ...
... and depth [ x y ] of mspace elements (click the math text to view the numeric values that are set). Interactive Sizing HTML Content <p> Use the control buttons below to adjust the parameters of the <code>mspace</code> element and see the effects. ...
...c values that are set). Interactive Sizing HTML Content <p> Use the control buttons below to adjust the parameters of the <code>mspace</code> element and see the effects. ...
...And 5 more matches
Refcount tracing and balancing
will log stack traces to refcounts.log for the 2nd nsDocShell object that gets allocated, and nothing else. Post-processing step 1: finding the leakers First you have to figure out which objects leaked. The script tools/rb/find_leakers.py does this. It grovels through the log file, and figures out which objects got allocated (it knows because they were just allocated because they got AddRef
()-ed and their refcount became 1). It adds them to a list. When it finds an object that got freed (it knows because its refcount goes to 0), it removes it from the list. Anything left over is leaked. The scripts output looks like the following. 0x00253ab0 (1) 0x00253ae0 (2) 0x00253bd0 (4) The number in parentheses indicates the order in which it was allocated, if you care. Pick one of these poi...
... Linux Users The log file generated on Linux system often lack function names, file names and line numbers. Linux users need to run a script to fix the call stack. python tools/rb/fix_stacks.py < ./refcounts.log > fixed_stack.log Post-processing step 3: building the balance tree Now that you've the log file fully prepared, you can build a balance tree. This process takes all the stack AddRef
() and Release
() stack traces and munges them into a call graph. Each node in the graph represents a call site. Each call site has a balance factor, which is positive if more AddRef
()s than Release
()es have happened at the site, zero if the number of AddRef
()s and Release
()es are equal, and negative if more Release
()es than AddRef
()s have happened at the site. To build the balance tree, run tools/r...
...tree, run tools/rb/make-tree.pl, specifying the object of interest. For example: perl -w tools/rb/make-tree.pl --object 0x00253ab0 < my-leak.log This will build an indented tree that looks something like this (except probably a lot larger and leafier): .root: bal=1 main: bal=1 DoSomethingWithFooAndReturnItToo: bal=2 NS_NewFoo: bal=1 Let's pretend in our toy example that NS_NewFoo
() is a factory method that makes a new foo and returns it. DoSomethingWithFooAndReturnItToo
() is a method that munges the foo before returning it to main
(), the main program. What this little tree is telling you is that you leak one refcount overall on object 0x00253ab0. But, more specifically, it shows you that: NS_NewFoo
() "leaks" a refcount. This is probably "okay" because it's a factory met...
...And 5 more matches
Optimizing Applications For NSPR
but there is always room for improvement. The casual client may not encounter a need to know the details of the shortcomings to the level described here, but if and when clients become more sophisticated, these issues will certainly surface. This memo is by no way complete. Multiplatform Do not call any blocking system call from a local thread. The only exception to this rule is the <tt>select
()</tt> and <tt>poll
()</tt> system calls on Unix, both of which NSPR has overridden to make sure they are aware of the NSPR local threads. In the combined (MxN) model, which includes NT, IRIX (sprocs), and pthreads-user, the primordial thread is always a local thread. Therefore, if you call a blocking system call from the primordial thread, it is going to block more than just the primordial thread ...
...e system call in that thread, and have the primordial thread join that thread. NSPR uses timer signals to implement thread preemption for local threads on some platforms. If all the software linked into the application is not ported to the NSPR API, the application may fail because of threads being preempted during critical sections. To disable thread preemption call <tt>PR_DisableClockInterrupts
()</tt>during initialization. Interrupting threads (via <tt>PR_Interrupt
()</tt>) on threads blocked in I/O functions is implemented to various degrees on different platforms. The UNIX based platforms all implement the function though there may be up to a 5 second delay in processing the request. The mechanism used to implement <tt>PR_Interrupt
()</tt> on the pthreads versions of NSPR is flawed. No ...
...an application by a shared library require an additional function prolog. The prolog is presented in the macro <tt>PR_CALLBACK</tt>. For any function made available to any shared library (most likely passed in as a function pointer), that function must have the <tt>PR_CALLBACK</tt> qualifier. NSPR functions are normally declared <tt>__cdecl</tt>. These declarations are hidden in the <tt>PR_EXTERN
()</tt> declarations in NSPR's header files. NSPR functions returning floating point types and structs by value, including the derived types PRInt64, are declared <tt>__PASCAL</tt>. These different declarations are to accommodate restrictions in Watcom's C/C++ version 11.0 and 11.0a compiler. Windows 3.1 does not provide a non-blocking file I/O interface. NSPR's file I/O is done using Windows 3.1's...
...And 5 more matches
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
ULL; CERTCertificate *issuerCert = NULL; CERTCertificate *cert = NULL; if ( !selfsign ) { issuerCert = CERT_FindCertByNicknameOrEmailAddr(handle, issuerNickName); if (!issuerCert) { PR_fprintf(PR_STDERR, "could not find certificate named %s\n", issuerNickName); goto cleanup; } } now = PR_Now
(); PR_ExplodeTime (now, PR_GMTParameters, &printableTime); if ( warpmonths ) { printableTime.tm_month += warpmonths; now = PR_ImplodeTime (&printableTime); PR_ExplodeTime (now, PR_GMTParameters, &printableTime); } printableTime.tm_month += validityMonths; after = PR_ImplodeTime (&printableTime); /* note that the time is now in micro-second un...
... trusts); if (rv) { PR_fprintf(PR_STDERR, "unable to decode trust string\n"); rv = SECFailure; goto cleanup; } rv = PK11_ImportCert(slot, cert, CK_INVALID_HANDLE, name, PR_FALSE); if (rv != SECSuccess) { /* sigh, PK11_Import Cert and CERT_ChangeCertTrust should have * been coded to take a password arg. ...
...FALSE); } if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "could not add certificate to token or database : %s\n", PORT_ErrorToString(rv)); rv = SECFailure; goto cleanup; } } rv = CERT_ChangeCertTrust(handle, cert, trust); if (rv != SECSuccess) { if (PORT_GetError
() == SEC_ERROR_TOKEN_NOT_LOGGED_IN) { rv = PK11_Authenticate(slot, PR_TRUE, pwdata); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "could not authenticate to token %s : %s\n", PK11_GetTokenName(slot), PORT_ErrorToString(rv)); rv = SECFailure; goto cleanup; } rv = CERT_...
...And 5 more matches
sample2
hs, int validityMonths) { PRExplodedTime printableTime; PRTime now; PRTime after; CERTValidity *validity = NULL; CERTCertificate *issuerCert = NULL; CERTCertificate *cert = NULL; if ( !selfsign ) { issuerCert = CERT_FindCertByNicknameOrEmailAddr(handle, issuerNickName); if (!issuerCert) { PR_fprintf(PR_STDERR, "could not find certificate named %s\n", issuerNickName); goto cleanup; } } now = PR_Now
(); PR_ExplodeTime (now, PR_GMTParameters, &printableTime); if ( warpmonths ) { printableTime.tm_month += warpmonths; now = PR_ImplodeTime (&printableTime); PR_ExplodeTime (now, PR_GMTParameters, &printableTime); } printableTime.tm_month += validityMonths; after = PR_ImplodeTime (&printableTime); /* note that the time is now in micro-second unit */ validity = CERT_CreateValidity (now, after); if (va...
...ust\n"); rv = SECFailure; goto cleanup; } rv = CERT_DecodeTrustString(trust, trusts); if (rv) { PR_fprintf(PR_STDERR, "unable to decode trust string\n"); rv = SECFailure; goto cleanup; } rv = PK11_ImportCert(slot, cert, CK_INVALID_HANDLE, name, PR_FALSE); if (rv != SECSuccess) { /* sigh, PK11_Import Cert and CERT_ChangeCertTrust should have * been coded to take a password arg. ...
...etTokenName(slot), PORT_ErrorToString(rv)); rv = SECFailure; goto cleanup; } rv = PK11_ImportCert(slot, cert, CK_INVALID_HANDLE, name, PR_FALSE); } if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "could not add certificate to token or database : %s\n", PORT_ErrorToString(rv)); rv = SECFailure; goto cleanup; } } rv = CERT_ChangeCertTrust(handle, cert, trust); if (rv != SECSuccess) { if (PORT_GetError
() == SEC_ERROR_TOKEN_NOT_LOGGED_IN) { rv = PK11_Authenticate(slot, PR_TRUE, pwdata); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "could not authenticate to token %s : %s\n", PK11_GetTokenName(slot), PORT_ErrorToString(rv)); rv = SECFailure; goto cleanup; } rv = CERT_ChangeCertTrust(handle, cert, trust); } if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "could not change trust on certificate : %s\n"...
...And 5 more matches
Feed content access API
ility class that unescapes HTML strings. Example: Reading a feed from the Web It's actually quite easy to read and parse a feed. Use an XMLHttpRequest to load the feed, then pass its string to an nsIFeedProcessor to parse the feed. ...
...rvice;1'] .getService(Components.interfaces.nsIIOService); var uri = ioService.newURI(feedUrl, null, null); if (data.length) { var parser = Components.classes["@mozilla.org/feed-processor;1"] .createInstance(Components.interfaces.nsIFeedProcessor); var listener = new FeedTestResultListener
(); try { parser.listener = listener; parser.parseFromString(data, uri); } catch(e) { alert("Error parsing feed."); } } } httpRequest = new XMLHttpRequest
(); httpRequest.open("GET", feedUrl, true); try { httpRequest.onload = infoReceived; httpRequest.send(null); } catch(e) { alert(e); ...
...equest = new XMLHttpRequest
(); httpRequest.open("GET", feedUrl, true); try { httpRequest.onload = infoReceived; httpRequest.send(null); } catch(e) { alert(e); } } The nsIFeedProcessor interface lets you parse the feed data from several possible sources; in this case, we're loading a document into a string, then parsing that string using its parseFromString
() method. However, you could also parse it from a file using parseFromStream
(), or directly from an URL using parseAsync
(). The actual processing of the parsed feed is done by a method called handleResult
() on the FeedTestResultListener object. That code looks like this: FeedTestResultListener.prototype = { handleResult: function(result) { var feed = result.doc; feed.Quer...
...And 5 more matches
Building the WebLock UI
code in the interface - represent this state and track it as the user manipulates the iWebLock interface. A boolean wLocked variable can do this: // initialize the wLocked variable as unlocked var wLocked = 0; Then the functions that get called from the interface and call through to the lock and unlock methods of the WebLock component must also adjust this variable accordingly: function wLock
() { // check to see if locking is on or off weblock.lock
(); wLocked = 1; } function wUnLock
() { // check to see if locking is on or off weblock.unlock
(); wLocked = 0; } An important preliminary of these functions is that the 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 ...
...= 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 currently loaded page or provide other UI (e.g., a textfield where you can enter an arbitrary URL) for specifying URLs. ...
...t. The URL that the AddSite method expects is a string, so we can pass a string directly in from the user interface, or we can do a check on the string and verify that it's a valid URL. In this tutorial, focusing as it is on the WebLock functionality (rather than the UI), we'll assume the strings we get from the UI itself are URLs we actually want to write to the white list: function addThisSite
() { var tf = document.getElementById("dialog.input"); // weblock is global and declared above weblock.AddSite(tf.value); } This JavaScript function can be called directly from the XUL widget, where the input string is retrieved as the value property of the textbox element. You also need to create the function that displays the WebLock window itself when the user clicks the weblock icon in ...
...And 5 more matches
NS ConvertASCIItoUTF16 external
es nsString_external Data Members No public members. ...
...st PRUnichar*, PRUint32) - source Parameters PRUnichar* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
... PRUint32 aLength BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 5 more matches
NS ConvertUTF16toUTF8 external
nsCString_external Data Members No public members. ...
... Adopt void Adopt(const char*, PRUint32) - source Parameters char* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...ameters char* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 5 more matches
NS ConvertUTF8toUTF16 external
sses nsString_external Data Members No public members. ...
...st PRUnichar*, PRUint32) - source Parameters PRUnichar* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
... PRUint32 aLength BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 5 more matches
NS LossyConvertUTF16toASCII external
_external Data Members No public members. ...
... Adopt void Adopt(const char*, PRUint32) - source Parameters char* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...ameters char* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 5 more matches
PromiseFlatCString (External)
tComparator Compare Equals operator< operator<= operator== operator>= operator> operator!= EqualsLiteral Find RFind FindChar RFindChar AppendInt ToInteger Base Classes nsCStringContainer Data Members No public members. ...
... Adopt void Adopt(const char*, PRUint32) - source Parameters char* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...ameters char* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 5 more matches
PromiseFlatString (External)
Equals operator< operator<= operator== operator>= operator> operator!= EqualsLiteral LowerCaseEqualsLiteral Find RFind FindChar RFindChar AppendInt ToInteger Base Classes nsStringContainer Data Members No public members. ...
...st PRUnichar*, PRUint32) - source Parameters PRUnichar* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
... PRUint32 aLength BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 5 more matches
nsAutoString (External)
Equals operator< operator<= operator== operator>= operator> operator!= EqualsLiteral LowerCaseEqualsLiteral Find RFind FindChar RFindChar AppendInt ToInteger Base Classes nsStringContainer Data Members No public members. ...
...st PRUnichar*, PRUint32) - source Parameters PRUnichar* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
... PRUint32 aLength BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 5 more matches
nsCAutoString (External)
tComparator Compare Equals operator< operator<= operator== operator>= operator> operator!= EqualsLiteral Find RFind FindChar RFindChar AppendInt ToInteger Base Classes nsCStringContainer Data Members No public members. ...
... Adopt void Adopt(const char*, PRUint32) - source Parameters char* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...ameters char* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 5 more matches
nsDependentCSubstring external
Equals operator< operator<= operator== operator>= operator> operator!= EqualsLiteral Find RFind FindChar RFindChar AppendInt ToInteger Base Classes nsCStringContainer Data Members No public members. ...
... Rebind void Rebind(const char*, PRUint32) - source Parameters char* aStart PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...meters char* aStart PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 5 more matches
nsDependentString
Parameters PRUnichar* data void Rebind(const PRUnichar*, PRUint32) - source Parameters PRUnichar* data PRUint32 length void Rebind(const PRUnichar*, const PRUnichar*) - source Parameters PRUnichar* st...
...Parameters PRUnichar* data void Rebind(const PRUnichar*, PRUint32) - source Parameters PRUnichar* data PRUint32 length void Rebind(const PRUnichar*, const PRUnichar*) - source Parameters PRUnichar* start PRUnichar* end operator= nsString& o...
... @param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...And 5 more matches
nsDependentSubstring external
Find(const nsAString&, PRUint32, PRInt32 (*) Find RFind(const nsAString&, PRInt32 (*) RFind(const nsAString&, PRInt32, PRInt32 (*) RFind FindChar RFindChar AppendInt ToInteger Base Classes nsStringContainer Data Members No public members. ...
...const PRUnichar*, PRUint32) - source Parameters PRUnichar aStart PRUint32 aLength BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
...art PRUint32 aLength BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 5 more matches
nsLiteralCString (External)
operator!= EqualsLiteral Find RFind FindChar RFindChar AppendInt ToInteger Base Classes nsCString_external Data Members No public members. ...
... Adopt void Adopt(const char*, PRUint32) - source Parameters char* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...ameters char* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 5 more matches
nsLiteralString (External)
operator!= EqualsLiteral Find RFind FindChar RFindChar AppendInt ToInteger Base Classes nsCString_external Data Members No public members. ...
... Adopt void Adopt(const char*, PRUint32) - source Parameters char* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...ameters char* aData PRUint32 aLength BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
...And 5 more matches
imgIEncoder
Last changed in Gecko 1.9 (Firefox 3) Method overview void addImageFrame( [array, size_is(length), const] in PRUint8 data, in unsigned long length, in PRUint32 width, in PRUint32 height, in PRUint32 stride, in PRUint32 frameFormat, in AString frameOptions); void encodeClipboardImage(in nsIClipboardImage aClipboardImage, out nsIFile aImageFile); Obsolete since Gecko 1.9 void endImageEncode
(); void initFromData([array, size_is(length), const] in PRUint8 data, in unsigned long length, in PRUint32 width, in PRUint32 height, in PRUint32 stride, in PRUint32 inputFormat, in AString outputOptions); void startImageEncode(in PRUint32 width, in PRUint32 height, in PRUint32 inputFormat, in AString outputOptions); Constants Possible values for input format (note that not all image form...
... it's internal representation) PRE-MULTIPLIED alpha is used (That is, 50% transparent red is 0x80800000, not 0x80ff0000) Possible values for outputOptions. Multiple values are semicolon-separated. PNG: ---- transparency=[yes|no|none] -- default: "yes" Overrides default from input format. "no" and "none" are equivalent. APNG: ----- The following options can be used with startImageEncode
(): transparency=[yes|no|none] -- default: "yes" Overrides default from input format. "no" and "none" are equivalent. skipfirstframe=[yes|no] -- default: "no" Controls display of the first frame in animations. PNG-only clients always display the first frame (and only that frame). frames=# -- default: "1" Total number of frames in the image. The first frame, even if skipped, is alw...
... frame in animations. PNG-only clients always display the first frame (and only that frame). frames=# -- default: "1" Total number of frames in the image. The first frame, even if skipped, is always included in the count. plays=# -- default: "0" Number of times to play the animation sequence. "0" will repeat forever. The following options can be used for each frame, with addImageFrame
(): transparency=[yes|no|none] -- default: "yes" Overrides default from input format. "no" and "none" are equivalent. delay=# -- default: "500" Number of milliseconds to display the frame, before moving to the next frame. dispose=[none|background|previous] -- default: "none" What to do with the image's canvas before rendering the next frame. See APNG spec. blend=[source|over] -- ...
...And 5 more matches
mozIStorageService
The database should not be open, or you should ensure that no database activity is happening when you call this method. The filename provided is only used as a suggestion. If the filename is already taken, attempts will be made to ensure that it is unique. The actual backup file is returned, and the resulting filename can be obtained from that. ns...
...rameters aDBFile The database file to back up. aBackupFileName The filename to give to the new backup file. aBackupParentDirectory Optional The directory to put the backup into. If this is not specified, the backup is placed in the same directory as the original file. Return value An nsIFile object representing the newly-created backup file. openDatabase
() Opens a database connection to the specified file. The specified file is created if it does not already exist. If this method throws NS_ERROR_FILE_CORRUPTED, it's recommended that you call mozIStorageService.backupDatabaseFile
() to back up the database so that user data is not lost (although we have no way of recovering this data yet). Consumers should check mozIStorageConnection.connectionReady ...
... Warning: If you have more than one connection to a file, you must use the exact same name for the file each time, including case. ...
...And 5 more matches
nsIClipboardCommands
webshell/public/nsIClipboardCommands.idlScriptable An interface for embedding clients who wish to interact with the system-wide OS clipboard. Mozilla does not use a private clipboard, instead it places its data directly onto the system clipboard. The webshell implements this interface. ...
...Commands.idlScriptable An interface for embedding clients who wish to interact with the system-wide OS clipboard. Mozilla does not use a private clipboard, instead it places its data directly onto the system clipboard. The webshell implements this interface. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview boolean canCopyImageContents
(); boolean canCopyImageLocation
(); boolean canCopyLinkLocation
(); boolean canCopySelection
(); boolean canCutSelection
(); boolean canPaste
(); void copyImageContents
(); void copyImageLocation
(); void copyLinkLocation
(); void copySelection
(); void cutSelection
(); void paste
(); void selectAll
(); void selectNone
(); Methods canCopyImageContents
() Returns whether we can copy an image's contents. boolean canCop...
...nCopyLinkLocation
(); boolean canCopySelection
(); boolean canCutSelection
(); boolean canPaste
(); void copyImageContents
(); void copyImageLocation
(); void copyLinkLocation
(); void copySelection
(); void cutSelection
(); void paste
(); void selectAll
(); void selectNone
(); Methods canCopyImageContents
() Returns whether we can copy an image's contents. boolean canCopyImageContents
(); Parameters None. Return value true if an image is selected, false otherwise. canCopyImageLocation
() Returns whether we can copy an image location. boolean canCopyImageLocation
(); Parameters None. Return value true if an image is selected, false otherwise. canCopyLinkLocation
() Returns whether we can copy a link location. boolean canCopyLinkLocation
(); Parameters None. Return value true if a l...
...And 5 more matches
nsIDownloadProgressListener
it/components/downloads/nsIDownloadProgressListener.idlScriptable This interface gives applications and extensions a way to monitor the status of downloads being processed by the Download Manager. Inherits from: nsISupports Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) To use simply implement this interface in your code, then call nsIDownloadManager.addListener
() to start listening. When you no longer need to listen to the Download Manager's state, call nsIDownloadManager.removeListener
() to stop listening. As the states of downloads change, the methods described here are called by the Download Manager so your code can take whatever steps it needs to. This interface works very similarly to the nsIWebProgress interface. It is important to note that ther...
...n nsIDownload aDownload); void onStatusChange(in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage, in nsIDownload aDownload); Obsolete since Gecko 1.9.1 Attributes Attribute Type Description document nsIDOMDocument document The document of the download manager frontend. Methods onDownloadStateChange
() Called when the status of a particular download changes. void onDownloadStateChange( in short aState, in nsIDownload aDownload ); Parameters aState The previous state of the download. See nsIDownloadManager.Constants for a list of possible values. aDownload The nsIDownload object representing the file whose download status has changed. You can get the new state of the download from ...
... download changes. void onDownloadStateChange( in short aState, in nsIDownload aDownload ); Parameters aState The previous state of the download. See nsIDownloadManager.Constants for a list of possible values. aDownload The nsIDownload object representing the file whose download status has changed. You can get the new state of the download from this object. onLocationChange
() Obsolete since Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) void onLocationChange( in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI aLocation, in nsIDownload aDownload ); Parameters aWebProgress The nsIWebProgress instance used by the Download Manager to monitor downloads. aRequest The nsIChannel that changed state. This parameter ...
...And 5 more matches
nsIEditorIMESupport
editor/idl/nsIEditorIMESupport.idlScriptable Please add a summary to this article. ...
... editor/idl/nsIEditorIMESupport.idlScriptable Please add a summary to this article. ...
...Obsolete since Gecko 2.0 void setCompositionString(in DOMString aCompositionString, in nsIPrivateTextRangeListPtr aTextRange, in nsTextEventReplyPtr aReply); Native code only! ...
...And 5 more matches
nsIExternalProtocolService
Specifically, this looks to see whether there are any known possible application handlers in either the nsIHandlerService datastore or registered with the OS. boolean externalProtocolHandlerExists( in string aProtocolScheme ); Parameters aProtocolScheme The scheme from a url: http, ftp, mailto, and so on. Note: aProtocolScheme should not...
... boolean externalProtocolHandlerExists( in string aProtocolScheme ); Parameters aProtocolScheme The scheme from a url: http, ftp, mailto, and so on. Note: aProtocolScheme should not include a trailing colon, which is part of the URI syntax, not part of the scheme itself. That is, pass "mailto" not "mailto:". Return value true if we have a handler and false otherwise. getApplicationDescription
() Gets a human-readable description for the application responsible for handling a specific protocol. AString getApplicationDescription( in AUTF8String aScheme ); Parameters aScheme The scheme to look up. For example, "mms". Return value This code makes little sense and needs to be cleaned up. -Nickolay <pre> // first construct an nsIURI object using the ioservice var ioservice = Components.cl...
...If neither the application nor the OS knows about a handler for the protocol, the object this method returns will represent a default handler for unknown content. Note: AProtocolScheme should not include a trailing colon, which is part of the URI syntax, not part of the scheme itself (That is pass "mailto" not "mailto:"). nsIHandlerInfo getProtocolHand...
...And 5 more matches
nsIFrameLoader
8 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Note: This interface works in tandem with the nsIContentView interface to manage frames across processes if Electrolysis is in use to support per-frame processes. ...
... nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Note: This interface works in tandem with the nsIContentView interface to manage frames across processes if Electrolysis is in use to support per-frame processes. ...
...n Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Note: This interface works in tandem with the nsIContentView interface to manage frames across processes if Electrolysis is in use to support per-frame processes. ...
...And 5 more matches
nsIFrameScriptLoader
ral/source/dom/base/nsIMessageManager.idl Inherits from: nsISupports This interface is used to load frame scripts. ...
...sageManager.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. ...
...And 5 more matches
nsIInputStream
xpcom/io/nsIInputStream.idlScriptable This interface represents a readable stream of data. Inherits from: nsISupports Last changed in Gecko 17.0 (Firefox 17.0 / Thunderbird 17.0 / SeaMonkey 2.14) An input stream may be "blocking" or "non-blocking" (see the isNonBlocking
() method). A blocking input stream may suspend the calling thread in order to satisfy a call to close
(), available
(), read
(), or readSegments
(). A non-blocking input stream, on the other hand, must not block the calling thread of execution. Note: Blocking input streams are often read on a background thread to avoid locking up the main application thread. For this reason, it is generally the case that a blocking input stream should be implemented using thread-safe AddRef and Release. Method overview ...
...ts
(). A non-blocking input stream, on the other hand, must not block the calling thread of execution. Note: Blocking input streams are often read on a background thread to avoid locking up the main application thread. For this reason, it is generally the case that a blocking input stream should be implemented using thread-safe AddRef and Release. ...
... the calling thread of execution. Note: Blocking input streams are often read on a background thread to avoid locking up the main application thread. For this reason, it is generally the case that a blocking input stream should be implemented using thread-safe AddRef and Release. Method overview unsigned long available
();Deprecated since Gecko 17.0 unsigned long long available
(); void close
(); boolean isNonBlocking
(); unsigned long read(in charPtr aBuf, in unsigned long aCount); Native code only! unsigned long readSegments(in nsWriteSegmentFun aWriter, in voidPtr aClosure, in unsigned long aCount); Native code only! Methods available
() Determine number of bytes available in the stream. In addition to the number of bytes avail...
...And 5 more matches
nsILocaleService
Introduced Gecko 1.6 Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) Implemented by: @mozilla.org/intl/nslocaleservice;1. ...
... nsISupports Last changed in Gecko 1.9 (Firefox 3) Implemented by: @mozilla.org/intl/nslocaleservice;1. To use this service, use: var localeService = Components.classes["@mozilla.org/intl/nslocaleservice;1"] .getService(Components.interfaces.nsILocaleService); Method overview nsILocale getApplicationLocale
(); AString getLocaleComponentForUserAgent
(); nsILocale getLocaleFromAcceptLanguage(in string acceptLanguage); nsILocale getSystemLocale
(); nsILocale newLocale(in AString aLocale); nsILocale newLocaleObject(in nsILocaleDefinition localeDefinition); Obsolete since Gecko 1.9 Methods getApplicationLocale
() Gets the user preference for locale from the operating system. Note: This has nothing to do with ...
... nsILocale newLocaleObject(in nsILocaleDefinition localeDefinition); Obsolete since Gecko 1.9 Methods getApplicationLocale
() Gets the user preference for locale from the operating system. Note: This has nothing to do with the locale used for localization of the application (UI text strings and so on.). This method returns something similar to getSystemLocale. nsILocale getApplicationLocale
(); Parameters None. Return value The user's OS setting for preferred locale. getLocaleComponentForUserAgent
() Gets the user preference for locale from the operating system. Note: This has nothing to do with any HTTP User-Agent. This method returns the same as getSystemLocale.getCategory("NSILOCALE_MESSAGES"). AString getLocaleComponentForUserAgent
(); Parameters None. Return value The user's OS se...
...And 5 more matches
nsIMsgThread
flags unsigned long Flags attached to the thread. subject ACString Subject of the thread newestMsgDate unsigned long numChildren unsi...
...y designating this thread. flags unsigned long Flags attached to the thread. subject ACString Subject of the thread newestMsgDate unsigned long numChildren unsigned long Readonly: Number of messages in the thread. numUnreadChildren unsigned long Readonly: Number of unread messages in the thread. Methods addChild
() Add a message to the thread. void addChild(in nsIMsgDBHdr child, in nsIMsgDBHdr inReplyTo, in boolean threadInThread, in nsIDBChangeAnnouncer announcer); Parameters child The message to add inReplyTo The message this should be in reply to threadInThread announcer An nsIDBChangeAnnouncer to receive notification when the change is made. ...
...age to the thread. void addChild(in nsIMsgDBHdr child, in nsIMsgDBHdr inReplyTo, in boolean threadInThread, in nsIDBChangeAnnouncer announcer); Parameters child The message to add inReplyTo The message this should be in reply to threadInThread announcer An nsIDBChangeAnnouncer to receive notification when the change is made. ...
...And 5 more matches
nsINavHistoryResultViewObserver
ement. Inherits from: nsISupports Last changed in Gecko 1.9.0 Method overview boolean canDrop(in long index, in long orientation); void onDrop(in long row, in long orientation); void onToggleOpenState(in long index); void onCycleHeader(in nsITreeColumn column); void onCycleCell(in long row, in nsITreeColumn column); void onSelectionChanged
(); void onPerformAction(in wstring action); void onPerformActionOnRow(in wstring action, in long row); void onPerformActionOnCell(in wstring action, in long row, in nsITreeColumn column); Constants Constant Value Description DROP_BEFORE -1 The drag operation wishes to insert the dragged item before the indicated row. DROP_ON ...
...umn); Constants Constant Value Description DROP_BEFORE -1 The drag operation wishes to insert the dragged item before the indicated row. DROP_ON 0 The drag operation wishes to drop the dragged item onto the indicated row. DROP_AFTER 1 The drag operation wishes to insert the dragged item after the indicated row. Methods canDrop
() Implement this method to report whether or not a drop is permitted onto the specified location. To provide behavior similar to the folder pane in Thunderbird, where drops are only permitted on items themselves instead of on the pane as a whole, always return false when the orientation isn't DROP_ON. Warning: Do not change the content of the observer list. boolean canDrop( in long index, ...
...en the orientation isn't DROP_ON. Warning: Do not change the content of the observer list. boolean canDrop( in long index, in long orientation ); Parameters index The item over which the drag is currently located. orientation Whether the drag target is before, after, or on the indicated row. Return value Return true if the drop is permitted or false if it isn't. onDrop
() Called when the user drops something onto the view being observed. void onDrop( in long row, in long orientation ); Parameters row The row at which the drop occurred. orientation DROP_BEFORE, DROP_ON, or DROP_AFTER, indicating whether the drop destination is before, on, or after the target row. onToggleOpenState
() Called when an item is opened or closed. void onToggleO...
...And 5 more matches
nsIProtocolProxyService
flag may result in locking up the calling thread for a lengthy period of time. By passing this flag to resolve, one can failover to asyncResolve to avoid locking up the calling thread if a PAC query is required. When this flag is passed to resolve, resolve may throw the exception NS_BASE_STREAM_WOULD_BLOCK to indicate that it failed due to this flag being present. ...
...lag being present. Methods resolve
() Deprecated since Gecko 18 This method has been removed in Firefox 18. Use resolveAsync instead Previous doc This method returns a nsIProxyInfo instance that identifies a proxy to be used for loading the given URI. Otherwise, this method returns null indicating that a direct connection should be used. If this proxy is unavailable, getFailoverForProxy
() may be called to determine the correct secondary proxy to be used. If the protocol handler for the given URI supports nsIProxiedProtocolHandler, then the nsIProxyInfo instance returned from resolve may be passed to the nsIProxiedProtocolHandler.newProxiedChannel
() method to create a nsIChannel to the given URI that uses the specified proxy. However, if the nsIProxyInfo type is "http", then it...
...ct connection. Note: If PAC is configured, and the PAC file has not yet been loaded, then this method will return a nsIProxyInfo instance with a type of "unknown" to indicate to the consumer that asyncResolve should be used to wait for the PAC file to finish loading. Otherwise, the consumer may choose to treat the result as type "direct" if desired. See nsIProxiedProtocolHandler.newProxiedChannel
(). asyncResolve
() This method is an asychronous version of the resolve method. Unlike resolve, this method is guaranteed not to block the calling thread waiting for DNS queries to complete. This method is intended as a substitute for resolve when the result is not needed immediately. nsICancelable asyncResolve( in nsIURI aURI, in unsigned long aFlags, in nsIProtocolProxyCallback aCall...
...And 5 more matches
nsIPushService
void subscribe( in DOMString scope, in nsIPrincipal principal, in nsIPushSubscriptionCallback callback ); Parameters scope The ServiceWorkerRegistration.scope for a service worker subscription, or a unique URL (for example, chrome://my-module/push) for a system subscription. principal The nsIPrincipal to associate with the subscription. Privileged code...
... void getSubscription( in DOMS...
...chrome://my-module/push", scriptSecurityManager.getSystemPrincipal
(), (code, subscription) => { if (!Components.isSuccessCode(code)) { Cu.reportError("Error creating subscription: " + code); return; } // `subscription` implements `nsIPushSubscription`. subscription.endpoint; subscription.getKey("p256dh"); subscription.getKey("auth"); } ); getSubscription
() Fetches an existing subscription. void getSubscription( in DOMString scope, in nsIPrincipal principal, in nsIPushSubscriptionCallback callback ); Parameters scope The unique scope URL, as passed to nsIPushService.subscribe
(). principal The subscription nsIPrincipal, as passed to nsIPushService.subscribe
(). callback The callback to call with the fetched nsIPushSubscription. Exa...
...And 5 more matches
nsIPushSubscription
routes the message to the instance of Firefox that created the subscription. A subscription also has a public key and secret; these are used to encrypt message payloads. This interface resembles PushSubscription from the Push API. Method overview void getKey(in DOMString name, [optional] out uint32_t keyLen, [array, size_is(keyLen), retval] out uint8_t key); bool quotaApplies
(); bool isExpired
(); Attributes Attribute Type Description endpoint DOMString The subscription URL. pushCount long long The total number of messages sent to this subscription. lastPush long long The last time a message was sent to this subscription, in milliseconds since the epoch. quota long The number of r...
... endpoint DOMString The subscription URL. pushCount long long The total number of messages sent to this subscription. lastPush long long The last time a message was sent to this subscription, in milliseconds since the epoch. quota long The number of remaining background messages for this subscription, or -1 if exempt. Methods getKey
() Returns a byte array containing the key material for this subscription. The remote server can use these keys to encrypt and authenticate message payloads. The following key names are supported: p256dh The ECDH public key, used as the input keying material in the HKDF invocation during encryption. auth The shared authentication secret, used as the salt in the HKDF invocat...
...used as the salt in the HKDF invocation. void getKey( in DOMString name, [optional] out uint32_t keyLen, [array, size_is(keyLen), retval] out uint8_t key ); Parameters name The encryption key name. keyLen The keying material length. key The byte array containing the keying material. keyLen and key are out parameters. ...
...And 5 more matches
nsISocketTransport
rk. Inherits from: nsITransport Last changed in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) Note: Connection setup is triggered by opening an input or output stream, it does not start on its own. Completion of the connection setup is indicated by a STATUS_CONNECTED_TO notification to the event sink (if set). ...
...o 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) Note: Connection setup is triggered by opening an input or output stream, it does not start on its own. Completion of the connection setup is indicated by a STATUS_CONNECTED_TO notification to the event sink (if set). ...
...ote: Connection setup is triggered by opening an input or output stream, it does not start on its own. Completion of the connection setup is indicated by a STATUS_CONNECTED_TO notification to the event sink (if set). ...
...And 5 more matches
nsIStructuredCloneContainer
dom/interfaces/base/nsIStructuredCloneContainer.idlScriptable This interface acts as a container for an object serialized using the structured clone algorithm. ...
.../base/nsIStructuredCloneContainer.idlScriptable This interface acts as a container for an object serialized using the structured clone algorithm. 1.0 66 Introduced Gecko 6.0 Inherits from: nsISupports Last changed in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) You can copy an object into an nsIStructuredCloneContainer using initFromVariant
() or initFromBase64
(). ...
... Inherits from: nsISupports Last changed in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) You can copy an object into an nsIStructuredCloneContainer using initFromVariant
() or initFromBase64
(). it is an error to initialize an nsIStructuredCloneContainer more than once. Once you've initialized the container, you can get a copy of the object it stores by calling deserializeToVariant
(). You can also get a base-64-encoded string containing a copy of the container's serialized data, using getDataAsBase64
(). ...
...And 5 more matches
nsITelemetry
nterfaces.nsITelemetry); Method overview jsval getHistogramById(in ACString id); jsval snapshotHistograms(in uint32_t aDataset, in boolean aSubsession, in boolean aClear); jsval getKeyedHistogramById(in ACString id); void captureStack(in ACString name); jsval snapshotCapturedStacks([optional] in boolean clear); nsISupports getLoadedModules
(); jsval snapshotKeyedHistograms(in uint32_t aDataset, in boolean aSubsession, in boolean aClear); void setHistogramRecordingEnabled(in ACString id, in boolean enabled); void asyncFetchTelemetryData(in nsIFetchTelemetryDataCallback aCallback); double msSinceProcessStart
(); void scalarAdd(in ACString aName, in jsval aValue); void scalarSet(in A...
...ptional] in boolean aClear); void keyedScalarAdd(in ACString aName, in AString aKey, in jsval aValue); void keyedScalarSet(in ACString aName, in AString aKey, in jsval aValue); void keyedScalarSetMaximum(in ACString aName, in AString aKey, in jsval aValue); jsval snapshotKeyedScalars(in uint32_t aDataset, [optional] in boolean aClear); void clearScalars
(); test only void flushBatchedChildTelemetry
(); void recordEvent(in ACString aCategory, in ACString aMethod, in ACString aObject, [optional] in jsval aValue, [optional] in jsval extra); void setEventRecordingEnabled(in ACString aCategory, in boolean aEnabled); jsval snapshotEvents(in uint32_t aDataset, [optional] in boolean aClear); void registerEvents(i...
...This is true if the FHR data reporting service or the self-support service is enabled. canRecordExtended boolean A flag indicating if Telemetry is allowed to record extended data. Returns false if the user ha...
...And 5 more matches
nsIAbCard/Thunderbird3
isMailList boolean If isMailList is true then mailListURI will contain the URI of the associated mail list. This will be removed from the interface at a later date. mailListURI string If isMailList is true then mailListURI will contain the URI of the associated mail list. This will be removed from the interface at a later date. Methods getProperty
() Returns a property for the given name. nsIVariant getProperty(in AUTF8String name, in nsIVariant defaultValue); Parameters name The case-sensitive name of the property to get. defaultValue The value to return if the property does not exist. Return value The value of the attribute asked for. Exceptions Thrown NS_ERROR_NOT_AVAILABLE<tt> If the named property does not exist. <...
...e); Parameters name The case-sensitive name of the property to get. defaultValue The value to return if the property does not exist. Return value The value of the attribute asked for. Exceptions Thrown NS_ERROR_NOT_AVAILABLE<tt> If the named property does not exist. <tt>NS_ERROR_CANNOT_CONVERT_DATA If the property cannot be converted to the desired type. getPropertyAsAString
() getPropertyAsAUTF8String
() getPropertyAsUint32
() getPropertyAsBool
() [noscript] AString getPropertyAsAString(in string name); [noscript] AUTF8String getPropertyAsAUTF8String(in string name); [noscript] PRUint32 getPropertyAsUint32(in string name); [noscript] boolean getPropertyAsBool(in string name); Returns a property for the given name. These functions convert values in the same manne...
...OT_AVAILABLE<tt> If the named property does not exist. <tt>NS_ERROR_CANNOT_CONVERT_DATA If the property cannot be converted to the desired type. [noscript] AString getPropertyAsAString(in string name); [noscript] AUTF8String getPropertyAsAUTF8String(in string name); [noscript] PRUint32 getPropertyAsUint32(in string name); [noscript] boolean getPropertyAsBool(in string name); setProperty
() setPropertyAsAString
() setPropertyAsAUTF8String
() setPropertyAsUint32
() setPropertyAsBool
() Assigns the given to value to the property of the given name. Should the property exist, its value will be overwritten. An implementation may impose additional semantic constraints for certain properties. However, such constraints might not be checked by this method. These functions convert values in...
...And 5 more matches
XPCOM Thread Synchronization
XPCOM thread synchronization primitives have the same semantics as those in NSPR, and each method of these synchronization objects (e.g. Mutex::Lock
()) has a matching function in NSPR (PR_Lock
()). This is no accident, as mozilla:: primitives are merely bare-minimum wrappers around NSPR's. This article covers the API of Mozilla synchronization only. For a higher-level introduction to thread synchronization, see Introduction_to_NSPR. Quick reference: Difference between nsAutoLock API and new API Old construction Note: This is deprecated code that is shown only to compare with approved code. ...
...und NSPR's. This article covers the API of Mozilla synchronization only. For a higher-level introduction to thread synchronization, see Introduction_to_NSPR. Quick reference: Difference between nsAutoLock API and new API Old construction Note: This is deprecated code that is shown only to compare with approved code. ...
... covers the API of Mozilla synchronization only. For a higher-level introduction to thread synchronization, see Introduction_to_NSPR. Quick reference: Difference between nsAutoLock API and new API Old construction Note: This is deprecated code that is shown only to compare with approved code. ...
...And 5 more matches
Using popup notifications
le is imported by the browser, so you don't need to do it explicitly yourself. Then you can create the popup notification at the appropriate time like this: PopupNotifications.show(gBrowser.selectedBrowser, "sample-popup", "This is a sample popup notification.", null, /* anchor ID */ { label: "Do Something", accessKey: "D", callback: function
() { alert("Doing something awesome!"); } }, null /* secondary action */ ); In this case, we aren't providing any secondary actions; that is, actions provided to the user through the drop-down menu. This notification looks like this: That's not very pretty; where's the icon? Adding an icon to your notification Adding an icon to a notification is...
... notification object's icon element. ...
...ant: Adding secondary options To provide options in the drop-down menu, add an array of notification actions to the call to the show
() method, like this: PopupNotifications.show(gBrowser.selectedBrowser, "sample-popup", "This is a sample popup notification.", null, /* anchor ID */ { label: "Do Something", accessKey: "D", callback: function
() { alert("Doing something awesome!"); } }, [ { label: "First secondary option", accessKey: "1", callback: function
() { alert("First secondary option selected."); } }, { label: "Second secondary option", accessKey: "2", callback: funct...
...And 5 more matches
Working with ArrayBuffers
/ buffer is a ArrayBuffer // incomingBuffer is a TypedArray var imageData2 = context.createImageData(w, h); imageData2.data.set(incomingBuffer); Further, if you have a byte array pixelBuffer, and you need to create ImageData from it. The data property holds an array of bytes. We start with the following: // pixelBuffer is a pointer to a RGBA pixel buffer of 400x400 image. pixelBuffer.toString
(); // "ctypes.uint8_t.ptr(ctypes.UInt64("0x352e0000"))" var imgWidth = 400; var imgHeight = 400; var myImgDat = new ImageData(imgWidth, imgHeight); Method 1: Passing ArrayType CData to Uint8ClampedArray.prototype.set One method is to get into a js-ctypes array, and then set it into the ImageData, as illustrated by the following code example. // Cast pointer to array, to pass to Uint8ClampedArr...
...gWidth = 400; var imgHeight = 400; var myImgDat = new ImageData(imgWidth, imgHeight); Method 1: Passing ArrayType CData to Uint8ClampedArray.prototype.set One method is to get into a js-ctypes array, and then set it into the ImageData, as illustrated by the following code example. // Cast pointer to array, to pass to Uint8ClampedArray.prototype.set. var casted = ctypes.cast(pixelBuffer.address
(), ctypes.uint8_t.array(myImgData.data.length).ptr).contents; // myImgDat.data.length is imgWidth * imgHeight * 4 because per pixel there is r, g, b, a numbers casted.toString
(); // "ctypes.uint8_t.array(640000)([45, 66, 135, 255, 99, 86, 55, 255, .......... ])" myImgDat.data.set(casted); The ctypes.cast takes a couple of milliseconds, however, the myImgDat.data.set takes up to 800ms for a size o...
....data.set(casted); The ctypes.cast takes a couple of milliseconds, however, the myImgDat.data.set takes up to 800ms for a size of 52,428,800 (which is image size of 1280 x 1024 pixels). So, for the size of 640,000 it takes about 98ms. ...
...And 5 more matches
Web Console Helpers - Firefox Developer Tools
The commands The JavaScript command line provided by the Web Console offers a few built-in helper functions that make certain tasks easier. $(selector, element) Looks up a CSS selector string selector , returning the first node descended from element that matches. If unspecified, element defaults to document. Equivalent to document.querySelector
() or calls the $ function in the page, if it exists. See the QuerySelector code snippet. $$(selector, element) Looks up a CSS selector string selector, returning an array of DOM nodes descended from element that match. If unspecified, element defaults to document. This is like for document.querySelectorAll
(), but returns an array instead of a NodeList. $0 The currently-inspected element in the page. $_ Stores the result of the last ...
...lt to return; it can be an XPathResult constant, or a corresponding string: "number", "string", "bool", "node", or "nodes"; if not provided, ANY_TYPE is used. :block (Starting in Firefox 80) Followed by an unquoted string, blocks requests where the URL contains that string. In the Network Monitor, the string now appears and is selected in the Request Blocking sidebar. Unblock with :unblock. ...
...If the argument is a string, it's copied as-is. If the argument is a DOM node, its outerHTML is copied. ...
...And 5 more matches
AbstractRange - Web APIs
terface. Contents of elements When trying to access the contents of an element, keep in mind that the element itself is a node, but so is any text inside it. In order to set a range endpoint within the text of an element, be sure to find the text node inside the element: let startElem = document.querySelector("p"); let endElem = startElem.querySelector("span"); let range = document.createRange
(); range.setStart(startElem, 0); range.setEnd(endElem, endElem.childNodes[0].length/2); let contents = range.cloneContents
(); document.body.appendChild(contents); This example creates a new range, rng, and sets its starting point to the third child node of the first element whose class is elementclass. The end point is set to be the middle of the first child of the span, and then the range is u...
...n onscreen. Each element's contents are linked below it in the tree, potentially spawning a series of branches below as elements include other elements and text nodes. If you want to create a range that incorporates the contents of the <p> element whose contents are "A <em>very</em> interesting thing happened on the way to the forum...", you can do so like this: let pRange = document.createRange
(); pRange.selectNodeContents(document.querySelector("#entry1 p")); Since we wish to select the entire contents of the <p> element, including its descendants, this works perfectly. If we wish to instead copy the text "An interesting thing..." from the <section>'s heading (an <h2> element) through the end of the letters "ve" in the <em> within the paragraph below it, the following code would work:...
...cument.querySelector("#entry1 p")); Since we wish to select the entire contents of the <p> element, including its descendants, this works perfectly. If we wish to instead copy the text "An interesting thing..." from the <section>'s heading (an <h2> element) through the end of the letters "ve" in the <em> within the paragraph below it, the following code would work: let r = document.createRange
(); let startNode = document.querySelector("section h2").childNodes[0]; r.setStart(startNode, 11); let endNode = document.querySelector("#entry1 p em").childNodes[0]; r.setEnd(endNode, 2); let fragment = r.cloneContents
(); Here an interesting problem arises--we are capturing content from multiple nodes located at different levels of the DOM hierarchy, and then only part of one of them. What shou...
...And 5 more matches
Animation - Web APIs
Properties Animation.currentTime The current time value of the animation in milliseconds, whether running or paused. If the animation lacks a timeline, is inactive or hasn't been played yet, its value is null. Animation.effect Gets and sets the AnimationEffectReadOnly associated with this animation. This will usually be a KeyframeEffect object. ...
...y Returns an enumerated value describing the playback state of an animation. Animation.playbackRate Gets or sets the playback rate of the animation. Animation.ready Read only Returns the current ready Promise for this animation. animation.replaceState Returns the replace state of the animation. This will be active if the animation has been replaced, or persisted if Animation.persist
() has been invoked on it. Animation.startTime Gets or sets the scheduled time when an animation's playback should begin. Animation.timeline Gets or sets the timeline associated with this animation. Event handlers Animation.oncancel Gets and sets the event handler for the cancel event. Animation.onfinish Gets and sets the event handler for the finish event. animation.onremove All...
...s or sets the timeline associated with this animation. Event handlers Animation.oncancel Gets and sets the event handler for the cancel event. Animation.onfinish Gets and sets the event handler for the finish event. animation.onremove Allows you to set and run an event handler that fires when the animation is removed (i.e., put into an active replace state). ...
...And 5 more matches
AudioListener - Web APIs
values are linearly independent of each other. The default is 1. AudioListener.upZ Represents the longitudinal (back and forth) position of the top of the listener's head in the same cartesian coordinate sytem as the position (positionX, positionY, and positionZ) values. The forward and up values are linearly independent of each other. The default is 0. Methods AudioListener.setOrientation
() Sets the orientation of the listener. AudioListener.setPosition
() Sets the position of the listener. Note: Although these methods are deprecated they are currently the only way to set the orientation and position in Firefox, Internet Explorer and Safari. Deprecated features AudioListener.dopplerFactor A double value representing the amount of pitch shift to use when rendering a ...
...fox, Internet Explorer and Safari. Deprecated features AudioListener.dopplerFactor A double value representing the amount of pitch shift to use when rendering a doppler effect. AudioListener.speedOfSound Is a double value representing the speed of sound, in meters per second. In a previous version of the specification, the dopplerFactor and speedOfSound properties and the setPosition
() method could be used to control the doppler effect applied to AudioBufferSourceNodes connected downstream -- these would be pitched up and down according to the relative speed of the PannerNode and the AudioListener. These features had a number of problems: Only AudioBufferSourceNodes were pitched up or down, not other source nodes. The behavior to adopt when an AudioBufferSourceNode was conn...
...pitched up or down, not other source nodes. The behavior to adopt when an AudioBufferSourceNode was connected to multiple PannerNodes was unclear. Because the velocity of the panner and the listener were not AudioParams, the pitch modification could not be smoothly applied, resulting in audio glitches. Because of these issues, these properties and methods have been removed. The setOrientation
() and setPosition
() methods have been replaced by setting their property value equivilents. For example setPosition(x, y, z) can be achieved by setting positionX.value, positionY.value, and positionZ.value respectively. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generall...
...And 5 more matches
BiquadFilterNode - Web APIs
The BiquadFilterNode interface represents a simple low-order filter, and is created using the AudioContext.createBiquadFilter
() method. It is an AudioNode that can represent different kinds of filters, tone control devices, and graphic equalizers. A BiquadFilterNode always has exactly one input and one output. Number of inputs 1 Number of outputs 1 Channel count mode "max" Channel count 2 (not used in the default count mode) Channel interpretation "speakers" Constructor BiquadFilterNode
() Creates a new instance of a BiquadFilterNode object. Properties Inherits properties from its parent, AudioNode. Note: Though the AudioParam objects returned are read-only, the values they represent are not. BiquadFilterNode.f...
...ous frequencies. The frequency with the maximal group delay, that is, the frequency where the center of the phase transition occurs. Controls how sharp the transition is at the medium frequency. The larger this parameter is, the sharper and larger the transition will be. Not used Methods Inherits methods from its parent, AudioNode. BiquadFilterNode.getFrequencyResponse
() From the current filter parameter settings this method calculates the frequency response for frequencies specified in the provided array of frequencies. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). var audioCtx = new (window.AudioContext...
...meter settings this method calculates the frequency response for frequencies specified in the provided array of frequencies. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
...And 5 more matches
Basic usage of canvas - Web APIs
ch are used to create and manipulate the content shown. In this tutorial, we focus on the 2D rendering context. Other contexts may provide different types of rendering; for example, WebGL uses a 3D context based on OpenGL ES. The canvas is initially blank. To display something, a script first needs to access the rendering context and draw on it. The <canvas> element has a method called getContext
(), used to obtain the rendering context and its drawing functions. getContext
() takes one parameter, the type of context. For 2D graphics, such as those covered by this tutorial, you specify "2d" to get a CanvasRenderingContext2D. var canvas = document.getElementById('tutorial'); var ctx = canvas.getContext('2d'); The first line in the script retrieves the node in the DOM representing the <canva...
...awing functions. getContext
() takes one parameter, the type of context. For 2D graphics, such as those covered by this tutorial, you specify "2d" to get a CanvasRenderingContext2D. var canvas = document.getElementById('tutorial'); var ctx = canvas.getContext('2d'); The first line in the script retrieves the node in the DOM representing the <canvas> element by calling the document.getElementById
() method. Once you have the element node, you can access the drawing context using its getContext
() method. Checking for support The fallback content is displayed in browsers which do not support <canvas>. Scripts can also check for support programmatically by simply testing for the presence of the getContext
() method. Our code snippet from above becomes something like this: var canvas = docume...
...nsupported code here } A skeleton template Here is a minimalistic template, which we'll be using as a starting point for later examples. Note: it is not good practice to embed a script inside HTML. We do it here to keep the example concise. ...
...And 5 more matches
Compositing and clipping - Web APIs
omposite shapes are built. We can, however, change this behaviour by setting the globalCompositeOperation property. In addition, the clip property allows us to hide unwanted parts of shapes. globalCompositeOperation We can not only draw new shapes behind existing shapes but we can also use it to mask off certain areas, clear sections from the canvas (not limited to rectangles like the clearRect
() method does) and more. globalCompositeOperation = type This sets the type of compositing operation to apply when drawing new shapes, where type is a string identifying which of the twelve compositing operations to use. See compositing examples for the code of the following examples. Clipping paths A clipping path is like a normal canvas shape but it acts as a mask to hide unwanted parts...
...ing modes that achieve more or less the same effect in source-in and source-atop. The most important differences between the two are that clipping paths are never actually drawn to the canvas and the clipping path is never affected by adding new shapes. This makes clipping paths ideal for drawing multiple shapes in a restricted area. In the chapter about drawing shapes I only mentioned the stroke
() and fill
() methods, but there's a third method we can use with paths, called clip
(). clip
() Turns the path currently being built into the current clipping path. You use clip
() instead of closePath
() to close a path and turn it into a clipping path instead of stroking or filling the path. By default the <canvas> element has a clipping path that's the exact same size as the canvas itself. In...
... of closePath
() to close a path and turn it into a clipping path instead of stroking or filling the path. By default the <canvas> element has a clipping path that's the exact same size as the canvas itself. In other words, no clipping occurs. A clip example In this example, we'll use a circular clipping path to restrict the drawing of a set of random stars to a particular region. ...
...And 5 more matches
Hit regions and accessibility - Web APIs
g. It's also very useful for assistive technology users (like screen readers) which can read and interpret the sub DOM in it. A good example at html5accessibility.com demonstrates how this can be done: <canvas> <h2>Shapes</h2> <p>A rectangle with a black border. In the background is a pink circle. ...
... for assistive technology users (like screen readers) which can read and interpret the sub DOM in it. A good example at html5accessibility.com demonstrates how this can be done: <canvas> <h2>Shapes</h2> <p>A rectangle with a black border. In the background is a pink circle. Partially overlaying the <a href="http://en.wikipedia.org/wiki/Circle" onfocus="drawCircle
();" onblur="drawPicture
();">circle</a>. ...
...ibility.com demonstrates how this can be done: <canvas> <h2>Shapes</h2> <p>A rectangle with a black border. In the background is a pink circle. Partially overlaying the <a href="http://en.wikipedia.org/wiki/Circle" onfocus="drawCircle
();" onblur="drawPicture
();">circle</a>. Partially overlaying the circle is a green <a href="http://en.wikipedia.org/wiki/Square" onfocus="drawSquare
();" onblur="drawPicture
();">square</a> and a purple <a href="http://en.wikipedia.org/wiki/Triangle" onfocus="drawTriangle
();" onblur="drawPicture
();">triangle</a>, both of which are semi-opaque, so the full circle can be seen underneath.</p> </canvas> See the video how NVDA reads this example by Steve Faulkner. ARIA rules Accessible Rich Internet Applications (ARIA) defines ways to make W...
...And 5 more matches
ConstantSourceNode - Web APIs
by automating the value of its offset or by connecting another node to it; see Controlling multiple parameters with ConstantSourceNode. A ConstantSourceNode has no inputs and exactly one monaural (one-channel) output. The output's value is always the same as the value of the offset parameter. Number of inputs 0 Number of outputs 1 Constructor ConstantSourceNode
() Creates and returns a new ConstantSourceNode instance, optionally specifying an object which establishes initial values for the object's properties. You can also create a ConstantSourceNode whose properties are initialized to their default values by calling AudioContext.createConstantSource
(). Properties Inherits properties from its parent interface, AudioScheduledSourceNode, and adds the fol...
...ioScheduledSourceNode. Some browsers' implementations of this event handler are part of the AudioScheduledSourceNode interface. onended Fired whenever the ConstantSourceNode data has stopped playing. Methods Inherits methods from its parent interface, AudioScheduledSourceNode. Some browsers' implementations of these methods are part of the AudioScheduledSourceNode interface. ...
...f this event handler are part of the AudioScheduledSourceNode interface. onended Fired whenever the ConstantSourceNode data has stopped playing. Methods Inherits methods from its parent interface, AudioScheduledSourceNode. Some browsers' implementations of these methods are part of the AudioScheduledSourceNode interface. start
() Schedules a sound to playback at an exact time. stop
() Schedules a sound to stop playback at an exact time. ...
...And 5 more matches
CustomEvent - Web APIs
Setting its value to true before returning from an event handler prevents propagation of the event. ...
...Setting its value to true before returning from an event handler prevents propagation of the event. Event.cancelable Read only A boolean indicating whether the event is cancelable. Event.composed Read only A boolean indicating whether or not the event can bubble across the boundary between the shadow DOM and the regular DOM. ...
...currentTarget Read only A reference to the currently registered target for the event. This is the object to which the event is currently slated to be sent. It's possible this has been changed along the way through retargeting. Event.deepPath An Array of DOM Nodes through which the event has bubbled. Event.defaultPrevented Read only Indicates whether or not the call to event.preventDefault
() canceled the event. Event.eventPhase Read only Indicates which phase of the event flow is being processed. Event.explicitOriginalTarget Read only The explicit original target of the event (Mozilla-specific.) Event.originalTarget Read only The original target of the event, before any retargetings. (Mozilla-specific.) Event.returnValue A historical property introduced by Internet Exp...
...And 5 more matches
DataTransfer - Web APIs
The DataTransfer object is used to hold the data that is being dragged during a drag and drop operation. It may hold one or more data items, each of one or more data types. For more information about drag and drop, see HTML Drag and Drop API. This object is available from the dataTransfer property of all drag events. Constructor DataTransfer
() Creates and returns a new DataTransfer object. Properties Standard properties DataTransfer.dropEffect Gets the type of drag-and-drop operation currently selected or sets the operation to a new type. The value must be none, copy, link or move. DataTransfer.effectAllowed Provides all of the types of operations that are possible. Must be one of none, copy, copyLink, copyMove, link, linkMove, move, all or uninitialized. DataTransfer.files ...
...s true if the user canceled the drag operation by pressing escape. It will be false in all other cases, including if the drag failed for any other reason, for instance due to a drop over an invalid location. Deprecated properties DataTransfer.mozItemCount Read only Gives the number of items in the drag operation. Removed in Firefox 71. ...
... drag operation. Removed in Firefox 71. Methods Standard methods DataTransfer.clearData
() Remove the data associated with a given type. The type argument is optional. If the type is empty or not specified, the data associated with all types is removed. If data for the specified type does not exist, or the data transfer contains no data, this method will have no effect. DataTransfer.getData
() Retrieves the data for a given type, or an empty string if data for that type does not exist or the data transfer contains no data. DataTransfer.setData
() Set the data for a given type. If data for the type does not exist, it is added at the end, such that the last item in the types list will be the new format. If data for the type already exists, the existing data is replaced in the same posi...
...And 5 more matches
DocumentFragment - Web APIs
Properties This interface has no specific properties, but inherits those of its parent, Node, and implements those of the ParentNode interface. ParentNode.children Read only Returns a live HTMLCollection containing all objects of type Element that are children of the DocumentFragment object. ParentNode.firstElementChild Read only Re...
...Child Read only Returns the Element that is the last child of the DocumentFragment object, or null if there is none. ParentNode.childElementCount Read only Returns an unsigned long giving the amount of children that the DocumentFragment has. Methods This interface inherits the methods of its parent, Node, and implements those of the ParentNode interface. ...
...only Returns an unsigned long giving the amount of children that the DocumentFragment has. Methods This interface inherits the methods of its parent, Node, and implements those of the ParentNode interface. DocumentFragment.querySelector
() Returns the first Element node within the DocumentFragment, in document order, that matches the specified selectors. DocumentFragment.querySelectorAll
() Returns a NodeList of all the Element nodes within the DocumentFragment that match the specified selectors. DocumentFragment.getElementById
() Returns the first Element node within the DocumentFragment, in document order, that matches the specified ID. Functionally equivalent to Document.getElementById
(). Usage notes A common use for DocumentFragment is to create one, assemble a DOM subtree ...
...And 5 more matches
Element: auxclick event - Web APIs
usedown and mouseup events have been fired, in that order. Bubbles Yes Cancelable Yes Interface MouseEvent Event handler property onauxclick Preventing default actions For the vast majority of browsers that map middle click to opening a link in a new tab, including Firefox, it is possible to cancel this behavior by calling preventDefault
() from within an auxclick event handler. When listening for auxclick events originating on elements that do not support input or navigation, you will often want to explicitly prevent other default actions mapped to the down action of the middle mouse button. On Windows this is usually autoscroll, and on macOS and Linux this is usually clipboard paste. This can be done by preventing the default beh...
... color of the button background, while the latter changes the button foreground (text) color. You also can see the two functions in action by trying the demo out with a multi-button mouse (see it live on GitHub; also see the source code). ...
...e the latter changes the button foreground (text) color. You also can see the two functions in action by trying the demo out with a multi-button mouse (see it live on GitHub; also see the source code). ...
...And 5 more matches
FileReader - Web APIs
Reader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. File objects may be obtained from a FileList object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile
() API on an HTMLCanvasElement. Important note: FileReader is used to read file content from the user's (remote) system in secure ways only. It cannot be used to simply read a file by pathname from a file system. To read files by pathname in JavaScript, standard Ajax solutions should be used to do server-side file reading, with CORS permission if reading cross-domain. Note: This feature is avail...
... FileReader is used to read file content from the user's (remote) system in secure ways only. It cannot be used to simply read a file by pathname from a file system. To read files by pathname in JavaScript, standard Ajax solutions should be used to do server-side file reading, with CORS permission if reading cross-domain. Note: This feature is available in Web Workers. Constructor FileReader
() Returns a newly constructed FileReader. See Using files from web applications for details and examples. Properties FileReader.error Read only A DOMException representing the error that occurred while reading the file. FileReader.readyState Read only A number indicating the state of the FileReader. This is one of the following: EMPTY 0 No data has been loaded yet. ...
... A handler for the loadend event. This event is triggered each time the reading operation is completed (either in success or failure). FileReader.onprogress A handler for the progress event. This event is triggered while reading a Blob content. As FileReader inherits from EventTarget, all those events can also be listened for by using the addEventListener method. ...
...And 5 more matches
HTMLAudioElement - Web APIs
Properties No specific properties; inherits properties from its parent, HTMLMediaElement, and from HTMLElement. Methods Inherits methods from its parent, HTMLMediaElement, and from HTMLElement. It offers no methods of its own. Obsolete Mozilla-only ...
...n audio file into it if the file URL is given. Properties No specific properties; inherits properties from its parent, HTMLMediaElement, and from HTMLElement. Methods Inherits methods from its parent, HTMLMediaElement, and from HTMLElement. It offers no methods of its own. Obsolete Mozilla-only methods The following methods are non-standard and should not be used. ...
...ement. Methods Inherits methods from its parent, HTMLMediaElement, and from HTMLElement. It offers no methods of its own. Obsolete Mozilla-only methods The following methods are non-standard and should not be used. mozCurrentSampleOffset
() Returns the number of samples form the beginning of the stream that have been written so far into the audio stream created by calling mozWriteAudio
(). mozSetup
() Sets up the audio stream to allow writing, given the number of audio channels (1 or 2) and the sample rate in kHz. ...
...And 5 more matches
HTMLInputElement - Web APIs
alues are none, off, characters, words, or sentences. inputmode Provides a hint to browsers as to the type of virtual keyboard configuration to use when editing this element or its contents. HTMLInputElement.align string: Represents the alignment of the element. Use CSS instead. HTMLInputElement.useMap string: Represents a client-side image map. Methods blur
() Removes focus from the input element; keystrokes will subsequently go nowhere. click
() Simulates a click on the input element. focus
() Focuses on the input element; keystrokes will subsequently go to this element. select
() Selects all the text in the input element, and focuses it so the user can subsequently replace all of its content. setSelectionR...
...Removes focus from the input element; keystrokes will subsequently go nowhere. click
() Simulates a click on the input element. focus
() Focuses on the input element; keystrokes will subsequently go to this element. select
() Selects all the text in the input element, and focuses it so the user can subsequently replace all of its content. setSelectionRange
() Selects a range of text in the input element (but does not focus it). setRangeText
() Replaces a range of text in the input element with new text. setCustomValidity
() Sets a custom validity message for the element. ...
...ctionRange
() Selects a range of text in the input element (but does not focus it). setRangeText
() Replaces a range of text in the input element with new text. setCustomValidity
() Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. checkValidity
() Returns a Boolean that is false if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires an invalid event at the element. It returns true if the element is not a candidate for constraint validation, or if it satisfies its constraints. ...
...And 5 more matches
IDBObjectStore - Web APIs
is object store. If this attribute is null, the application must provide a key for each modification operation. IDBObjectStore.name The name of this object store. IDBObjectStore.transaction Read only The IDBTransaction object to which this object store belongs. IDBObjectStore.autoIncrement Read only The value of the auto increment flag for this object store. Methods IDBObjectStore.add
() Returns an IDBRequest object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. This is for adding new records to an object store. IDBObjectStore.clear
() Creates and immediately returns an IDBRequest object, and clears this object store in a separate thread. This is for deleting all current records out of an object store. IDBO...
...Request object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. This is for adding new records to an object store. IDBObjectStore.clear
() Creates and immediately returns an IDBRequest object, and clears this object store in a separate thread. This is for deleting all current records out of an object store. IDBObjectStore.count
() Returns an IDBRequest object, and, in a separate thread, returns the total number of records that match the provided key or IDBKeyRange. ...
...est object, and clears this object store in a separate thread. This is for deleting all current records out of an object store. IDBObjectStore.count
() Returns an IDBRequest object, and, in a separate thread, returns the total number of records that match the provided key or IDBKeyRange. If no arguments are provided, it returns the total number of records in the store. IDBObjectStore.createIndex
() Creates a new index during a version upgrade, returning a new IDBIndex object in the connected database. IDBObjectStore.delete
() returns an IDBRequest object, and, in a separate thread, deletes the store object selected by the specified key. ...
...And 5 more matches
IDBObjectStoreSync - Web APIs
Constants Mode constants Constant Value Description READ_ONLY 1 Modification operations are not allowed on this object store. READ_WRITE 0 Modification operations are allowed on this object store. SNAPSHOT_READ 2 Any read operations must access a snapshot view of the data, which cannot change once it is created. Methods add
() Stores the given value into this object store, optionally with the specified key. If a record already exists with the given key, an exception is raised. any add( in any value, in optional any key ) raises (IDBDatabaseException); Parameters Returns Exceptions This method can raise a IDBDatabaseException with the following codes: value The value to store into the index. key A key t...
...h a key corresponding to the key parameter or the index is auto-populated, or if no record exists with a key corresponding to the value parameter in the index's referenced object store. DATA_ERR If this object store uses out-of-line keys, and the key parameter was not passed. SERIAL_ERR If the data being stored could not be serialized by the internal structured cloning algorithm. createIndex
() Creates and returns a new index with the given name in the connected database. IDBIndexSync createIndex ( in DOMString name, in DOMString keypath, in optional boolean unique ); Parameters name The name of a new index. keyPath The key path used by the new index. unique If true, keys in the index must be unique; if false, duplicate keys are allowed. Returns IDBIndexSy...
...in the connected database. IDBIndexSync createIndex ( in DOMString name, in DOMString keypath, in optional boolean unique ); Parameters name The name of a new index. keyPath The key path used by the new index. unique If true, keys in the index must be unique; if false, duplicate keys are allowed. Returns IDBIndexSync An object to access the newly created index. get
() Retrieves and returns the value from this object store for the record that corresponds to the given key. any get ( in any key ) raises (IDBDatabaseException); Parameters key The key that identifies the record to be retrieved. Returns any The value retrieved from the object store. Exceptions This method can raise a IDBDatabaseException with the following codes: SERIAL_ERR If...
...And 5 more matches
IDBTransaction - Web APIs
trans1.objectStore("foo") objectStore2.put("2", "key"); objectStore1.put("1", "key"); After the code is executed the object store should contain the value "2", since trans2 should run after trans1. Transaction failures Transactions can fail for a fixed number of reasons, all of which (except the user agent crash) will trigger an abort callback: Abort due to bad requests, e.g. trying to add
() the same key twice, or put
() with the same index key with a uniqueness constraint. This causes an error on the request, which can bubble up to an error on the transaction, which aborts the transaction. This can be prevented by using preventDefault
() on the error event on the request. An explicit abort
() call from script. An uncaught exception in the request's success/error handler. An I/O erro...
...ion. Properties IDBTransaction.db Read only The database connection with which this transaction is associated. IDBTransaction.error Read only Returns a DOMException indicating the type of error that occured when there is an unsuccessful transaction. ...
...IDBTransaction.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, 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 th...
...And 5 more matches
MediaRecorder - Web APIs
Options are available to do things like set the container's MIME type (such as "video/webm" or "video/mp4") and the bit rates of the audio and video tracks or a single overall bit rate. Properties MediaRecorder.mimeType Read only Returns the MIME type that was selected as the recording container for the MediaRecorder object when it was created. ...
...default is false. MediaRecorder.videoBitsPerSecond Read only Returns the video encoding bit rate in use. This may differ from the bit rate specified in the constructor (if it was provided). MediaRecorder.audioBitsPerSecond Read only Returns the audio encoding bit rate in use. This may differ from the bit rate specified in the constructor (if it was provided). ...
... Returns the video encoding bit rate in use. This may differ from the bit rate specified in the constructor (if it was provided). MediaRecorder.audioBitsPerSecond Read only Returns the audio encoding bit rate in use. This may differ from the bit rate specified in the constructor (if it was provided). Methods MediaRecorder.pause
() Pauses the recording of media. MediaRecorder.requestData
() Requests a Blob containing the saved data received thus far (or since the last time requestData
() was called. After calling this method, recording continues, but in a new Blob. MediaRecorder.resume
() Resumes recording of media after having been paused. MediaRecorder.start
() Begins recording media; this method can optionally be passed a timeslice argument with a value in milliseconds. If this...
...And 5 more matches
Path2D - Web APIs
The Path2D interface of the Canvas 2D API is used to declare a path that can then be used on a CanvasRenderingContext2D object. The path methods of the CanvasRenderingContext2D interface are also present on this interface, which gives you the convenience of being able to retain and replay your path whenever desired. Constructors Path2D
() Path2D constructor. Creates a new Path2D object. ...
...of the Canvas 2D API is used to declare a path that can then be used on a CanvasRenderingContext2D object. The path methods of the CanvasRenderingContext2D interface are also present on this interface, which gives you the convenience of being able to retain and replay your path whenever desired. Constructors Path2D
() Path2D constructor. Creates a new Path2D object. Methods Path2D.addPath
() Adds a path to the current path. ...
...n then be used on a CanvasRenderingContext2D object. The path methods of the CanvasRenderingContext2D interface are also present on this interface, which gives you the convenience of being able to retain and replay your path whenever desired. Constructors Path2D
() Path2D constructor. Creates a new Path2D object. Methods Path2D.addPath
() Adds a path to the current path. Path2D.closePath
() Causes the point of the pen to move back to the start of the current sub-path. ...
...And 5 more matches
Pointer events - Web APIs
this event is fired when the stylus leaves the hover range detectable by the digitizer. gotpointercapture ongotpointercapture Fired when an element receives pointer capture. lostpointercapture onlostpointercapture Fired after pointer capture is released for a pointer. Element extensions There are three extensions to the Element interface: setPointerCapture
() Designates a specific element as the capture target of future pointer events. releasePointerCapture
() This method releases (stops) pointer capture that was previously set for a specific pointer event. Navigator extension The Navigator.maxTouchPoints property is used to determine the maximum number of simultaneous touch points that are supported at any single point in time. Examples This s...
... function over_handler(event) { } function enter_handler(event) { } function down_handler(event) { } function move_handler(event) { } function up_handler(event) { } function cancel_handler(event) { } function out_handler(event) { } function leave_handler(event) { } function gotcapture_handler(event) { } function lostcapture_handler(event) { } function init
() { var el=document.getElementById("target"); // Register pointer event handlers el.onpointerover = over_handler; el.onpointerenter = enter_handler; el.onpointerdown = down_handler; el.onpointermove = move_handler; el.onpointerup = up_handler; el.onpointercancel = cancel_handler; el.onpointerout = out_handler; el.onpointerleave = leave_han...
...</div> </body> </html> Event properties This example illustrates accessing all of a touch event's properties. <html> <script> var id = -1; function process_id(event) { // Process this event based on the event's identifier } function process_mouse(event) { // Process the mouse pointer event } function process_pen(ev...
...And 5 more matches
SharedWorker - Web APIs
d from several browsing contexts, such as several windows, iframes or even workers. They implement an interface different than dedicated workers and have a different global scope, SharedWorkerGlobalScope. 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). Constructors SharedWorker
() Creates a shared web worker that executes the script at the specified URL. Properties Inherits properties from its parent, EventTarget, and implements properties from AbstractWorker. AbstractWorker.onerror Is an EventListener that is called whenever an ErrorEvent of type error bubbles through the worker. SharedWorker.port Read only Returns a MessagePort object used to communicate with ...
...ur Basic shared worker example (run shared worker), we have two HTML pages, each of which uses some JavaScript to perform a simple calculation. The different scripts are using the same worker file to perform the calculation -- they can both access it, even if their pages are running inside different windows. ...
...ws. The following code snippet shows creation of a SharedWorker object using the SharedWorker
() constructor. Both scripts contain this: var myWorker = new SharedWorker('worker.js'); Both scripts then access the worker through a MessagePort object created using the SharedWorker.port property. ...
...And 5 more matches
SourceBuffer - Web APIs
subsequently appended to the SourceBuffer. SourceBuffer.trackDefaults Specifies the default values to use if kind, label, and/or language information is not available in the initialization segment of the media to be appended to the SourceBuffer. SourceBuffer.updating Read only A boolean indicating whether the SourceBuffer is currently being updated -- i.e. whether an SourceBuffer.appendBuffer
(), SourceBuffer.appendStream
(), or SourceBuffer.remove
() operation is currently in progress. SourceBuffer.videoTracks Read only A list of the video tracks currently contained inside the SourceBuffer. Event handlers SourceBuffer.onabort Fired whenever SourceBuffer.appendBuffer
() or SourceBuffer.appendStream
() is ended by a call to SourceBuffer.abort
(). SourceBuffer.updating changes from tru...
...eBuffer.videoTracks Read only A list of the video tracks currently contained inside the SourceBuffer. Event handlers SourceBuffer.onabort Fired whenever SourceBuffer.appendBuffer
() or SourceBuffer.appendStream
() is ended by a call to SourceBuffer.abort
(). SourceBuffer.updating changes from true to false. SourceBuffer.onerror Fired whenever an error occurs during SourceBuffer.appendBuffer
() or SourceBuffer.appendStream
(). SourceBuffer.updating changes from true to false. SourceBuffer.onupdate Fired whenever SourceBuffer.appendBuffer
() method or the SourceBuffer.remove
() completes. ...
...rror occurs during SourceBuffer.appendBuffer
() or SourceBuffer.appendStream
(). SourceBuffer.updating changes from true to false. SourceBuffer.onupdate Fired whenever SourceBuffer.appendBuffer
() method or the SourceBuffer.remove
() completes. SourceBuffer.updating changes from true to false. This event is fired before onupdateend. SourceBuffer.onupdateend Fired whenever SourceBuffer.appendBuffer
() method or the SourceBuffer.remove
() has ended. This event is fired after onupdate. SourceBuffer.onupdatestart Fired whenever the value of SourceBuffer.updating transitions from false to true. Methods Inherits methods from its parent interface, EventTarget. SourceBuffer.abort
() Aborts the current segment and resets the segment parser. ...
...And 5 more matches
SpeechRecognition - Web APIs
s the controller interface for the recognition service; this also handles the SpeechRecognitionEvent sent from the recognition service. Note: On some browsers, like Chrome, using Speech Recognition on a web page involves a server-based recognition engine. Your audio is sent to a web service for recognition processing, so it won't work offline. Constructor SpeechRecognition.SpeechRecognition
() Creates a new SpeechRecognition object. Properties SpeechRecognition also inherits properties from its parent interface, EventTarget. SpeechRecognition.grammars Returns and sets a collection of SpeechGrammar objects that represent the grammars that will be understood by the current SpeechRecognition. SpeechRecognition.lang Returns and sets the language of the current SpeechRecognition. ...
...nitionAlternatives provided per result. The default value is 1. SpeechRecognition.serviceURI Specifies the location of the speech recognition service used by the current SpeechRecognition to handle the actual recognition. The default is the user agent's default speech service. Methods SpeechRecognition also inherits methods from its parent interface, EventTarget. ...
... by the current SpeechRecognition to handle the actual recognition. The default is the user agent's default speech service. Methods SpeechRecognition also inherits methods from its parent interface, EventTarget. SpeechRecognition.abort
() Stops the speech recognition service from listening to incoming audio, and doesn't attempt to return a SpeechRecognitionResult. SpeechRecognition.start
() Starts the speech recognition service listening to incoming audio with intent to recognize grammars associated with the current SpeechRecognition. ...
...And 5 more matches
SpeechSynthesis - Web APIs
pending Read only A Boolean that returns true if the utterance queue contains as-yet-unspoken utterances. SpeechSynthesis.speaking Read only A Boolean that returns true if an utterance is currently in the process of being spoken -- even if SpeechSynthesis is in a paused state. Methods SpeechSynthesis also inherits methods from its parent interface, EventTarget. SpeechSynthesis.cancel
() Removes all utterances from the utterance queue. SpeechSynthesis.getVoices
() Returns a list of SpeechSynthesisVoice objects representing all the available voices on the current device. SpeechSynthesis.pause
() Puts the SpeechSynthesis object into a paused state. SpeechSynthesis.resume
() Puts the SpeechSynthesis object into a non-paused state: resumes it if it was already paused. SpeechSynt...
...ll utterances from the utterance queue. SpeechSynthesis.getVoices
() Returns a list of SpeechSynthesisVoice objects representing all the available voices on the current device. SpeechSynthesis.pause
() Puts the SpeechSynthesis object into a paused state. SpeechSynthesis.resume
() Puts the SpeechSynthesis object into a non-paused state: resumes it if it was already paused. SpeechSynthesis.speak
() Adds an utterance to the utterance queue; it will be spoken when any other utterances queued before it have been spoken. Events Listen to this event using addEventListener
() or by assigning an event listener to the oneventname property of this interface. ...
... Also available via the onvoiceschanged property. Examples First, a simple example: let utterance = new SpeechSynthesisUtterance("Hello world!"); speechSynthesis.speak(utterance); Now we'll look at a more fully-fledged example. In our Speech synthesiser demo, we first grab a reference to the SpeechSynthesis controller using window.speechSynthesis. ...
...And 5 more matches
SpeechSynthesisUtterance - Web APIs
Properties SpeechSynthesisUtterance also inherits properties from its parent interface, EventTarget. ...
...which the utterance will be spoken at. SpeechSynthesisUtterance.text Gets and sets the text that will be synthesised when the utterance is spoken. SpeechSynthesisUtterance.voice Gets and sets the voice that will be used to speak the utterance. SpeechSynthesisUtterance.volume Gets and sets the volume that the utterance will be spoken at. Events Listen to these events using addEventListener
() or by assigning an event listener to the oneventname property of this interface. boundary Fired when the spoken utterance reaches a word or sentence boundary. Also available via the onboundary property. end Fired when the utterance has finished being spoken. Also available via the onend property. error Fired when an error occurs that prevents the utterance from being succesfully spoken.
...available via the onresume property. start Fired when the utterance has begun to be spoken. Also available via the onstart property. Examples In our basic Speech synthesiser demo (source), we first grab a reference to the SpeechSynthesis controller using window.speechSynthesis. ...
...And 5 more matches
Multi-touch interaction - Web APIs
background: white; border: 1px solid black; } #target3 { background: white; border: 1px solid black; } #target4 { background: white; border: 1px solid black; } </style> Global state tpCache is used to cache touch points for processing outside of the event where they were fired. // Log events flag var logEvents = false; // Touch Point cache var tpCache = new Array
(); Register event handlers Event handlers are registered for all four touch event types. The touchend and touchcancel event types use the same handler. function set_handlers(name) { // Install event handlers for the given element var el=document.getElementById(name); el.ontouchstart = start_handler; el.ontouchmove = move_handler; // Use same handler for touchcancel and touchend el.ontouch...
...our touch event types. The touchend and touchcancel event types use the same handler. function set_handlers(name) { // Install event handlers for the given element var el=document.getElementById(name); el.ontouchstart = start_handler; el.ontouchmove = move_handler; // Use same handler for touchcancel and touchend el.ontouchcancel = end_handler; el.ontouchend = end_handler; } function init
() { set_handlers("target1"); set_handlers("target2"); set_handlers("target3"); set_handlers("target4"); } Move/Pinch/Zoom handler This function provides very basic support for 2-touch horizontal move/pinch/zoom handling. The code does not include error handling, or vertical moving. Note that the threshold for pinch and zoom movement detection is application specific (and device dependent). ...
... function start_handler(ev) { // If the user makes simultaneous touches, the browser will fire a // separate touchstart event for each touch point. Thus if the...
...And 5 more matches
Geometry and reference spaces in WebXR - Web APIs
s and code to use the same coordinate system as WebGL does. The WebGL coordinates and lengths are transformed automatically at render time to the size of the viewport in which the scene is being rendered. Angles Angles are specified using radians. To convert degrees to radians, simply multiply the value in degrees by ?/180. The following code snippet shows two simple functions, degreesToRadians
() and radiansToDegrees
(), which convert back and forth between the two units for measuring angles. const RADIANS_PER_DEGREE = Math.PI / 180.0; let degreesToRadians = (deg) => deg * RADIANS_PER_DEGREE; let radiansToDegrees = (rad) => rad / RADIANS_PER_DEGREE; Times and durations Note that for security reasons, DOMHighResTimeStamp usually introduces a small amount of imprecision to the clock in ...
...itten using WebXR will still work, within the limitations of the available hardware. Regardless of the type of reference space you choose, its type is XRReferenceSpace or is a type derived from XRReferenceSpace. The currently available reference space types, which are defined by the XRReferenceSpaceType enumeration, are shown below. The reference space returned by XRSession.requestReferenceSpace
() is either XRReferenceSpace or XRBoundedReferenceSpace. The "Interface" column in the table below indicates which of the two types is returned for each reference space type constant.. Reference space descriptors The types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. XRReferenceSpaceType ...
...ss a floor is otherwise established. These space types are not viable if the rooms have uneven floors or floors whose height above ground level vary, since they don't support the avatar's vertical position changing. The primary reference space types The viewer reference space corresponds to the viewer's position in space; it's used by the XRViewerPose returned by the XRFrame method getViewerPose
(). It's not typically used directly otherwise. The only real exception is that you are likely to use the viewer reference space when performing the XR scene inline within web content. The local reference space is typically used to describe a relatively small area, such as a single room. It is not only always available when using an immersive session mode (immersive-vr or immersive-ar), but is alwa...
...And 5 more matches
Using IIR filters - Web APIs
lculated based on the lowpass filter specified in the filter characteristics of the Web Audio API specification. As this filter node gains more popularity we should be able to collate more coefficient values. ...
...hould be able to collate more coefficient values. Using an IIRFilter in an audio graph Let's create our context and our filter node: const AudioContext = window.AudioContext || window.webkitAudioContext; const audioCtx = new AudioContext
(); const iirFilter = audioCtx.createIIRFilter(feedForward, feedBack); We need a sound source to play. ...
...const iirFilter = audioCtx.createIIRFilter(feedForward, feedBack); We need a sound source to play. We set this up using a custom function, playSoundNode
(), which creates a buffer source from an existing AudioBuffer, attaches it to the default destination, starts it playing, and returns it: function playSourceNode(audioContext, audioBuffer) { const soundSource = audioContext.createBufferSource
(); soundSource.buffer = audioBuffer; soundSource.connect(audioContext.destination); soundSource.start
(); return soundSource; } This function is called when the play button is pressed. The play button HTML looks like this: <button class="button-play" role="switch" data-playing="false" aria-pressed="false">Play</button> And the click event listener starts like so: playButton.addEventListe...
...And 5 more matches
Using the Web Storage API - Web APIs
This article provides a walkthrough of how to make use of this technology. Basic concepts Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings). You can access these values like an object, or with the Storage.getItem
() and Storage.setItem
() methods. These three lines all set the (same) colorSetting entry: localStorage.colorSetting = '#a4509b'; localStorage['colorSetting'] = '#a4509b'; localStorage.setItem('colorSetting', '#a4509b'); Note: It's recommended to use the Web Storage API (setItem, getItem, removeItem, key, length) to prevent the pitfalls associated with using plain objects as key-value stores. T...
...rmation outputted as a StorageEvent is fired. Note: As well as viewing the example pages live using the above links, you can also check out the source code. Testing whether your storage has been populated To start with, in main.js, we test whether the storage object has already been populated (i.e., the page was previously accessed): if(!localStorage.getItem('bgcolor')) { populateStorage
(); } else { setStyles
(); } The Storage.getItem
() method is used to get a data item from storage; in this case, we are testing to see whether the bgcolor item exists; if not, we run populateStorage
() to add the existing customization values to the storage. If there are already values there, we run setStyles
() to update the page styling with the stored values. Note: You could also use Storage.len...
...exists; if not, we run populateStorage
() to add the existing customization values to the storage. If there are already values there, we run setStyles
() to update the page styling with the stored values. Note: You could also use Storage.length to test whether the storage object is empty or not. Getting values from storage As noted above, values can be retrieved from storage using Storage.getItem
(). This takes the key of the data item as an argument, and returns the data value. ...
...And 5 more matches
window.location - Web APIs
synonym of location.href = 'http://www.example.com'. See Location for all available properties. ...
...ation.assign
() had been called with the modified URL. Note that security settings, like CORS, may prevent this to effectively happen. ...
...may prevent this to effectively happen. ...
...And 5 more matches
-webkit-border-before - CSS: Cascading Style Sheets
) | rgb( ...
...one or hiddenborder-top-width: the absolute length or 0 if border-top-style is none or hiddenborder-style: as each of the properties of the shorthand:border-bottom-style: as specifiedborder-left-style: as specifiedborder-right-style: as specifiedborder-top-style: as specifiedcolor: If the value is translucent, the computed value will be the rgba
() corresponding one. If it isn't, it will be the rgb
() corresponding one. ...
...specifiedborder-left-style: as specifiedborder-right-style: as specifiedborder-top-style: as specifiedcolor: If the value is translucent, the computed value will be the rgba
() corresponding one. If it isn't, it will be the rgb
() corresponding one. ...
...And 5 more matches
Using CSS gradients - CSS: Cascading Style Sheets
CSS gradients are represented by the <gradient> data type, a special type of <image> made of a progressive transition between two or more colors. You can choose between three types of gradients: linear (created with the linear-gradient
() function), radial (created with radial-gradient
()), and conic (created with the conic-gradient
() function). You can also create repeating gradients with the repeating-linear-gradient
(), repeating-radial-gradient
(), and repeating-conic-gradient
() functions. Gradients can be used anywhere you would use an <image>, such as in backgrounds. Because gradients are dynamically generated, they can negate the need for the raster image files that traditionally were used to achieve similar effects. In addition, because gradients are generated by the browser, they look...
...Example conic gradients include pie charts and color wheels, but they can also be used for creating checker boards and other intersting effects. The conic-gradient syntax is similar to the radial-gradient syntax, but the color-stops are placed aroun...
... The size of the gradient line or arc that repeats is the length between the first color stop value and the last color stop length value. If th...
...And 5 more matches
Basic Shapes - CSS: Cascading Style Sheets
x; } What is worth noting is that the margin-box will clip the shape, therefore shapes created in reference to other shapes which extend past the margin box will have the shape clipped to the margin box. We will see this in the following examples of basic shapes. For an excellent description of references boxes as they apply to CSS Shapes see Understanding Reference Boxes for CSS Shapes. inset
() The inset
() type defines a rectangle, which may not seem very useful as simply floating an item will give you a rectangular shape around it. However the inset
() types enables the definition of offsets, thus pulling the content in over the shape. Therefore inset
() takes four values for the top, right, bottom and left values plus a final value for border-radius. The below CSS creates a rectangula...
... the second. If there are three values, the top is set to the first value, the left and right are set to the second, and the bottom is set to the third. If there are four values, they apply to the top, right, bottom, and left, respectively. ...
...This argument can be a length or percentage but can also be one of the keywords closest-side or farthest-side. ...
...And 5 more matches
Specificity - CSS: Cascading Style Sheets
the specificity. Selector Types The following list of selector types increases by specificity: Type selectors (e.g., h1) and pseudo-elements (e.g., ::before). Class selectors (e.g., .example), attributes selectors (e.g., [type="radio"]) and pseudo-classes (e.g., :hover). ID selectors (e.g., #example). Universal selector (*), combinators (+, >, ~, ' ', ||) and negation pseudo-class (:not
()) have no effect on specificity. (The selectors declared inside :not
() do, however.) For more information, visit: "Specificity" in "Cascade and inheritance", you can also visit: https://specifishity.com Inline styles added to an element (e.g., style="font-weight: bold;") always overwrite any styles in external stylesheets, and thus can be thought of as having the highest specificity. The !impor...
...But selectors placed into the pseudo-class count as normal selectors when determining the count of selector types. This chunk of CSS ... div.outer p { color: orange; } div:not(.outer) p { color: blueviolet; } ... when used wit...
...But selectors placed into the pseudo-class count as normal selectors when determining the count of selector types. This chunk of CSS ... div.outer p { color: orange; } div:not(.outer) p { color: blueviolet; } ... when used with the follo...
...And 5 more matches
<filter-function> - CSS: Cascading Style Sheets
The <filter-function> CSS data type represents a graphical effect that can change the appearance of an input image. It is used in the filter and backdrop-filter properties. Syntax The <filter-function> data type is specified using one of the filter functions listed below. Each function requires an argument which, if invalid, results in no filter being applied. blur
() Blurs the image. ...
...<filter-function> CSS data type represents a graphical effect that can change the appearance of an input image. It is used in the filter and backdrop-filter properties. Syntax The <filter-function> data type is specified using one of the filter functions listed below. Each function requires an argument which, if invalid, results in no filter being applied. blur
() Blurs the image. brightness
() Makes the image brighter or darker. contrast
() Increases or decreases the image's contrast. drop-shadow
() Applies a drop shadow behind the image. grayscale
() Converts the image to grayscale. hue-rotate
() Changes the overall hue of the image. invert
() Inverts the colors of the image. opacity
() Makes the image transparent. saturate
() Super-saturates or desaturates the input image. s...
... Examples Filter function comparison This example provides a simple graphic, along with a select menu to allow you to choose between the different types of filter function, and a slider to allow you to vary the values used inside the filter function. ...
...And 5 more matches
outline-color - CSS: Cascading Style Sheets
N Understanding WCAG, Guideline 1.4 explanations Understanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0 Formal definition Initial valueinvert, for browsers supporting it, currentColor for the otherApplies toall elementsInheritednoComputed valueFor the keyword invert, the computed value is invert. ...
...erstanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0 Formal definition Initial valueinvert, for browsers supporting it, currentColor for the otherApplies toall elementsInheritednoComputed valueFor the keyword invert, the computed value is invert. For the color value, if the value is translucent, the computed value will be the rgba
() corresponding one. If it isn't, it will be the rgb
() corresponding one. ...
...Color for the otherApplies toall elementsInheritednoComputed valueFor the keyword invert, the computed value is invert. For the color value, if the value is translucent, the computed value will be the rgba
() corresponding one. If it isn't, it will be the rgb
() corresponding one. ...
...And 5 more matches
<transform-function> - CSS: Cascading Style Sheets
sents a transformation that affects an element's appearance. Transformation functions can rotate, resize, distort, or move an element in 2D or 3D space. It is used in the transform property. Syntax The <transform-function> data type is specified using one of the transformation functions listed below. Each function applies a geometric operation in either 2D or 3D. ...
...ansformation functions can rotate, resize, distort, or move an element in 2D or 3D space. It is used in the transform property. Syntax The <transform-function> data type is specified using one of the transformation functions listed below. Each function applies a geometric operation in either 2D or 3D. Matrix transformation matrix
() Describes a homogeneous 2D transformation matrix. matrix3d
() Describes a 3D transformation as a 4x4 homogeneous matrix. ...
...t is used in the transform property. Syntax The <transform-function> data type is specified using one of the transformation functions listed below. Each function applies a geometric operation in either 2D or 3D. Matrix transformation matrix
() Describes a homogeneous 2D transformation matrix. matrix3d
() Describes a 3D transformation as a 4x4 homogeneous matrix. Perspective perspective
() Sets the distance between the user and the z=0 plane. Rotation rotate
() Rotates an element around a fixed point on the 2D plane. ...
...And 5 more matches
Parsing and serializing XML - Developer guides
ions of an XML document, and locating XML nodes based on those addresses. Creating an XML document Using one of the following approaches to create an XML document (which is an instance of Document. ...
... If the document is HTML, the code shown above will return a Document. If t...
... If the document is HTML, the code shown above will return a Document. If the document is XML, the r...
...And 5 more matches
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
mg> or SVG <svg> element, attempting to retrieve the contents of the canvas isn't allowed. If the foreign content comes from an image obtained from either as HTMLCanvasElement or ImageBitMap, and the image source doesn't meet the same origin rules, attempts to read the canvas's contents are blocked. Calling any of the following on a tainted canvas will result in an error: Calling getImageData
() on the canvas's context Calling toBlob
() on the <canvas> element itself Calling toDataURL
() on the canvas Attempting any of these when the canvas is tainted will cause a SecurityError to be thrown. This protects users from having private data exposed by using images to pull information from remote web sites without permission. Storing an image from a foreign origin In this example, we wish ...
...omain the code is running on. The key is to use the crossorigin attribute by setting crossOrigin on the HTMLImageElement into which the image will be loaded. This tells the browser to request cross-origin access when trying to download the image data. Starting the download The code that starts the download (say, when the user clicks a "Download" button), looks like this: function startDownload
() { let imageURL = "https://cdn.glitch.com/4c9ebeb9-8b9a-4adc-ad0a-238d9ae00bb5%2Fmdn_logo-only_color.svg?1535749917189"; downloadedImg = new Image; downloadedImg.crossOrigin = "Anonymous"; downloadedImg.addEventListener("load", imageReceived, false); downloadedImg.src = imageURL; } We're using a hard-coded URL here (imageURL), but that could easily come from anywhere. To begin download...
...ae00bb5%2Fmdn_logo-only_color.svg?1535749917189"; downloadedImg = new Image; downloadedImg.crossOrigin = "Anonymous"; downloadedImg.addEventListener("load", imageReceived, false); downloadedImg.src = imageURL; } We're using a hard-coded URL here (imageURL), but that could easily come from anywhere. To begin downloading the image, we create a new HTMLImageElement object by using the Image
() constructor. The image is then configured to allow cross-origin downloading by setting its crossOrigin attribute to "Anonymous" (that is, allow non-authenticated downloading of the image cross-origin). An event listener is added for the load event being fired on the image element, which means the image data has been received. Finally, the image's src attribute is set to the URL of the image to d...
...And 5 more matches
<input type="color"> - HTML: Hypertext Markup Language
o contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Value A 7-character DOMString specifying a <color> in lower-case hexadecimal notation Events change and input Supported common attributes autocomplete and list IDL attributes list and value Methods select
() Value The value of an <input> element of type color is always a DOMString which contains a 7-character string specifying an RGB color in hexadecimal format. While you can input the color in either upper- or lower-case, it will be stored in lower-case form. The value is never in any other form, and is never empty. Note: Setting the value to anything that isn't a valid, fully-opaque, RGB ...
...o that color: <input type="color" value="#ff0000"> If you don't specify a value, the default is #000000, which is black. The value must be in seven-character hexadecimal notation, meaning the "#" character followed by two digits each representing red, green, and blue, like this: #rrggbb. If you have colors that are in any other format (such as CSS color names or CSS color functions such as rgb
() or rgba
()), you'll have to convert them to hexadecimal before setting the value. Tracking color changes As is the case with other <input> types, there are two events that can be used to detect changes to the color value: input and change. input is fired on the <input> element every time the color changes. The change event is fired when the user dismisses the color picker. In both cases, you can...
...r("change", watchColorPicker, false); function watchColorPicker(event) { document.querySelectorAll("p").forEach(function(p) { p.style.color = event.target.value; }); } Selecting the value If the <input> element's implementation of the color type on the user's browser doesn't support a color well, but is instead a text field for entering the color string directly, you can use the select
() method to select the text currently in the edit field. If the browser instead uses a color well, select
() does nothing. You should be aware of this behavior so your code can respond appropriately in either case. colorWell.select
(); Appearance variations As previously mentioned, when a browser doesn't support a color picker interface, its implementation of color inputs will be a text box that v...
...And 5 more matches
HTTP Index - HTTP
ctive controls whether the current document is allowed to autoplay media requested through the HTMLMediaElement interface. 126 Feature-Policy: battery The HTTP Feature-Policy header battery directive controls whether the current document is allowed to gather information about the acceleration of the device through the BatteryManager interface obtained via Navigator.getBattery
(). 127 Feature-Policy: camera Directive, Feature Policy, Feature-Policy, HTTP, Reference, camera The HTTP Feature-Policy header camera directive controls whether the current document is allowed to use video input devices. When this policy is enabled, the Promise returned by MediaDevices.getUserMedia
() will reject with a NotAllowedError. 128 Feature-Policy: display-ca...
...ls whether the current document is allowed to use video input devices. When this policy is enabled, the Promise returned by MediaDevices.getUserMedia
() will reject with a NotAllowedError. 128 Feature-Policy: display-capture The HTTP Feature-Policy header display-capture directive controls whether or not the document is permitted to use Screen Capture API, i.e.,getDisplayMedia
() to capture the screen's contents. 129 Feature-Policy: document-domain Directive, Experimental, Feature Policy, Feature-Policy, HTTP, Reference, document-domain, header The HTTP Feature-Policy header document-domain directive controls whether the current document is allowed to set document.domain. When this policy is enabled, attempting to set document.domain will fail and cau...
...ror DOMException to be be thrown. 130 Feature-Policy: encrypted-media Directive, EME, Feature Policy, Feature-Policy, HTTP, Reference The HTTP Feature-Policy header encrypted-media directive controls whether the current document is allowed to use the Encrypted Media Extensions API (EME). When this policy is enabled, the Promise returned by Navigator.requestMediaKeySystemAccess
() will reject with a DOMException. 131 Feature-Policy: fullscreen Feature Policy, Feature-Policy, HTTP, fullscreen, header The HTTP Feature-Policy header fullscreen directive controls whether the current document is allowed to use Element.requestFullScreen
(). When this policy is enabled, the returned Promise rejects with a TypeError. 132 Feature-Policy: geolocation ...
...And 5 more matches
static - JavaScript
tances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects. 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 static methodName
() { ... } Examples Using static in classes The following example demonstrates several things: How a static method is implemented on a class. That a class with a static member can be sub-classed. How a static method can and cannot be called. class Triple { static triple(n = 1) { return n * 3; } } class BiggerTriple extends Triple { static triple(n) { return super.triple(n) *...
...ollowing example demonstrates several things: How a static method is implemented on a class. That a class with a static member can be sub-classed. How a static method can and cannot be called. class Triple { static triple(n = 1) { return n * 3; } } class BiggerTriple extends Triple { static triple(n) { return super.triple(n) * super.triple(n); } } console.log(Triple.triple
()); // 3 console.log(Triple.triple(6)); // 18 var tp = new Triple
(); console.log(BiggerTriple.triple(3)); // 81 (not affected by parent's instantiation) console.log(tp.triple
()); // 'tp.triple is not a function'. Calling static methods from another static method In order to call a static method within another static method of the same class, you can use the this keyword. class S...
...e(6)); // 18 var tp = new Triple
(); console.log(BiggerTriple.triple(3)); // 81 (not affected by parent's instantiation) console.log(tp.triple
()); // 'tp.triple is not a function'. Calling static methods from another static method In order to call a static method within another static method of the same class, you can use the this keyword. ...
...And 5 more matches
SyntaxError: missing } after function body - JavaScript
yntaxError What went wrong? There is a syntax mistake when creating a function somewhere. Also check if any closing curly brackets or parenthesis are in the correct order. Indenting or formatting the code a bit nicer might also help you to see through the jungle. ...
...s a syntax mistake when creating a function somewhere. Also check if any closing curly brackets or parenthesis are in the correct order. Indenting or formatting the code a bit nicer might also help you to see through the jungle. ...
...a function somewhere. Also check if any closing curly brackets or parenthesis are in the correct order. Indenting or formatting the code a bit nicer might also help you to see through the jungle. ...
...And 5 more matches
SyntaxError: function statement requires a name - JavaScript
ment in the code that requires a name. You'll need to check how functions are defined and if you need to provide a name for it, or if the function in question needs to be a function expression, an IIFE, or if the function code is placed correctly in this context at all. ...
...eds to be a function expression, an IIFE, or if the function code is placed correctly in this context at all. Examples Statements vs expressions A function statement (or function declaration) requires a name, this won't work: function
() { return 'Hello world'; } // SyntaxError: function statement requires a name You can use a function expression (assignment) instead: var greet = function
() { return 'Hello world'; }; Or, you function is maybe intended to be an IIFE (Immediately Invoked Function Expression), which is a function that runs as soon as it is defined. You will need a few more braces in this case: (function
() { })
(); Labeled functions If you are using function labels, you will still need to provide a function name after the function keyword. This doesn't work: fun...
...Hello world'; }; Or, you function is maybe intended to be an IIFE (Immediately Invoked Function Expression), which is a function that runs as soon as it is defined. You will need a few more braces in this case: (function
() { })
(); Labeled functions If you are using function labels, you will still need to provide a function name after the function keyword. This doesn't work: function Greeter
() { german: function
() { return "Moin"; } } // SyntaxError: function statement requires a name This would work, for example: function Greeter
() { german: function g
() { return "Moin"; } } Object methods If you intended to create a method of an object, you will need to create an object. The following syntax without a name after the function keyword is valid then. var greeter =...
...And 5 more matches
Error.prototype.stack - JavaScript
imes. For example, Firefox sets it when creating an Error object, while PhantomJS sets it only when throwing the Error, and archived MSDN docs also seem to match the PhantomJS implementation. Examples Using the stack property The following HTML markup demonstrates the use of stack property. ...
...n throwing the Error, and archived MSDN docs also seem to match the PhantomJS implementation. Examples Using the stack property The following HTML markup demonstrates the use of stack property. ...
...he Error, and archived MSDN docs also seem to match the PhantomJS implementation. Examples Using the stack property The following HTML markup demonstrates the use of stack property. ...
...And 5 more matches
WeakRef - JavaScript
ject in memory. When an object no longer has any strong references to it, the JavaScript engine's garbage collector may destroy the object and reclaim its memory. If that happens, you can't get the object from a weak reference anymore. Note: Please see the Avoid where possible section below. Correct use of WeakRef takes careful thought, and it's best avoided if possible. Constructor WeakRef
() Creates a new WeakRef object. Instance methods WeakRef.prototype.deref
() Returns the WeakRef object's target object, or undefined if the target object has been reclaimed. Avoid where possible Correct use of WeakRef takes careful thought, and it's best avoided if possible. It's also important to avoid relying on any specific behaviors not guaranteed by the specification. When, how, and w...
...f, even if nothing strongly holds the target, because the garbage collector may never decide to reclaim the object. ...
...ng strongly holds the target, because the garbage collector may never decide to reclaim the object. ...
...And 5 more matches
WebAssembly.Global - JavaScript
A WebAssembly.Global object represents a global variable instance, accessible from both JavaScript and importable/exportable across one or more WebAssembly.Module instances. This allows dynamic linking of multiple modules. Constructor WebAssembly.Global
() Creates a new Global object. Global instances All Global instances inherit from the Global
() constructor's prototype object -- this can be modified to affect all Global instances. Instance properties Global.prototype.constructor Returns the function that created this object's instance. By default this is the WebAssembly.Global
() constructor. Global.prototype[@@toStringTag] The initial value of the @@toStringTag property is the String value "WebAssembly.Global". Global.prototype.value The value contained inside the global v...
...It is being defined as a mutable i32 type, with a value of 0. ...
... Global.prototype.value The value contained inside the global variable -- this can be used to directly set and get the global's value. Instance methods Global.prototype.valueOf
() Old-style method that returns the value contained inside the global variable. Examples Creating a new Global instance The following example shows a new global instance being created using the WebAssembly.Global
() constructor. It is being defined as a mutable i32 type, with a value of 0. The value of the global is then changed, first to 42 using the Global.value property, and then to 43 using the incGlobal
() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the new value). const output = document.getElementById('output'); function assertEq(msg...
...And 5 more matches
Nullish coalescing operator (??) - JavaScript
) let notFalsyText = myText || 'Hello world'; console.log(notFalsyText); // Hello world let preservingFalsy = myText ?? 'Hi neighborhood'; console.log(preservingFalsy); // '' (as myText is neither undefined nor null) Short-circuiting Like the OR and AND logical operators, the right-hand side expression is not evaluated if the left-hand side proves to be neither null nor undefined. ...
...alsyText); // Hello world let preservingFalsy = myText ?? 'Hi neighborhood'; console.log(preservingFalsy); // '' (as myText is neither undefined nor null) Short-circuiting Like the OR and AND logical operators, the right-hand side expression is not evaluated if the left-hand side proves to be neither null nor undefined. ...
...'Hi neighborhood'; console.log(preservingFalsy); // '' (as myText is neither undefined nor null) Short-circuiting Like the OR and AND logical operators, the right-hand side expression is not evaluated if the left-hand side proves to be neither null nor undefined. ...
...And 5 more matches
instanceof - JavaScript
ibute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax object instanceof constructor Parameters object The object to test. constructor Function to test against Description The instanceof operator tests the presence of constructor.prototype in object's prototype chain. ...
...eractive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax object instanceof constructor Parameters object The object to test. constructor Function to test against Description The instanceof operator tests the presence of constructor.prototype in object's prototype chain. ...
...oject, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax object instanceof constructor Parameters object The object to test. constructor Function to test against Description The instanceof operator tests the presence of constructor.prototype in object's prototype chain. ...
...And 5 more matches
yield - JavaScript
ike to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax [rv] = yield [expression] expression Optional Defines the value to return from the generator function via the iterator protocol. If omitted, undefined is returned instead. rv Optional Retrieves the optional value passed to the generator's next
() method to resume its execution. Description The yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword. yield can only be called directly from the generator function that contains it. It cannot be called from nested functions o...
...enerator function execution and the value of the expression following the yield keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword. yield can only be called directly from the generator function that contains it. It cannot be called from nested functions or from callbacks. ...
... The yield keyword causes the call to the generator's next
() method to return an IteratorResult object with two properties: value and done. The value property is the result of evaluating the yield expression, and done is false, indicating that the generator function has not fully completed. Once paused on a yield expression, the generator's code execution remains paused until the generator's next
() method is called. Each time the generator's next
() method is called, the generator resumes execution, and runs until it reaches one of the following: A yield, which causes the generator to once again pause and return the generator's new value. The next time next
() is called, execution resumes with the statement immediately after the yield. throw is used to throw an exception from the generato...
...And 5 more matches
Exported WebAssembly functions - WebAssembly
you get some activity in the background to convert the arguments into types that wasm can work with (for example converting JavaScript numbers to Int32), the arguments are passed to the function inside your wasm module, the function is invoked, and the result is converted and passed back to JavaScript. You can retrieve exported WebAssembly functions in two ways: By calling Table.prototype.get
() on an existing table. By accessing a function exported from a wasm module instance via Instance.exports. Either way, you get the same kind of wrapper for the underlying function. From a JavaScript point of view, it's as if every wasm function is a JavaScript function too -- but they are encapsulated by the exported wasm function object instance and there are only limited ways to access them. ...
...o access them. An example Let's look at an example to clear things up (you can find this on GitHub as table-set.html; see it running live also, and check out the wasm text representation): var otherTable = new WebAssembly.Table({ element: "anyfunc", initial: 2 }); WebAssembly.instantiateStreaming(fetch('table.wasm')) .then(obj => { var tbl = obj.instance.exports.tbl; console.log(tbl.get(0)
()); // 13 console.log(tbl.get(1)
()); // 42 otherTable.set(0,tbl.get(0)); otherTable.set(1,tbl.get(1)); console.log(otherTable.get(0)
()); console.log(otherTable.get(1)
()); }); Here we create a table (otherTable) from JavaScript using the WebAssembly.Table constructor, then we load table.wasm into our page using the WebAssembly.instantiateStreaming
() method. We then get the function exp...
... To prove this, we then retrieve these references back from otherTable and print their results to console too, which gives the same results. ...
...And 5 more matches
Compiling an Existing C Module to WebAssembly - WebAssembly
ings. Emscripten provides most of these features, although there are some limitations. As an example, let's compile an encoder for WebP to wasm. The source for the WebP codec is written in C and available on GitHub as well as some extensive API documentation. That's a pretty good starting point. $ git clone https://github.com/webmproject/libwebp To start off simple, expose WebPGetEncoderVersion
() from encode.h to JavaScript by writing a C file called webp.c: #include "emscripten.h" #include "src/webp/encode.h" EMSCRIPTEN_KEEPALIVE int version
() { return WebPGetEncoderVersion
(); } This is a good simple program to test whether you can get the source code of libwebp to compile, as it doesn't require any parameters or complex data structures to invoke this function. To compile this prog...
...configure and emmake to wrap these commands and inject the appropriate parameters. You can find more in the Emscripten documentation. Now you only need some HTML and JavaScript to load your new module: <script src="./a.out.js"></script> <script> Module.onRuntimeInitialized = async _ => { const api = { version: Module.cwrap('version', 'number', []), }; console.log(api.version
()); }; </script> And you will see the correct version number in the output: Note: libwebp returns the current version a.b.c as a hexadecimal number 0xabc. For example, v0.6.1 is encoded as 0x000601 = 1537. Get an image from JavaScript into Wasm Getting the encoder's version number is great, but encoding an actual image would be more impressive. How do we do that? The first question you n...
...r is: how do I get the image into wasm? Looking at the encoding API of libwebp, you'll find that it expects an array of bytes in RGB, RGBA, BGR or BGRA. ...
...And 5 more matches
Private Properties - Archive of obsolete content
ty name with an underscore. Consider the following example: function Point(x, y) { this._x = x; this._y = y; } The properties _x and _y are intended to be private, and should only be accessed by member functions. To make a private property readable/writable from any function, it's common to define getter/setter functions for the property, respectively: Point.prototype.getX = function
() { return this._x; }; Point.prototype.setX = function (x) { this._x = x; }; Point.prototype.getY = function
() { return this._y; }; Point.prototype.setY = function (y) { this._y = y; }; The above technique is simple and clearly expresses intent. However, the use of an underscore prefix is just a coding convention and is not enforced by the language: there is nothing to prevent...
...an underscore prefix is just a coding convention and is not enforced by the language: there is nothing to prevent a user from directly accessing a property that is supposed to be private. Using Closures Another common technique, is to define private properties as variables and their getter and setter functions as a closure over these variables: function Point(_x, _y) { this.getX = function
() { return _x; }; this.setX = function (x) { _x = x; }; this.getY = function
() { return _y; }; this.setY = function (y) { _y = y; }; } Note that this technique requires member functions that need access to private properties to be defined on the object itself, instead of its prototype. This is slightly less efficient than using the u...
... 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 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 eventua...
...And 4 more matches
Working with Events - Archive of obsolete content
ion which will be called whenever the event occurs. The arguments that will be passed to the listener are specific to an event type and are documented with the event emitter. For example, the following add-on registers a listener with the tabs module to listen for the ready event, and logs a string to the console reporting the event: var tabs = require("sdk/tabs"); tabs.on("ready", function
() { console.log("tab loaded"); }); It is not possible to enumerate the set of listeners for a given event. The value of this in the listener function is the object that emitted the event. Listening to all events You can pass the wildcard "*" as the type argument. If you do this, the listener will be called for any event emitted by that object, and its argument will be the name of the event: ...
...he ready event above, or they may be objects returned by constructors. In the latter case the options object passed to the constructor typically defines properties whose names are the names of supported event types prefixed with "on": for example, "onOpen", "onReady" and so on. Then in the constructor you can assign a listener function to this property as an alternative to calling the object's on
() method. For example: the ActionButton object emits an event when the button is clicked. The following add-on creates a button and assigns a listener to the onClick property of the options object supplied to the button's constructor. The listener loads https://developer.mozilla.org/: require("sdk/ui/button/action").ActionButton({ id: "visit-mozilla", label: "Visit Mozilla", icon: "./icon-...
...ctionButton object emits an event when the button is clicked. The following add-on creates a button and assigns a listener to the onClick property of the options object supplied to the button's constructor. ...
...And 4 more matches
tabs - Archive of obsolete content
('ready', function(tab) { console.log('tab is loaded', tab.title, tab.url); }); Access tabs The module itself can be used as a list of all opened tabs across all windows. ...
...t: var tabs = require('sdk/tabs'); for (let tab of tabs) console.log(tab.title); You can also access individual tabs by index: var tabs = require('sdk/tabs'); tabs.on('ready', function
() { console.log('first: ' + tabs[0].title); console.log('last: ' + tabs[tabs.length-1].title); }); You can access the currently active tab: var tabs = require('sdk/tabs'); tabs.on('activate', function
() { console.log('active: ' + tabs.activeTab.url); }); Track a single tab Given a tab, you can register event listeners to be notified when the tab is closed, activated or deactivated, or when the page hosted by the tab is loaded or retrieved from the "back-forward cache": var tabs = require("sdk/tabs"); function onOpen(tab) { console.log(tab.url + " is open"); tab.on("pageshow", logShow);...
...'self.port.emit("html", document.body.innerHTML);' }); worker.port.on("html", function(message) { console.log(message) }) }); Note that tab.attach is tab-centric: if the user navigates to a new page in the same tab, then the worker and content scripts will be reattached to the new page. Attaching stylesheets New in Firefox 34. You can't attach style sheets to a tab using tab.attach
(), but from Firefox 34 onwards you can attach and detach them using the low-level stylesheet/style and content/mod APIs. Here's an add-on that uses a toggle button to attach a stylesheet to the active tab, and detach it again. The stylesheet is called "style.css" and is located in the add-on's "data" directory: var tabs = require("sdk/tabs"); var { attach, detach } = require('sdk/content/mod'); va...
...And 4 more matches
timers - Archive of obsolete content
econds. Any additional arguments are passed straight through to the callback. Parameters callback : function Function to be called. ms : integer Interval in milliseconds after which the function will be called. Returns integer : An ID that can later be used to undo this scheduling, if callback hasn't yet been called. ...
...llback : function Function to be called. ms : integer Interval in milliseconds after which the function will be called. Returns integer : An ID that can later be used to undo this scheduling, if callback hasn't yet been called. Example var { setTimeout } = require("sdk/timers"); setTimeout(function
() { // do something in 0 ms }, 0) clearTimeout(ID) Given an ID returned from setTimeout
(), prevents the callback with the ID from being called (if it hasn't yet been called). ...
... ID that can later be used to undo this scheduling, if callback hasn't yet been called. Example var { setTimeout } = require("sdk/timers"); setTimeout(function
() { // do something in 0 ms }, 0) clearTimeout(ID) Given an ID returned from setTimeout
(), prevents the callback with the ID from being called (if it hasn't yet been called). Parameters ID : integer An ID returned from setTimeout
(). Example var { setTimeout, clearTimeout } = require("sdk/timers"); var id = setTimeout(function
() { // do something in 1 sec }, 1000); // to stop/cancel this timeout clearTimeout(id); setInterval(callback, ms) Schedules callback to be called repeatedly every ms milliseconds. Any additional arguments are passed straight through to the callback. Parameters callback : function Function t...
...And 4 more matches
lang/functional - Archive of obsolete content
umber.times(2); // 20 myNumber.add(3); // 23 Parameters lambda : function The function to be wrapped and returned. Returns function : The wrapped lambda. defer(fn) Takes a function and returns a wrapped version of the function. Calling the wrapped version will call the original function during the next event loop. This is similar to calling setTimeout with no wait (i.e. setTimeout(function
() { ... }, 0)), except that the wrapped function may be reused and does not need to be repeated each time. This also enables you to use these functions as event listeners. let { defer } = require("sdk/lang/functional"); let fn = defer(function myEvent (event, value) { console.log(event + " : " + value); }); fn("click", "#home"); console.log("done"); // This will print 'done' before 'click : #h...
...event, value) { console.log(event + " : " + value); }); fn("click", "#home"); console.log("done"); // This will print 'done' before 'click : #home' since // we deferred the execution of the wrapped `myEvent` // function, making it non-blocking and executing on the // next event loop Parameters fn : function The function to be deferred. Returns function : The new, deferred function. ...
... params : Array Parameters to be passed into callee. self : mixed Object to be passed as the this context to callee. ...
...And 4 more matches
ui/toolbar - Archive of obsolete content
Showing and hiding toolbars By default, a toolbar is shown when it is created, although you can specify that a toolbar should be hidden initially by passing hidden:true as an option in its constructor. After that, though, you can't show or hide the toolbar programmatically. Toolbars get a close button at the right-hand side, and users can show or hide the toolbar using the Firefox "Vie...
...ding(e) { console.log("hiding: " + e.title); } Parameters event : string The name of the event to listen to. Toolbar supports the following events: attach, detach, show, and hide. listener : function The listener function. This may be passed arguments, depending on the particular event. removeListener(event, listener) Removes an event listener. ...
...toolbar.removeListener("show", showing); } function hiding(e) { console.log("hiding: " + e.title); toolbar.removeListener("hide", hiding); } Parameters event : string The event the listener is listening for. Toolbar supports the following events: attach, detach, show, and hide. listener : function The listener to remove. off(event, listener) This function is an alias for removeListener
(). Parameters event : string The event the listener is listening for. Toolbar supports the following events: attach, detach, show, and hide. listener : function The listener to remove. destroy
() Destroys the toolbar. After calling this function, the toolbar will no longer be visible and its menu item will no longer appear in the Firefox "Toolbars" menu. Calling this function also causes the ...
...And 4 more matches
console - Archive of obsolete content
then these messages appear in the command shell you used. If the add-on has been installed in Firefox, then the messages appear in the Browser Console. If you're developing your add-on using the Extension Auto-installer, then the add-on is installed in Firefox, meaning that messages will appear in the Browser Console. But see the discussion of logging levels: by default, messages logged using log
(), info
(), trace
(), or warn
() won't be logged in these situations. Console Methods All console methods except exception
() and trace
() accept one or more JavaScript objects as arguments and log them to the console. Depending on the console's underlying implementation and user interface, you may be able to examine the properties of non-primitive objects that are logged. console.debug(...) Depreca...
...n't be logged in these situations. Console Methods All console methods except exception
() and trace
() accept one or more JavaScript objects as arguments and log them to the console. Depending on the console's underlying implementation and user interface, you may be able to examine the properties of non-primitive objects that are logged. console.debug(...) Deprecated, you should use console.log
() instead. console.error(object[, object, ...]) Logs the arguments to the console, preceded by "error:" and the name of your add-on: console.error("This is an error message"); error: my-addon: This is an error message console.exception(exception) Logs the given exception instance as an error, outputting information about the exception's stack traceback if one is available. try { doThing...
... instead. console.error(object[, object, ...]) Logs the arguments to the console, preceded by "error:" and the name of your add-on: console.error("This is an error message"); error: my-addon: This is an error message console.exception(exception) Logs the given exception instance as an error, outputting information about the exception's stack traceback if one is available. try { doThing
(); } catch (e) { console.exception(e); } function UserException(message) { this.message = message; this.name = "UserException"; } function doThing
() { throw new UserException("Thing could not be done!"); } error: my-addon: An exception occurred. UserException: Thing could not be done! console.info(object[, object, ...]) A synonym for console.log
(). console.log(object[, object, ...
...And 4 more matches
Unit Testing - Archive of obsolete content
ng test code from cfx to jpm, see the guide to migrating from cfx, in particular the section on loading modules from test code. The SDK provides a framework to help create and run unit tests for your code. To demonstrate how it works we'll write some unit tests for a simple Base64 encoding module. A Simple Base64 Module In a web page, you can perform Base64 encoding and decoding using the btoa
() and atob
() functions. Unfortunately these functions are attached to the window object: since this object is not available in your main add-on code, atob
() and btoa
() aren't available either. So we'll create a base64 module to expose these functions from the platform (see Creating Reusable Modules). To begin with, create a new directory, navigate to it, and run jpm init. Now create a new file cal...
... the platform (see Creating Reusable Modules). To begin with, create a new directory, navigate to it, and run jpm init. ...
...rm (see Creating Reusable Modules). To begin with, create a new directory, navigate to it, and run jpm init. Now create a new file called "base64.js", and give it the following contents: const { atob, btoa } = require("resource://gre/modules/Services.jsm"); exports.atob = a => atob(a); exports.btoa = b => btoa(b); This code exports two functions, which just call the platform's btoa
() and atob
() functions. ...
...And 4 more matches
JavaScript timers - Archive of obsolete content
A block of JavaScript code is generally executed synchronously. But there are some JavaScript native functions (timers) which allow us to delay the execution of arbitrary instructions: setTimeout
() setInterval
() setImmediate
() requestAnimationFrame
() The setTimeout
() function is commonly used if you wish to have your function called once after the specified delay. The setInterval
() function is commonly used to set a delay for functions that are executed again and again, such as animations. ...
... which allow us to delay the execution of arbitrary instructions: setTimeout
() setInterval
() setImmediate
() requestAnimationFrame
() The setTimeout
() function is commonly used if you wish to have your function called once after the specified delay. The setInterval
() function is commonly used to set a delay for functions that are executed again and again, such as animations. The setImmediate
() function can be used instead of the setTimeout(fn, 0) method to execute heavy operations in IE. The requestAnimationFrame
() function tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame. ...
...y for functions that are executed again and again, such as animations. The setImmediate
() function can be used instead of the setTimeout(fn, 0) method to execute heavy operations in IE. The requestAnimationFrame
() function tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame. Documentation setTimeout
() Calls a function or executes a code snippet after specified delay. setInterval
() Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function. setImmediate
() Calls a function immediately after the browser has completed other operations, such as events and display updates. clearTimeout
() Clears the delay set by setTimeout
(). clearInterv...
...And 4 more matches
Jetpack Processes - Archive of obsolete content
ate with their parent chrome 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 ...
...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 the chrome process that was triggered by the message. registerReceiver(aMessageName, aReceiver) Similar to nsIJetpack.registerReceiver
(), this function registers a callback that is triggered when the chrome process sends a message with the given name. ...
... Array whose elements are the return values of each receiver in the chrome process that was triggered by the message. registerReceiver(aMessageName, aReceiver) Similar to nsIJetpack.registerReceiver
(), this function registers a callback that is triggered when the chrome process sends a message with the given name. unregisterReceiver(aMessageName, aReceiver) Similar to nsIJetpack.unregisterReceiver
(), this function unregisters a callback previously registered with registerReceiver
(). ...
...And 4 more matches
JavaScript Object Management - Archive of obsolete content
eral utility functions or properties that you want to use across all objects within the namespace. For instance, there are frequently used XPCOM services such as the Observer service that can be included as members in the namespace: /** * <Namespace> namespace. */ if (typeof <Namespace> == "undefined") { var <Namespace> = { /** * Initializes this object. ...
...PCOM services such as the Observer service that can be included as members in the namespace: /** * <Namespace> namespace. */ if (typeof <Namespace> == "undefined") { var <Namespace> = { /** * Initializes this object. */ init : function
() { this.obsService = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService); } }; <Namespace>.init
(); }; JS objects can also be treated as string-indexed arrays: // equivalent. <Namespace>.Hello = {}; <Namespace>["Hello"] = {}; // equivalent. <Namespace>.Hello.init
(); <Namespace>.Hello["init"]
(); This is very useful in cases where you have to set attributes or functions with dynamically generated names. It's one of the funky properties of JavaScript: all objects are nothing more th...
...r noticing the changes. /** * Controls the browser overlay for the Hello World extension. */ <Namespace>.BrowserOverlay = { /** * Initializes this object. */ init : function(aEvent) { this._stringBundle = document.getElementById("xulschoolhello-string-bundle"); // you can make changes to the window DOM here. } // more stuff }; window.addEventListener( "load", function
() { <Namespace>.BrowserOverlay.init
(); }, false); There are some things you can't (or shouldn't) do inside load handlers, such as closing the window being loaded, or opening new windows, alerts or dialogs. The window has to finish loading before it can do any of these things. They are bad UI practices anyway and you should avoid them. If you really need to do something like this anyway, one way...
...And 4 more matches
Java in Firefox Extensions - Archive of obsolete content
ead, although the new documentation for the LiveConnect reimplementation states that these globals will be deprecated (in the context of applets), "Firefox and the Java Plug-In will continue to support the global java/Packages keywords, in particular in the context of Firefox extensions."). These 2 objects let you make use of the standard JDK classes, e.g., var aJavaList = new java.util.LinkedList
(); If you want to load your own JARs, then you can create your own Java class loader. The following technique only works in JavaScript code linked from or contained in XUL files. If you wish to call Java code from within JavaScript code that implements some XPCOM components, at this time, you need a different technique (refer to the complete Java Firefox Extension). A good reason for calling Java...
...(this works in fi...
...(this works in firefox 3.x, for firefox 4.x use AddonManager.getAddonByID) var e...
...And 4 more matches
The life of an HTML HTTP request - Archive of obsolete content
the content type of the incoming data, so the DocumentLoader can find an nsIDocumentLoaderFactory for the "text/html" content type (in this case an nsLayoutDLF). This factory is then told to create a nsIContentViewer. The factory creates a ContentViewer. In most cases (including this) it also creates a nsIDocument (nsHTMLDocument) and binds it to the ContentViewer. The ContentViewer is then Embed
():ed into the ContentViewerContainer (the WebShell). (4) The document then creates a nsIParser for parsing the input stream. For HTML document this is an nsParser, which also implements nsIStreamListener. This StreamListener is returned to the DocumentLoader and connected to the nsIChannel of the request. (5) The Document (nsHTMLDocument) also creates a nsIContentSink (nsHTMLContentSink) and conn...
... parsed block it passes the parsed data as nsIParserNodes to the ContentSink unless the parser has been temporarily blocked, in wich case it waits until it gets unblocked before parsing the cached data it has receieved while being blocked. (6) The contentsink then builds up nsIContent nodes that describe the document. These content nodes are created by calling functions like NS_NewHTMLXxxxElement
(). These element nodes implement the nsIHTMLContent interface as well as their respective DOM interfaces. nsIContent::AppendChild
() is used to build the content tree but AppendChild takes a "aNotify" argument that marks if it should notify the document about the content model changes or not. This argument is always PR_FALSE when the content sink calls AppendChild. The content sink tells the documen...
...WillInterrup is called by the parser between every 8kb block of data (unless the parser is temporarily blocked). ...
...And 4 more matches
Install script template - Archive of obsolete content
f (err != 0) { // call initInstall again in case illegal characters in PLID err = initInstall(SOFTWARE_NAME, SOFTWARE_NAME, VERSION); if (err != 0) cancelInstall(err); } //addFiles to current browser block var pluginsFolder = getFolder("Plugins"); //Verify Disk Space if(verifyDiskSpace(pluginsFolder, PLUGIN_SIZE+COMPONENT_SIZE)) { // start installing plugin shared library resetError
(); // install the plugin shared library to the current browser's Plugin directory errBlock1 = addFile (PLID, VERSION, PLUGIN_FILE, pluginsFolder, null); if (errBlock1!=0) { logComment("Could NOT add " + PLUGIN_FILE + " to " + pluginsFolder + ":" + errBlock1); cancelInstall(errBlock1); } // start installing xpt file if this is a scriptable plugin // install to the plugins directory -...
... Mozilla 1.0 clients, the Components directory can be avoided for XPT files errBlock1 = addFile (PLID, VERSION, COMPONENT_FILE, pluginsFolder, null); if (errBlock1!=0) { logComment("Could NOT add " + COMPONENT_FILE + " to " + pluginsFolder + ":" + errBlock1); cancelInstall(errBlock1); } } else { logComment("Cancelling current browser install due to lack of space..."); cancellInstall
(); } // Secondary install block, which sets up plugins and xpt in another location in addition to the current browser errBlock2 = createSecondaryInstall
(); // performInstall block, in which error conditions from previous blocks are checked. // This block also invokes a function to write registry keys (PLID) and checks return from key writing // This block invokes refreshPlugins
() to ensure th...
... You can also simply call refreshPlugi...
...And 4 more matches
Accessing Files - Archive of obsolete content
Once one of these starting directories is determined, a file reference may be created relative to this. A common case is to write a file in the directory that holds the user's preferences. This is a convenient location where an extension might save a file it needs to use. This directory is referred to as the user's profile directory. To get a reference to a File object use nsIScriptableIO.getFile
(). ...
...In the example above the word 'Profile' is used, which means start from within the user's profile directory. ...
...d sample.txt located in the profile directory. var file = IO.getFile("Profile", "sample.txt"); The nsIScriptableIO object is a global object always available within an application or extension which provides a number of useful functions for dealing with files. One such method it provides is nsIScriptableIO.getFile
() which returns a new nsIFile object. The first argument to nsIScriptableIO.getFile
() is the starting directory from which to locate a file. In the example above the word 'Profile' is used, which means start from within the user's profile directory. The actual location of this directory will vary by user and system, so this is a convenient means to refer to a common directory without having to locate it yourself. For a full list of starting directories, see Starting Directories be...
...And 4 more matches
Writing to Files - Archive of obsolete content
n files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. To write to a file, an output stream is used. An output stream is an object which can be used to write bytes, strings and other values to a file. To create an output stream, use nsIScriptableIO.newOutputStream
(). This method has a number of options to specify text or binary writing, the character set, and whether to append to an existing file or create a new one. To create an input stream, first get a reference to a nsIFile, and then use nsIScriptableIO.newOutputStream
() to open a stream for writing to it. To learn more about file objects, see Files and Streams. try { var file = IO.getFile("Desktop", "...
...In this example, the operations are enclosed in a try-catch block in order to capture any errors that might occur during the process. ...
...eam for writing to it. To learn more about file objects, see Files and Streams. try { var file = IO.getFile("Desktop", "myinfo.txt"); var stream = IO.newOutputStream(file, "text"); } catch (ex) { alert(ex); } This example retrieves a file object on the desktop called 'myinfo.txt' using nsIScriptableIO.getFile
(). It doesn't matter whether the file exists or not. nsIScriptableIO.newOutputStream
() is called to create a new output stream, which will be used to write to the file. In this example, the operations are enclosed in a try-catch block in order to capture any errors that might occur during the process. See File Errors for a list of errors that might occur. The newOutputStream method takes two arguments in this example. The first argument is the file to write to, and the second is a ...
...And 4 more matches
Custom Tree Views - Archive of obsolete content
hich can be called whatever you want: //Moz 1.8 var treeView = { rowCount : 10000, getCellText : function(row,column){ if (column.id == "namecol") return "Row "+row; else return "February 18"; }, setTree: function(treebox){ this.treebox = treebox; }, isContainer: function(row){ return false; }, isSeparator: function(row){ return false; }, isSorted: function
(){ return false; }, getLevel: function(row){ return 0; }, getImageSrc: function(row,col){ return null; }, getRowProperties: function(row,props){}, getCellProperties: function(row,col,props){}, getColumnProperties: function(colid,col,props){} }; The functions in the example not described above do not need to perform any action, but they must be implemented as the tree calls the...
... not need to perform any action, but they must be implemented as the tree calls them to gather additional information. This example can be used for a tree with 10,000 rows. The contents of the cells in the first column will be set to the text 'Row X' where X is the row number. The contents of the cells in the second column will be set to 'February 18'. The if statement in the function getCellText
() compares the id property of the column argument to the text 'namecol'. This text 'namecol' corresponds to the id of the first treecol in the example above. This example is very simple of course -- in reality you would have more complex data in each cell. The final step is to associate the view object with the tree. The tree has a property view, which can be assigned to the view object declared a...
...ds to the id of the first treecol in the example above. This example is very simple of course -- in reality you would have more complex data in each cell. The final step is to associate the view object with the tree. The tree has a property view, which can be assigned to the view object declared above. We can assign a value to this property at any time to set or change the view. function setView
(){ document.getElementById('my-tree').view = treeView; } The following presents the example together. An inline script has been used here to simplify the example. Normally, you would put the script in an external script file. Example custom tree Source <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window title="Tree Example" id="tree-window" x...
...And 4 more matches
Writing JavaScript for XHTML - Archive of obsolete content
ave correctly in both application/xhtml+xml and text/html environments are sometimes known as 'polyglot' documents.) To test the following examples locally, use Firefox's extension switch. Just write an ordinary (X)HTML file and save it once as test.html and once as test.xhtml. Problem: Nothing Works After switching the MIME type suddenly no inline script works anymore. Even the plain old alert
() method is gone. The code looks something like this: <script type="text/javascript"> //<!-- window.alert("Hello World!"); //--> </script> Solution: The CDATA Trick This problem usually arises, when inline scripts are included in comments. This was common practice in HTML, to hide the scripts from browsers not capable of JS. In the age of XML comments are what they were intended: comm...
...indow.alert("Hello World!"); </script> This will work so long as your code doesn't contain characters which are "special" in XML, which usually means < and &. If your code contains either of these, you can work around this with CDATA sections: <script type="text/javascript"> <![CDATA[ // is the variable a non-negative integer less than 10? if (variable < 10 && variable >= 0) action
(); ]]> </script> Note that the CDATA section is only necessary because of the < in the code; otherwise you could have ignored it. A third solution is to use only external scripts, neatly sidestepping the special-character problem. Alternatively, the CDATA section can be couched within comments so as to be able to work in either application/xhtml+xml or text/html: <script type="text/javascrip...
...- (For styles, it is different) --> <style type="text/css"><!--/*--><![CDATA[/*><!--*/ ... /*]]>*/--></style> See this document for more on the issues related to application/xhtml+xml and text/html (at least as far as XHTML 1.* and HTML 4; HTML5 addresses many of these problems). ...
...And 4 more matches
Windows Media in Netscape - Archive of obsolete content
ectly instantiated, you will know that it is a version of Windows Media Player 7 and up, since the clsid used with the object element reflects the unique component in this version range. Scripting the Control Namespacing issues are the most important distinction between scripting the Windows Media control in IE and Netscape 7.1. In code deployed for IE, invocations of the sort Player.controls.play
(); are common, where Player is the id of the object element. In Netscape 7.1, plugins and ActiveX controls are not exposed to the global namespace, but rather as properties of the document object. Accessing properties and controls from the document object works well with IE also, and thus, in order to deploy cross-platform code, avoiding syntax that makes use of global namespace is important. Here,...
...loy cross-platform code, avoiding syntax that makes use of global namespace is important. ...
... important. Here, for example, is a code snippet that works equally well on both Netscape 7.1 and IE: <object id="Player" height="0" width="0" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"> <param name="autoStart" value="true"> </object> <input type="button" name="PlayMedia" value="Play" OnClick="StartMediaUp
()"> <input type="button" name="StopMedia" value="Stop" OnClick="ShutMediaDown
()"> <P>This example shows a minimally-functional player <script> <!-- function StartMediaUp
() { document.Player.URL = "preludesteel.wma"; document.Player.controls.play
(); } function ShutMediaDown
() { document.Player.controls.stop
(); } --> </script> More extensive examples of working cross-browser code can be found in the examples section at the end. Qualifying references with documen...
...And 4 more matches
Mobile touch controls - Game development
We can get the first touch (e.touches[0], our example is not multitouch-enabled), extract the pageX and pageY variables and set the player's ship position on the screen by subtracting the Canvas offset (distance from the Canvas and the edge of the screen) and half the player's width...
...he first touch (e.touches[0], our example is not multitouch-enabled), extract the pageX and pageY variables and set the player's ship position on the screen by subtracting the Canvas offset (distance from the Canvas and the edge of the screen) and half the player's width and height. To see if it's working correctly we can output the x and y positions using the output element. The preventDefault
() function is needed to prevent the browser from moving -- without it you'd have the default behaviour, and the Canvas would be dragged around the page, which would show the browser scroll bars and look messy. Touch events in Phaser We don't have to do this on our own; frameworks like Phaser offer systems for managing touch events for us -- see managing the touch events. Pointer theory A pointe...
... You can quickly get the coordinates of the most recently active pointer via the this.game.input.x and this.game.input.y variables. Input events Instead of using the pointers directly it is also possible to listen for this.game.input events, like onDown, onUp, onTap and onHold: this.game.input.onDown.add(itemTouched, this); function itemTouched(pointer) { // do something } The itemTouched
() function will be executed when the onDown event is dispatched by touching the screen. The pointer variable will contain the information about the pointer that activated the event. This approach uses the generally available this.game.input object, but you can also detect the actions on any game objects like sprites or buttons by using onInputOver, onInputOut, onInputDown, onInputUp, onDragStart, ...
...And 4 more matches
Build the brick field - Game development
nt; r++) { bricks[c][r] = { x: 0, y: 0 }; } } The code above will loop through the rows and columns and create the new bricks. NOTE that the brick objects will also be used for collision detection purposes later. Brick drawing logic Now let's create a function to loop through all the bricks in the array and draw them on the screen. ...
...ed for collision detection purposes later. Brick drawing logic Now let's create a function to loop through all the bricks in the array and draw them on the screen. Our code might look like this: function drawBricks
() { for(var c=0; c<brickColumnCount; c++) { for(var r=0; r<brickRowCount; r++) { bricks[c][r].x = 0; bricks[c][r].y = 0; ctx.beginPath
(); ctx.rect(0, 0, brickWidth, brickHeight); ctx.fillStyle = "#0095DD"; ctx.fill
(); ctx.closePath
(); } } } Again, we're looping through the rows and columns to set the x and y position of each brick, and we're also painting a brick on the Canvas -- size brickWidth x brickHeight -- with each loop iteration. The problem is that we're paintin...
...th + brickPadding, multiplied by the column number, c, plus the brickOffsetLeft; the logic for the brickY is identical except that it uses the values for row number, r, brickHeight, and brickOffsetTop. Now every single brick can be placed in its correct place row and column, with padding between each brick, drawn at an offset from the left and top canvas edges. ...
...And 4 more matches
Paddle and keyboard controls - Game development
s near the top of your code, beside your other variables: var paddleHeight = 10; var paddleWidth = 75; var paddleX = (canvas.width-paddleWidth) / 2; Here we're defining the height and width of the paddle and its starting point on the x axis for use in calculations further on down the code. Let's create a function that will draw the paddle on the screen. Add the following just below your drawBall
() function: function drawPaddle
() { ctx.beginPath
(); ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight); ctx.fillStyle = "#0095DD"; ctx.fill
(); ctx.closePath
(); } Allowing the user to control the paddle We can draw the paddle wherever we want, but it should respond to the user's actions. It's time to implement some keyboard controls. We will need the fol...
...s can be defined and initialized with boolean variables like in the example. Add these lines somewhere near the rest of your variables: var rightPressed = false; var leftPressed = false; The default value for both is false because at the beginning the control buttons are not pressed. To listen for key presses, we will set up two event listeners. ...
... not pressed. To listen for key presses, we will set up two event listeners. Add the following lines just above the setInterval
() line at the bottom of your JavaScript: document.addEventListener("keydown", keyDownHandler, false); document.addEventListener("keyup", keyUpHandler, false); When the keydown event is fired on any of the keys on your keyboard (when they are pressed), the keyDownHandler
() function will be executed. The same pattern is true for the second listener: keyup events will fire the keyUpHandler
() function (when the keys stop being pressed). ...
...And 4 more matches
Player paddle and controls - Game development
paddle From the framework point of view the paddle is very similar to the ball -- we need to add a variable to represent it, load the relevant image asset, and then do the magic. ...
...k point of view the paddle is very similar to the ball -- we need to add a variable to represent it, load the relevant image asset, and then do the magic. Loading the paddle First, add the paddle variable we will be using in our game, right after the ball variable: var paddle; Then, in the preload function, load the paddle image by adding the following new load.image
() call: function preload
() { // ... ...
...oad.image
() call: function preload
() { // ... game.load.image('ball', 'img/ball.png'); game.load.image('paddle', 'img/paddle.png'); } Adding the paddle graphic Just so we don't forget, at this point you should grab the paddle graphic from Github, and save it in your /img folder. Rendering the paddle, with physics Next up, we will init our paddle by adding the following add.sprite
() call inside the create
() function -- add it right at the bottom: paddle = game.add.sprite(game.world.width*0.5, game.world.height-5, 'paddle'); We can use the world.width and world.height values to position the paddle exactly where we want it: game.world.width*0.5 will be right in the middle of the screen. In our case the world is the same as the Canvas, but for other types of games, like side...
...And 4 more matches
JavaScript object basics - Learn web development
et a result similar to one of the below lines: [object Object] Object { } { } Congratulations, you've just created your first object. Job done! But this is an empty object, so we can't really do much with it. ...
... we can't really do much with it. Let's update the JavaScript object in our file to look like this: const person = { name: ['Bob', 'Smith'], age: 32, gender: 'male', interests: ['music', 'skiing'], bio: function
() { alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. ...
...[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.'); }, greeting: function
() { alert('Hi! I\'m ' + this.name[0] + '.'); } }; After saving and refreshing, try entering some of the following into the JavaScript console on your browser devtools: person.name person.name[0] person.age person.interests[1] person.bio
() person.greeting
() You have now got some data and functionality inside your object, and are now able to access them with some nice simple syntax! Note: If you are having trouble getting this to work, try comparing your code against our version -- see oojs-finished.html (also see it running live). The live version will give you a blank screen, but that's OK -- again, open your devtools and try t...
...And 4 more matches
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
ponent { @service('todo-data') todos; } Now we need to go back to our todo-data.js file and add some functionality that will allow us to return the number of incomplete todos (useful for showing how many are left), and clear the completed todos out of the list (which is what the "Clear completed" functionality needs). ...
... todo-data.js file and add some functionality that will allow us to return the number of incomplete todos (useful for showing how many are left), and clear the completed todos out of the list (which is what the "Clear completed" functionality needs). ...
...ful for showing how many are left), and clear the completed todos out of the list (which is what the "Clear completed" functionality needs). In todo-data.js, add the following getter underneath the existing all
() getter to define what the incomplete todos actually are: get incomplete
() { return this.todos.filter(todo => { return todo.isCompleted === false; }); } Using array.filter
(), we declare that "incomplete" todos are ones that have isCompleted equal to false. Next, add the following action underneath the existing add(text) action: @action clearCompleted
() { this.todos = this.incomplete; } This is rather nice for clearing the todos -- we just need to set the todos array to equal the list of incomplete todos. Finally, we need to make use of this new fu...
...And 4 more matches
Adding a new event
ts from keyboard or IME and also other text edit related events like querying focused content information. TouchEvents.h This header file should be used for defining input events from touch devices. MiscEvents.h If the new event class isn't proper any header files above, you should use this. Each event class should implement following methods manually. virtual InternalFooEvent* AsFooEvent
() MOZ_OVERRIDE This method should just return this. This method is used for retrieving sub class pointer avoiding to use static_cast. virtual WidgetEvent* Duplicate
() const MOZ_OVERRIDE This method should create a new instance with copying its members except widget. For copying the members, this should use AssignFooEventData
() with true for aCopyTargets. And also, mFlags should be just copied si...
...This method is basically used for duplicating an internal event class instance of a DOM event when the DOM event is stored by content. ...
...ntent, the class should be able to cross process boundary. In such cases, you may need to add new ParamTraits for the new event class in nsGUIEventIPC.h. Modify utility methods of WidgetEvent WidgetEvent class has some utility mehtods and all of them are implemented in WidgetEventImple.cpp. E.g., if your event shouldn't cause DOM event, you need to modify WidgetEvent::IsAllowedToDispatchDOMEvent
(). If your event should be fired on focused node, you need to modify WidgetEvent::IsTargetedAtFocusedContent
(). How to implement a DOM event class If you're in the case 3 (non-DOM events), you can skip this section. Create WebIDL of the event Write a DOM event definition with WebIDL. It should be created under dom/webidl/. See WebIDL bindings for the detail. If your new event shouldn't be cr...
...And 4 more matches
Debugging on Mac OS X
ad-index 1 --auto-continue true --one-shot true breakpoint command add -s python # This script that we run does not work if we try to use the global 'lldb' # object, since it is out of date at the time that the script runs (for # example, `lldb.target.executable.fullpath` is empty). Therefore we must # get the following objects from the 'frame' object. ...
...auto-continue true --one-shot true breakpoint command add -s python # This script that we run does not work if we try to use the global 'lldb' # object, since it is out of date at the time that the script runs (for # example, `lldb.target.executable.fullpath` is empty). Therefore we must # get the following objects from the 'frame' object. ...
...e true --one-shot true breakpoint command add -s python # This script that we run does not work if we try to use the global 'lldb' # object, since it is out of date at the time that the script runs (for # example, `lldb.target.executable.fullpath` is empty). Therefore we must # get the following objects from the 'frame' object. ...
...And 4 more matches
Error codes returned by Mozilla APIs
his error may occur when a relative path is supplied to a method that expects an absolute path and vice versa. NS_ERROR_FILE_UNRESOLVABLE_SYMLINK (0x80520002) An attempt was made to access a symbolic link to a file or directory which does not exist. NS_ERROR_FILE_EXECUTION_FAILED (0x80520003) An attempt to launch or execute a file failed because the file is not executable. nsIFile.isExecutable
() may be used to check if a file is executable. NS_ERROR_FILE_UNKNOWN_TYPE (0x80520004) An call was made to nsIFile.create
() with an invalid type. Only NORMAL_FILE_TYPE and DIRECTORY_TYPE are allowed. NS_ERROR_FILE_DESTINATION_NOT_DIR (0x80520005) An attempt was made to copy or move a file to a destination that is not a directory. NS_ERROR_FILE_TARGET_DOES_NOT_EXIST (0x80520006) An attempt wa...
..._FILE_TYPE and DIRECTORY_TYPE are allowed. NS_ERROR_FILE_DESTINATION_NOT_DIR (0x80520005) An attempt was made to copy or move a file to a destination that is not a directory. NS_ERROR_FILE_TARGET_DOES_NOT_EXIST (0x80520006) An attempt was made to reference a file that does not exist for copy/move, checking its size, etc. NS_ERROR_FILE_COPY_OR_MOVE_FAILED (0x80520007) A call to nsIFile.copyTo
() or nsIFile.moveTo
() failed. NS_ERROR_FILE_ALREADY_EXISTS (0x80520008) An attempt was made to create a file that already exists. NS_ERROR_FILE_INVALID_PATH (0x80520009) This error occurs when an attempt is made to use a path that isn't valid for the platform. NS_ERROR_FILE_DISK_FULL (0x8052000A) This error will occur if attempting to write to a disk that is full. NS_ERROR_FILE_CORRUPTED (0x...
...CTORY (0x8052000D) This error will occur if an attempt was made to perform an operation on a directory that is only valid for files. NS_ERROR_FILE_IS_LOCKED (0x8052000E) This error indicates that a file cannot be accessed because it is locked, typically because the file is already being used by another application. ...
...And 4 more matches
AddonListener
These notifications come in the form of calls to methods on the listener object. A listener only needs to implement the methods corresponding to the events it cares about; missing methods will not cause any problems. ...
... void onEnabled( in Addon addon, ) Parameters addon The Addon that has been enable...
...erationCancelled(in Addon addon) void onPropertyChanged(in Addon addon, in string properties[]) Methods onEnabling
() Called when an add-on is about to be enabled. void onEnabling( in Addon addon, in boolean needsRestart ) Parameters addon The Addon that is being enabled needsRestart True if an application restart is necessary for the change to take effect onEnabled
() Called when an add-on has been enabled. void onEnabled( in Addon addon, ) Parameters addon The Addon that has been enabled onDisabling
() Called when an add-on is about to be disabled. void onDisabling( in Addon addon, in boolean needsRestart ) Parameters addon The Addon that is being disabled needsRestart True if an application restart is necessary for the change to take e...
...And 4 more matches
InstallListener
Only called for add-ons that need to be downloaded. A listener may return false to c...
...all install) void onExternalInstall(in Addon install, in Addon existingAddon, in boolean needsRestart) Methods onNewInstall
() Called when a new instance of AddonInstall is created, primarily so UI can display some kind of progress for all installs. void onNewInstall( in AddonInstall install ) Parameters install The AddonInstall representing the install onDownloadStarted
() Called when downloading begins for an add-on install. Only called for add-ons that need to be downloaded. A listener may return false to cancel the download. void onDownloadStarted( in AddonInstall install ) Parameters install The AddonInstall representing the install onDownloadProgress
() Called as data is received during a download. Check the progress property for the amount of data ...
...Only called for add-ons that need to be downloaded. ...
...And 4 more matches
Add-on Repository
The Add-on Repository is responsible for finding available add-ons; it provides an interface for interacting with the addons.mozilla.org (AMO) site. Its API provides URLs that can be visited to browse the repository's add-ons. The API also offers two ways to search for and retrieve an array of Addon instances: retrieveRecommendedAddons
(), which returns a list of recommended add-ons, and searchAddons
(), which performs a search of the repository. These searches are asynchronous; results are passed to the provided SearchCallback object when the search is completed. Results passed to the SearchCallback object only include add-ons that are compatible with the current application and are not already installed or in the process of being installed. AddonRepository can only process one search at a ...
...and are not already installed or in the process of being installed. AddonRepository can only process one search at a time. A new search will immediately fail if the AddonRepository is already handling another search request. ...
...ry can only process one search at a time. A new search will immediately fail if the AddonRepository is already handling another search request. To import the Add-on Repository code module, use: Components.utils.import("resource://gre/modules/AddonRepository.jsm"); Method overview string getRecommendedURL
() string getSearchURL(in string searchTerms) void cancelSearch
() void retrieveRecommendedAddons(in integer maxResults, in SearchCallback callback) void searchAddons(in string searchTerms, in integer maxResults, in SearchCallback callback) Properties Property Type Description homepageURL string The URL of the repository site's home page. isSearching boolean true if a search is currently in p...
...And 4 more matches
Measuring performance using the PerfMeasurement.jsm code module
ment.CPU_CYCLES | PerfMeasurement.CACHE_REFERENCES | PerfMeasurement.CACHE_MISSES); This creates a new PerfMeasurement object, configured to record the specified event types. it doesn't, however, start to record data. ...
... PerfMeasurement.CACHE_REFERENCES | PerfMeasurement.CACHE_MISSES); This creates a new PerfMeasurement object, configured to record the specified event types. it doesn't, however, start to record data. ...
...CACHE_REFERENCES | PerfMeasurement.CACHE_MISSES); This creates a new PerfMeasurement object, configured to record the specified event types. it doesn't, however, start to record data. ...
...And 4 more matches
AsyncTestUtils extended framework
This is likely to happen when I/O is involved or a poten...
...lows you to write reasonably normal looking functions instead of having to chain together a whole bunch of functions and callbacks. Your test functions need to agree to the following contract: The Asynchronous Function Contract A function should yield false or return false when something asynchronous is going on. When the asynchronous operation is complete, something needs to call async_driver
(). Returning false tells the asynchronous driver that it should yield control up to the top-level. Calling async_driver
() lets it know to start up again. A function should yield true or return true when the asynchronous driver should continue executing without stopping. A function that does not return anything (or returns undefined) and is not a generator is treated like a function that returned ...
...so that they are immediately available for offline use. Creating / injecting messages All of these functions take synthetic set definitions. Look at the section on Synthetic Message Sets above to understand how to specify these. Create a single folder with messages in it let [folder, set1, set2, ...] = make_folder_with_sets([aSynSetDef1, aSynSetDef2, ...]); yield wait_for_message_injection
(); This creates a folder with an automatically generated name and adds one or more sets of messages to it. If multiple sets are specified, their messages will be interleaved. Example: let [folder, messageSet] = make_folder_with_sets([{count: 3}]); This creates a new folder with a set of three messages in it and saves the folder handle into 'folder' and the message set into 'messageSet'. Anothe...
...And 4 more matches
JSS FAQ
setCipherPolicy does not need to be called by a JSS app unless that app wants to limit itself to export-allowed cipher suites. My SSL connection is hanging on Windows? NSPR makes use of NT vs. Windows distinction and provides different NT and Windows builds. Many Netscape products, including NSS, have NT and Windows builds that are essentially the same ...
...illa/jss/provider/javax/crypto/JSSSecretKeyFactorySpi.java org/mozilla/jss/util/UTF8Converter.java org/mozilla/jss/util/Base64InputStream.java jss/samples/PQGGen.java jss/samples/pkcs12.java If I don't call setCipherPolicy, is the DOMESTIC policy used by default? Yes, domestic is the default because we call NSS_SetDomesticPolicy
() during CryptoManager.initialize
(). setCipherPolicy does not need to be called by a JSS app unless that app wants to limit itself to export-allowed cipher suites. My SSL connection is hanging on Windows? NSPR makes use of NT vs. Windows distinction and provides different NT and Windows builds. Many Netscape products, including NSS, have NT and Windows builds that are essentially the same except one difference: one is link...
...separate db's? No, you can only have one initialized instance of JSS for each database. Once JSS initialized, I can't get anymore instances with CertificateFactory.getInstance("X.509")? In version previous to JSS 3.1, JSS removes the default SUN provider on startup. Upgrade to the latest JSS, or, in the CryptoManager.InitializationValues object you pass to CryptoManager.initialize
(), set removeSunProivider=true. Is it possible to sign data in Java with JSS? What I am trying to do is write a Java applet that will access the Netscape certificate store, retrieve a X509 certificate and then sign some data. The best way to do this is with the PKCS #7 signedData type. Check out the javadoc. How do I convert org.mozilla.jss.crypto.X509Certificate to org.mozilla.jss.pkix.c...
...And 4 more matches
Pork Tools
Outparamdel Outparamdel converts functions to return via return value instead of an outparam. It takes a list of functions as input and rewrites the definition and call sites of those functions. <caption>Rewrites Performed</caption> nsresult Getter(nsIFoo **aResult) { *aResult = ... if (!*aResult) return NS_ERROR_FAILURE; return NS_OK; } nsIFoo* Getter
() { nsIFoo *result = NULL; // aResult below is kept for complicated cases // typically it wont be needed and can be removed nsIFoo **aResult = &result; // *aResult patterns are replaced with result result = ... if (result) return nsnull; // error returns are changed to nsnull //instead NS_OK, actual result is returned return result; } caller1 { //case 1 nsresult rv; rv = Getter(&var); N...
...e 1 nsresult rv; rv = Getter(&var); NS_ENSURE_SUCCESS(rv,rv); //case 2: naked call Getter(&var); //case 3: nsresult decl nsresult rv2 = Getter(&var); NS_ENSURE_SUCCESS(rv2,rv2); } caller1 { // case 1 // figure out that rv was only used for the rewritten // outparam call + NS_ENSURE_SUCCESS. ...
...E_SUCCESS(rv2,rv2); } caller1 { // case 1 // figure out that rv was only used for the rewritten // outparam call + NS_ENSURE_SUCCESS. ...
...And 4 more matches
Tutorial: Embedding Rhino
t, and print a result. Here's an example use of RunScript from a shell command line: $ java RunScript "Math.cos(Math.PI)" -1 $ java RunScript "function f(x){return 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...
... will be reported with the filename <cmd> and line number 1. Printing the result The code System.out.println(cx.toString(result)); prints the result of evaluating the script (contained in the variable result). result could be a string, JavaScript object, or other values. The toString method converts any JavaScript value to a string. Exiting the Context The code } finally { Context.exit
(); } exits the Context. This removes the association between the Context and the current thread and is an essential cleanup action. There should be a call to exit for every call to enter. To make sure that it is called even if an exception is thrown, it is put into the finally block corresponding to the try block starting after Context.enter
(). Expose Java APIs Using Java APIs No additional co...
...programs to interact with Java objects: $ java RunScript "java.lang.System.out.println(3)" 3.0 undefined Implementing interfaces Using Rhino, JavaScript objects can implement arbitrary Java interfaces. There's no Java code to write -- it's part of Rhino's LiveConnect implementation. For example, we can see how to implement java.lang.Runnable in a Rhino shell session: js> obj = { run: function
() { print("hi"); } } [object Object] js> obj.run
() hi js> r = new java.lang.Runnable(obj); [object Object] js> t = new java.lang.Thread(r) Thread[Thread-0,5,main] js> t.start
() hi Adding Java objects The next example is RunScript2. This is the same as RunScript, but with the addition of two extra lines of code: Object wrappedOut = Context.javaToJS(System.out, scope); ScriptableObject.putPropert...
...And 4 more matches
GCIntegration - SpiderMonkey Redirect 1
ing C++ objects that point to JS objects (unless it's just to their own wrapper--that's okay). It's safe for JS objects to point to other JS objects or to C++ objects. If there is a choice between storing a GC thing inside a C++ object or its JS corresponding representation, prefer to store it in the JS representation. Never store GC things in a JSObject's private pointer (i.e., via JS_SetPrivate
()). It's better to store them in reserved slots, since those will automatically be traced if the object is native. As much as possible, avoid trace hooks. If objects are structured as described above, there should be no need for them. This should be obvious by now, but never ever allow a GC thing point to a GC thing in a different compartment unless it's a wrapper that's registered in the cross-c...
...allocated or else reachable at the beginning, since objects can never go from unreachable to reachable. The end result is that all reachable objects are marked. A simple way to visualize the invariant is that, when an incremental GC starts, an "initial snapshot" of the heap is taken. The snapshot consists of all objects reachable from the roots via traced pointers--as if someone did a JS_DumpHeap
() at the beginning of the incremental GC. These objects, as well as any that were allocated since the GC started, are guaranteed to be marked. The write barrier guarantees the snapshot-at-the-beginning (SATB) invariant in a simple way. If, in the middle of an incremental GC, a pointer to an object X is destroyed (meaning overwritten or no longer traced for some reason), then X will be marked. In t...
...irst slice, and so they don't need a write barrier. Many other XPConnect pointers are also traced in this way. See XPCJSRuntime::TraceBlackJS and XPCJSRuntime::TraceGrayJS. If a pointer doesn't fit one of these categories, then it probably requires a write barrier. Before the pointer is modified (except initializing writes, which don't need a barrier), you should call IncrementalReferenceBarrier
() or IncrementalValueBarrier
(), passing it the value the pointer held before the write. There are several examples of this usage in XPConnect. The js::ObjectPtr class is intended to serve as a drop-in replacement for JSObject *. It has an assignment operator that automatically invokes a write barrier. So far, though, there hasn't been much use for this class--there aren't many places outside of Sp...
...And 4 more matches
How to build an XPCOM component in JavaScript
b, and may skip to the next section. If you don't find a suitable pre-existing interface, then you must define your own. XPCOM uses a dialect of IDL to define interfaces, called XPIDL. Here's the XPIDL definition for our HelloWorld component: HelloWorld.idl #include "nsISupports.idl" [scriptable, uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)] interface nsIHelloWorld : nsISupports { string hello
(); }; Note that you must generate a new UUID for each XPCOM component that you create. See Generating GUIDs for more information. Compiling the Typelib Your interface definition must be compiled into a binary format (XPT) in order to be registered and used within Mozilla applications. The compilation can be done using the Gecko SDK. You can learn how to get Mac, Linux, and Windows versions of t...
...COMUtils library: Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); then implement your interface the same way you did above, except with a few modifications so that XPCOMUtils can set it up properly: /*********************************************************** class definition ***********************************************************/ //class constructor function HelloWorld
() { // If you only need to access your component from JavaScript, uncomment the following line: //this.wrappedJSObject = this; } // class definition HelloWorld.prototype = { // properties required for XPCOM registration: classDescription: "My Hello World JavaScript XPCOM Component", classID: Components.ID("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractID: "@dietrich.gan...
.../ properties required for XPCOM registration: classDescription: "My Hello World JavaScript XPCOM Component", classID: Components.ID("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractID: "@dietrich.ganx4.com/helloworld;1", // [optional] custom factory (an object implementing nsIFactory). If not // provided, the default factory is used, which returns // |(new MyComponent
()).QueryInterface(iid)| in its createInstance
(). _xpcom_factory: { ... }, // [optional] an array of categories to register this component in. _xpcom_categories: [{ // Each object in the array specifies the parameters to pass to // nsICategoryManager.addCategoryEntry
(). 'true' is passed for both // aPersist and aReplace params. category: "some-category", // optional, def...
...And 4 more matches
Observer Notifications
p Note: An extension can no longer be registered to receive this notification in Firefox 4 and later. See XPCOM changes in Gecko 2.0 for details. Called when xpcom is initialized. Many things are not available for use at this point. To receive this notification you have to register with nsICategoryManager. The registered component is always retrieved as a singleton (That is getService
() will be used to instantiate it). app-startup Note: An extension can no longer be registered to receive this notification in Firefox 4 and later. See XPCOM changes in Gecko 2.0 for details. General event for application startup. To receive this notification you have to register with nsICategoryManager. Prepend "service," to the contract ID in the category registration to ...
...ate it). app-startup Note: An extension can no longer be registered to receive this notification in Firefox 4 and later. See XPCOM changes in Gecko 2.0 for details. General event for application startup. To receive this notification you have to register with nsICategoryManager. Prepend "service," to the contract ID in the category registration to be invoked via getService
() instead of createInstance
(). profile-do-change This is fired after the profile has been selected. You will not be able to access user preferences, bookmarks, or anything that uses the profile folder until this event occurs. This occurs after any profile migration. profile-after-change This is fired after all the observers for profile-do-change have been notified. ...
...sible nsIAppWindow Called just after a XUL window is made visible. browsing-context-discarded BrowsingContext Called while a BrowsingContext is being discarded. By this point, the BrowsingContext will have been detached from its BrowsingContextGroup and parent WindowContext, and removed from any BrowsingContext tree it was a part of. This is sent before BrowsingContext::Closed
() is updated. window-global-created WindowGlobalParent Called just after a WindowGlobalParent is initialized. A WindowGlobal actor has a lifetime matching that of an nsGlobalWindowInner. window-global-destroyed WindowGlobalParent Called just before a WindowGlobalParent is destroyed. By this point, the WGP being destroyed will have cleaned up most of its state, includin...
...And 4 more matches
nsACString (External)
ind RFind FindChar RFindChar AppendInt ToInteger Data Members No public members. Methods BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
... ToInteger Data Members No public members. Methods BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
... @param newSize Size the string to this length. Pass PR_UINT32_MAX to leave the length unchanged. ...
...And 4 more matches
nsAdoptingCString
char AssignLiteral(char Adopt Replace ReplaceASCII Append AppendASCII AppendLiteral(const char AppendLiteral(char operator+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Base Classes nsXPIDLCString Data Members No public members. ...
... @param aString is s...
... - source Parameters nsACString_internal& str nsACString_internal& operator=(const nsCSubstringTuple&) - source Parameters nsCSubstringTuple& tuple operator const char* char* operator const char*
() const - source operator[] char operator[](PRInt32) const - source Parameters PRInt32 i char operator[](PRUint32) const - source Parameters PRUint32 i get char* get
() const - source returns the null-terminated string Find PRInt32 Find(const nsCString&, PRBool, PRInt32, PRInt32) const - source Search for the given substring within this string. @param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...And 4 more matches
nsAdoptingString
st char AssignLiteral(char Adopt Replace ReplaceASCII Append AppendASCII AppendLiteral(const char AppendLiteral(char operator+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Base Classes nsXPIDLString Data Members No public members. ...
... @param...
...AString_internal& str nsAString_internal& operator=(const nsSubstringTuple&) - source Parameters nsSubstringTuple& tuple operator const PRUnichar* PRUnichar* operator const PRUnichar*
() const - source operator[] PRUnichar operator[](PRInt32) const - source Parameters PRInt32 i PRUnichar operator[](PRUint32) const - source Parameters PRUint32 i get PRUnichar* get
() const - source returns the null-terminated string Find PRInt32 Find(const nsCString&, PRBool, PRInt32, PRInt32) const - source Search for the given substring within this string. @param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...And 4 more matches
nsAutoString
(const char AssignLiteral(char Adopt Replace ReplaceASCII Append AppendASCII AppendLiteral(const char AppendLiteral(char operator+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Base Classes nsFixedString Data Members No public members. ...
... @param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...anIndex is the ofs where you want to write the given char @return TRUE if successful Parameters PRUnichar aChar PRUint32 aIndex StripChars void StripChars(const char*) - source These methods are used to remove all occurrences of the characters found in aSet from this string. @param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace
() - source This method strips whitespace throughout the string. ReplaceChar void ReplaceChar(PRUnichar, PRUnichar) - source swaps occurence of 1 string for another Parameters PRUnichar aOldChar PRUnichar aNewChar void ReplaceChar(const char*, PRUnichar) - source Parameters char* aSet PRUnichar aNewChar ReplaceSubstring void ReplaceSubstring(const nsString&, const nsString&) ...
...And 4 more matches
nsCAutoString
Append AppendASCII AppendLiteral(const char AppendLiteral(char operator+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Base Classes nsFixedCString Data Members No public members. ...
... @param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the ...
...e you want to write the given char @return TRUE if successful Parameters PRUnichar aChar PRUint32 aIndex StripChars void StripChars(const char*) - source These methods are used to remove all occurrences of the characters found in aSet from this string. @param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace
() - source This method strips whitespace throughout the string. ReplaceChar void ReplaceChar(char, char) - source swaps occurence of 1 string for another Parameters char aOldChar char aNewChar void ReplaceChar(const char*, char) - source Parameters char* aSet char aNewChar ReplaceSubstring void ReplaceSubstring(const nsCString&, const nsCString&) - ...
...And 4 more matches
nsCString
nst char AssignLiteral(char Adopt Replace ReplaceASCII Append AppendASCII AppendLiteral(const char AppendLiteral(char operator+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Base Classes nsACString_internal Data Members No public members. ...
... @param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...anIndex is the ofs where you want to write the given char @return TRUE if successful Parameters PRUnichar aChar PRUint32 aIndex StripChars void StripChars(const char*) - source These methods are used to remove all occurrences of the characters found in aSet from this string. @param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace
() - source This method strips whitespace throughout the string. ReplaceChar void ReplaceChar(char, char) - source swaps occurence of 1 string for another Parameters char aOldChar char aNewChar void ReplaceChar(const char*, char) - source Parameters char* aSet char aNewChar ReplaceSubstring void ReplaceSubstring(const nsCString&, const nsCString&) - source Parameters nsCSt...
...And 4 more matches
nsCStringContainer (External)
FindChar RFindChar AppendInt ToInteger Base Classes nsACString Data Members No public members. Methods BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
... Base Classes nsACString Data Members No public members. Methods BeginReading PRUint32 BeginReading(const char**, const char**) const - source Returns the length, beginning, and end of a string in one operation. ...
... @param newSize Size the string to this length. Pass PR_UINT32_MAX to leave the length unchanged. ...
...And 4 more matches
nsDependentCString
nsDependentCString(const nsCString_internal&, PRUint32) Constructs an nsDependentString from an existing flat string. Parameters nsCString_internal& str The existing flat string. PRUint32 startPos The position within the existing string at which the dependent string should start. This is similar to using Substring(str, startPos), except that the resulting string is flat. void nsDependentCString
() - source Constructs an nsDependentString to be rebound later. nsDependentCString(const nsACString_internal&) - source Obsolete in Gecko 9. This constructor should not be used. Parameters nsACString_internal& str AssertValid void AssertValid
() - source verify restrictions Rebind void Rebind(const char*) - source allow this class to be bound to a different string... Parameters char...
... @param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...anIndex is the ofs where you want to write the given char @return TRUE if successful Parameters PRUnichar aChar PRUint32 aIndex StripChars void StripChars(const char*) - source These methods are used to remove all occurrences of the characters found in aSet from this string. @param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace
() - source This method strips whitespace throughout the string. ReplaceChar void ReplaceChar(char, char) - source swaps occurence of 1 string for another Parameters char aOldChar char aNewChar void ReplaceChar(const char*, char) - source Parameters char* aSet char aNewChar ReplaceSubstring void ReplaceSubstring(const nsCString&, const nsCString&) - source Parameters nsCSt...
...And 4 more matches
nsString
const char AssignLiteral(char Adopt Replace ReplaceASCII Append AppendASCII AppendLiteral(const char AppendLiteral(char operator+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Base Classes nsAString_internal Data Members No public members. ...
... @param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...anIndex is the ofs where you want to write the given char @return TRUE if successful Parameters PRUnichar aChar PRUint32 aIndex StripChars void StripChars(const char*) - source These methods are used to remove all occurrences of the characters found in aSet from this string. @param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace
() - source This method strips whitespace throughout the string. ReplaceChar void ReplaceChar(PRUnichar, PRUnichar) - source swaps occurence of 1 string for another Parameters PRUnichar aOldChar PRUnichar aNewChar void ReplaceChar(const char*, PRUnichar) - source Parameters char* aSet PRUnichar aNewChar ReplaceSubstring void ReplaceSubstring(const nsString&, const nsString&) ...
...And 4 more matches
nsStringContainer (External)
Char AppendInt ToInteger Base Classes nsAString Data Members No public members. Methods BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
...Members No public members. Methods BeginReading PRUint32 BeginReading(const PRUnichar**, const PRUnichar**) const - source Returns the length, beginning, and end of a string in one operation. ...
... @param newSize Size the string to this length. Pass PR_UINT32_MAX to leave the length unchanged. @return The new length of the string, or 0 if resizing failed. ...
...And 4 more matches
nsXPIDLCString
al(const char AssignLiteral(char Adopt Replace ReplaceASCII Append AppendASCII AppendLiteral(const char AppendLiteral(char operator+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Base Classes nsCString Data Members No public members. ...
... operator+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Base Classes nsCString Data Members No public members. ...
... @param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...And 4 more matches
nsXPIDLString
eral(const char AssignLiteral(char Adopt Replace ReplaceASCII Append AppendASCII AppendLiteral(const char AppendLiteral(char operator+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Base Classes nsString Data Members No public members. ...
...or+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Base Classes nsString Data Members No public members. ...
... @param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...And 4 more matches
IAccessibleHyperlink
st changed in Gecko 1.9 (Firefox 3) This interface represents a hyperlink associated with a single substring of text or single non-text object. Non-text objects can have either a single link or a collection of links such as when the non-text object is an image map. Linked objects and anchors are implementation dependent. This interface is derived from IAccessibleAction. IAccessibleAction.nActions
() is one greater than the maximum value for the indices used with the methods of this interface. Furthermore, the object that implements this interface has to be connected implicitly or explicitly with an object that implements IAccessibleText. startIndex
() and endIndex
() are indices with respect to the text exposed by IAccessibleText. This interface provides access to a single object which can hav...
...h as "smart tags" which are objects, typically strings, which have multiple actions such as "Activate URI", "Bookmark URI", end so on. An interesting use case is an image map where each area is associated with multiple actions, for example an image map of smart tags. In this case you would have to implement two levels of accessible hyperlinks. The first level hyperlinks would only implement anchor
() and anchorTarget
(). The anchors would all reference the image object. The anchorTargets would reference the second level accessible hyperlink objects. None of the IAccessibleAction methods would be implemented on the first level hyperlink objects. The second level hyperlink objects would implement the IAccessibleAction methods. Their anchors would also reference the image object and their anchorT...
...s suggested that implementations should not rely on the inheritance. Method overview [propget] HRESULT anchor([in] long index, [out] VARIANT anchor ); [propget] HRESULT anchorTarget([in] long index, [out] VARIANT anchorTarget ); [propget] HRESULT endIndex([out] long index ); [propget] HRESULT startIndex([out] long index ); [propget] HRESULT valid([out] boolean valid ); Methods anchor
() Returns an object that represents the link anchor, as appropriate for the link at the specified index. [propget] HRESULT anchor( [in] long index, [out] VARIANT anchor ); Parameters index A 0 based index identifies the anchor when, as in the case of an image map, there is more than one link represented by this object. The valid maximal index is indicated by IAccessibleAction.nActions
(). anch...
...And 4 more matches
mozIAsyncFavicons
toolkit/components/places/mozIAsyncFavicons.idlScriptable Interface for accessing the favicon service asynchronously. 1.0 66 Introduced Gecko 6.0 Inherits from: nsISupports Last changed in Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8) nsIFaviconService handles this interface, so you do not need to directly create a new service. Simply QueryInterface
() the nsIFaviconService to this interface. As an alternative, you can just use PlacesUtils.favicons from JavaScript. Method overview void getFaviconURLForPage(in nsIURI aPageURI, in nsIFaviconDataCallback aCallback); void getFaviconDataForPage(in nsIURI aPageURI, in nsIFaviconDataCallback aCallback); void setAndFetchFaviconForPage(in nsIURI aPageURI, ...
...void getFaviconURLForPage( in nsIURI aPageURI, in nsIFaviconDataCallback aCallback ); Parameters aPageURI URI of the page whose favicon's URL we're looking up. aCallback Once we have found the favicon's URL, we invoke this callback. Note that the callback's aDataLen will be 0, aData will be null, and aMimeType w...
...e( in nsIURI aPageURI, in nsIFaviconDataCallback aCallback ); Parameters aPageURI URI of the page whose favicon's URL we're looking up. aCallback Once we have found the favicon's URL, we invoke this callback. Note that the callback's aDataLen will be 0, aData will be null, and aMimeType will be empty -- only aURI will be non-zero/null/empty. getFaviconDataForPage
() Retrieves the favicon URI and data associated to the given page, if any. void getFaviconURLForPage( in nsIURI aPageURI, in nsIFaviconDataCallback aCallback ); Parameters aPageURI URI of the page whose favicon URI and data we're looking up. aCallback This callback is always invoked to notify the result of the lookup. The aURI parameter will be the favicon URI, or ...
...And 4 more matches
mozIPersonalDictionary
r personalDictionary = Components.classes["@mozilla.org/spellchecker/personaldictionary;1"] .getService(Components.interfaces.mozIPersonalDictionary); Method overview void addCorrection(in wstring word,in wstring correction, in wstring lang); void addWord(in wstring word, in wstring lang); boolean check(in wstring word, in wstring lang); void endSession
(); void getCorrection(in wstring word, [array, size_is(count)] out wstring words, out PRUint32 count); void ignoreWord(in wstring word); void load
(); void removeCorrection(in wstring word,in wstring correction, in wstring lang); void removeWord(in wstring word, in wstring lang); void save
(); Attributes Attribute Type Description wordList nsIStringEnumerator Get the (lexicographi...
...out wstring words, out PRUint32 count); void ignoreWord(in wstring word); void load
(); void removeCorrection(in wstring word,in wstring correction, in wstring lang); void removeWord(in wstring word, in wstring lang); void save
(); Attributes Attribute Type Description wordList nsIStringEnumerator Get the (lexicographically sorted) list of words. Read only. Methods addCorrection
() Adds a misspelling to the list of corrections. Note that this method is not currently implemented. void addCorrection( in wstring word, in wstring correction, in wstring lang ); Parameters word The incorrect spelling of the word to add to the list of corrections. correction The correct spelling of the word. lang The language of the word. addWord
() Add a word to the personal dictionary. ...
...ameters word The incorrect spelling of the word to add to the list of corrections. correction The correct spelling of the word. lang The language of the word. addWord
() Add a word to the personal dictionary. void addWord( in wstring word, in wstring lang ); Parameters word The word to add to the dictionary. lang The language of the word. Note that this parameter is currently unused. check
() Checks a Unicode string. boolean check( in wstring word, in wstring lang ); Parameters word The word to check. lang The language of the word. Note that this parameter is currently ignored. ...
...And 4 more matches
mozIStorageFunction
This is an interface that must be implemented by consumers. It allows consumers to add functions that are available to SQL queries and triggers. There are a number of already defined functions provided by SQLite. Objects implementing this interface can be registered with mozIStorageConnection.createFunction
(). storage/public/mozIStorageFunction.idlScriptable Please add a summary to this article. ...
...te. Objects implementing this interface can be registered with mozIStorageConnection.createFunction
(). storage/public/mozIStorageFunction.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9.1.4 (Firefox 3.5.4) Inherits from: nsISupports Method overview nsIVariant onFunctionCall(in mozIStorageValueArray aFunctionArguments); Methods onFunctionCall
() The implementation of the function. This is called by the database engine when the function registered with mozIStorageConnection.createFunction
() is used in an executing SQL statement or trigger. Note This callback is executed on the thread that the statement or trigger is executing on. ...
...Likewise, if you execute SQL on a different thread, this callback will be executed on that thread. ...
...And 4 more matches
nsIAutoCompleteInput
toolkit/components/autocomplete/public/nsIAutoCompleteInput.idlScriptable This interface monitors the input in a text field and displays an autocomplete panel at the appropriate time. ...
...components/autocomplete/public/nsIAutoCompleteInput.idlScriptable This interface monitors the input in a text field and displays an autocomplete panel at the appropriate time. ...
...pleteInput.idlScriptable This interface monitors the input in a text field and displays an autocomplete panel at the appropriate time. ...
...And 4 more matches
nsIChannel
netwerk/base/nsIChannel.idlScriptable This interface allows clients to construct 'GET' requests for specific protocols, and manage them in a uniform way. Inherits from: nsIRequest Last changed in Gecko 19.0 (Firefox 19.0 / Thunderbird 19.0 / SeaMonkey 2.16) Once a channel is created (via nsIIOService.newChannel
()), parameters for that request may be set by using the channel attributes, or by calling QueryInterface
() to retrieve a subclass of nsIChannel for protocol-specific parameters. Then, the URI can be fetched by calling open
() or asyncOpen
(). After a request has been completed, the channel is still valid for accessing protocol-specific results. For example, QueryInterfacing to nsIHttpChannel allows response headers to be retrieved for the corresponding http transaction. ...
...Interfacing to nsIHttpChannel allows response headers to be retrieved for the corresponding http transaction. This interface must be used only from the XPCOM main thread. Implemented by netwerk/base/src/nsBaseChannel.cpp and netwerk/protocol/http/src/nsHttpChannel.cpp. Method overview void asyncOpen(in nsIStreamListener aListener, in nsISupports aContext); nsIInputStream open
(); Attributes Attribute Type Description contentCharset ACString The character set of the channel's content if available and if applicable. This attribute only applies to textual data. Setting contentCharset before the channel has been opened provides a hint to the channel on what the charset should be. The behavior is similar to contentType. The ...
...rong document type stored on a server and so on.), and the caller most likely wants to verify with the actual data. Setting contentType before the channel has been opened provides a hint to the channel as to what the MIME type is. The channel may ignore this hint in deciding on the actual MIME type that it will report. Setting contentType after onStartRequest has been fired or after open
() is called will override the type determined by the channel. Setting contentType between the time that asyncOpen
() is called and the time when onStartRequest is fired has undefined behavior at this time. The value of the contentType attribute is a lowercase string. A value assigned to this attribute will be parsed and normalized as follows: Any parameters (delimited with a ';'...
...And 4 more matches
nsIComponentManager
A "bootstrapped" chrome manifest supports some of the instructions allowed in a regular chrome manifest, see the Chrome Registration documentation for details. This method was introduced in Gecko 8 to let bootstrapped add-ons provide content at chrome:// URIs. Until Gecko 10 you had to call this method manuall...
...nifest file from the specified directory or XPI file. A "bootstrapped" chrome manifest supports some of the instructions allowed in a regular chrome manifest, see the Chrome Registration documentation for details. This method was introduced in Gecko 8 to let bootstrapped add-ons provide content at chrome:// URIs. Until Gecko 10 you had to call this method manually from within the add-on's startup
() method (with a matching removeBootstrappedManifestLocation
() call in the add-on's shutdown
() method). If you're targeting Gecko 10 or higher there should be no need to call this method, since the bootstrapped add-on's chrome.manifest is loaded automatically now. void addBootstrappedManifestLocation( in interface nsILocalFile aLocation ); Parameters aLocation The directory or XPI from wh...
...Unlike getService, this returns a new instance each time it is called. (See also nsIFactory.createInstance.) void createInstance( in nsCIDRef aClass, in nsISupports aDelegate, in nsIIDRef aIID, [iid_is(aIID),retval] out nsQIResult result ); Parameters aClass The ClassID of the object instance that is being requested. ...
...And 4 more matches
nsIConsoleService
Obsolete since Gecko 19 (Firefox 19 / Thunderbird 19 / SeaMonkey 2.16)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. void getMessageArray( ...
...ssageArray([optional] out uint32_t count, [retval, array, size_is(count)] out nsIConsoleMessage messages); void logMessage(in nsIConsoleMessage message); void logStringMessage(in wstring message); void registerListener(in nsIConsoleListener listener); void reset
(); void unregisterListener(in nsIConsoleListener listener); Methods getMessageArray
() To obtain an array of all logged messages. Obsolete since Gecko 19 (Firefox 19 / Thunderbird 19 / SeaMonkey 2.16)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. void getMessageArray( [array, size_is(count)] out nsIConsoleMessage messages, out PRUint32 count ); Parameters messa...
... out PRUint32 count, [retval, array, size_is(count)] out nsIConsoleMessage messages ); Parameters count The number of messages in the array. If no messages are logged, this function will return a count of 0, but allocating a placeholder word for messages, showing as a 0-length array when called from the script. Note: See the code samples below for how to call getMessageArray. logMessage
() void logMessage( in nsIConsoleMessage message ); Parameters message The nsIConsoleMessage to log. logStringMessage
() A convenient method for logging simple messages. void logStringMessage( in wstring message ); Parameters message The string to log. registerListener
() Registers a listener, to notify when an error is logged. Note: To guard against stack overflows from liste...
...And 4 more matches
nsIControllers
stance, use: var controllers = Components.classes["@mozilla.org/xul/xul-controllers;1"] .createInstance(Components.interfaces.nsIControllers); Method overview void appendController(in nsIController controller); nsIController getControllerAt(in unsigned long index); nsIController getControllerById(in unsigned long controllerID); unsigned long getControllerCount
(); nsIController getControllerForCommand(in string command); unsigned long getControllerId(in nsIController controller); void insertControllerAt(in unsigned long index, in nsIController controller); void removeController(in nsIController controller); nsIController removeControllerAt(in unsigned long index); Attributes Attribute Type Description commandDispatcher nsIDOMXULCommandDi...
...nsIController getControllerAt( in unsigned long index ); Parameters index The position of the wanted co...
...signed long index); Attributes Attribute Type Description commandDispatcher nsIDOMXULCommandDispatcher Obsolete since Gecko 1.9 Methods appendController
() Adds a controller to the end of the list. void appendController( in nsIController controller ); Parameters controller A controller to be added to the list of controllers. Exceptions thrown NS_ERROR_OUT_OF_MEMORY getControllerAt
() Returns the controller instance at the given position. nsIController getControllerAt( in unsigned long index ); Parameters index The position of the wanted controller. Return value The controller at the given position. Exceptions thrown NS_ERROR_FAILURE The given index is out of range. getControllerById
() Returns a controller given by its order, rather than position, of insertion. nsIContr...
...And 4 more matches
nsICryptoHMAC
netwerk/base/public/nsICryptoHMAC.idlScriptable This interface provides HMAC signature algorithms. 1.0 66 Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) Method overview ACString finish(in PRBool aASCII); void init(in unsigned long aAlgorithm, in nsIKeyObject aKeyObject); void reset
(); void update([const, array, size_is(aLen)] in octet aData, in unsigned long aLen); void updateFromStream(in nsIInputStream aStream, in unsigned long aLen); Constants Hashing Algorithms. These values are to be used by the init
() method to indicate which hashing function to use. These values map onto the values defined in mozilla/security/nss/lib/softoken/pkcs11t.h and are switched to CKM_*_H...
...1t.h and are switched to CKM_*_HMAC constant. Constant Value Description MD2 1 Message Digest Algorithm 2 MD5 2 Message-Digest algorithm 5 SHA1 3 Secure Hash Algorithm 1 SHA256 4 Secure Hash Algorithm 256 SHA384 5 Secure Hash Algorithm 384 SHA512 6 Secure Hash Algorithm 512 Methods finish
() Completes this HMAC object and produces the actual HMAC diegest data. Note: This method may be called any time after init
() is called. This call resets the object to its pre-init state. ACString finish( in PRBool aASCII ); Parameters aASCII If true then the returned value is a base-64 encoded string. if false, then the returned value is binary data. Return value A hash of the data th...
...is call resets the object to its pre-init state. ACString finish( in PRBool aASCII ); Parameters aASCII If true then the returned value is a base-64 encoded string. if false, then the returned value is binary data. Return value A hash of the data that was read by this object. This can be either binary data or base 64 encoded. Exceptions thrown NS_ERROR_NOT_INITIALIZED If init
() has not been called. init
() Initialize the hashing object. This method may be called multiple times with different algorithm types. Warning: This approach is not FIPS compliant. Note: This method must be called before any other method on this interface is called. void init( in unsigned long aAlgorithm, in nsIKeyObject aKeyObject ); Parameters aAlgorithm The algorithm type to be u...
...And 4 more matches
nsIDBChangeListener
void onHdrFlagsChanged(in nsIMsgDBHdr aHdrChanged, in unsigned long aOldFlags, in unsigned long aNewFlags, in nsIDBChangeListener aInstigator); Parameters aHdrChanged The nsIMsgDBHdr of the message that changed. aOldFlags The original flags on the message. Can be used to figure...
...ags The original flags on the message. Can be used to figure out what changed. Flags are defined in nsMsgMessageFlags. aNewFlags The new flags on the message. Can be used to figure out what changed. Flags are defined in nsMsgMessageFlags. aInstigator The caller who changed the header. This can be used to filter out events that you yourself started. aInstigator may also be null. onHdrDeleted
() Called when a header is deleted from the database. void onHdrDeleted(in nsIMsgDBHdr aHdrChanged, in nsMsgKey aParentKey, in long aFlags, in nsIDBChangeListener aInstigator); Parameters aHdrChanged The nsIMsgDBHdr of the message that was removed. aParentKey The key of the parent folder for deleted header. The typedef of nsMsgKey i...
... The nsIMsgDBHdr of the message that was removed. aParentKey The key of the parent folder for deleted header. The typedef of nsMsgKey is given in MailNewsTypes2.idl. aFlags The flags on the message. Flags are defined in nsMsgMessageFlags. aInstigator The caller who deleted the header. This can be used to filter out events that you yourself started. aInstigator may also be null. onHdrAdded
() Called when a header is added to the database. void onHdrAdded(in nsIMsgDBHdr aHdrChanged, in nsMsgKey aParentKey, in long aFlags, in nsIDBChangeListener aInstigator); Parameters aHdrChanged The nsIMsgDBHdr of the message that was added. aParentKey The key of the parent folder for new header. The typedef of nsMsgKey is given in MailNew...
...And 4 more matches
nsIDOMParser
When you create a DOMParser from a privileged script, you can pass parameters to the constructor, more on that below. ...
...xtensions--not to Web content.) To create a document, the parser needs to specify a principal (see Security check basics), a base URI (see document.baseURIObject), and a documentURI. These values are automatically determined as defined below, but if you work with DOMParser from privileged code, you can override the defaults by providing arguments to the DOMParser constructor or calling parser.init
(). ...
...u work with DOMParser from privileged code, you can override the defaults by providing arguments to the DOMParser constructor or calling parser.init
(). Usually you don't need to do that. If you come across a situation when these matter, feel free to ask questions in mozilla.dev.tech.dom and update this documentation to mention these cases. When a DOMParser is instantiated by calling new DOMParser
(), it inherits the calling code's principal (except that for chrome callers the principal is set to the null principal) and the documentURI and baseURI of the window the constructor came from. If the caller has UniversalXPConnect privileges, it can pass parameters to new DOMParser
(). If fewer than three parameters are passed, the remaining parameters will default to null. The first parameter is th...
...And 4 more matches
nsIDOMXULElement
dom/interfaces/xul/nsIDOMXULElement.idlScriptable Represents a XUL element within the DOM. 66 Introduced Gecko 1.0 Inherits from: nsIDOMElement Last changed in Gecko 1.9 (Firefox 3) Method overview void blur
(); void click
(); void doCommand
(); void focus
(); nsIDOMNodeList getElementsByAttribute(in DOMString name, in DOMString value); nsIDOMNodeList getElementsByAttributeNS(in DOMString namespaceURI, in DOMString name, in DOMString value); Attributes Attribute Type Description align DOMString Gets/sets the value of the element's align attribute. allowEvents boolean true if the element's allowevents attribute is the string "true", otherwise false. Removes the attribute if you set it to false. boxObject nsIBoxObject Read only. Gets or cr...
...t that may be used to read or write individual CSS style properties for the element. tooltip DOMString Gets/sets the value of the element's tooltip attribute. tooltipText DOMString Gets/sets the value of the element's tooltiptext attribute. top DOMString Gets/sets the value of the element's top attribute. width DOMString Gets/sets the value of the element's width attribute. ...
...e properties for the element. tooltip DOMString Gets/sets the value of the element's tooltip attribute. tooltipText DOMString Gets/sets the value of the element's tooltiptext attribute. top DOMString Gets/sets the value of the element's top attribute. width DOMString Gets/sets the value of the element's width attribute. Methods blur
() Attempts to remove focus from the element. void blur
(); Parameters None. ...
...And 4 more matches
nsIEditorMailSupport
editor/idl/nsIEditorMailSupport.idlScriptable Provides simple editing actions for the Thunderbird mail editor. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview nsISupportsArray getEmbeddedObjects
(); nsIDOMNode insertAsCitedQuotation(in AString aQuotedText, in AString aCitation, in boolean aInsertHTML); nsIDOMNode insertAsQuotation(in AString aQuotedText); void insertTextWithQuotations(in DOMString aStringToInsert); void pasteAsCitedQuotation(in AString aCitation, in long aSelectionType); void pasteAsQuotation(in long aSelectionType); void rewrap(in boolean aRespectNewlines); void stripCites
(); Methods getEmbeddedObjects
() Get a list of IMG and OBJECT tags in the current document. nsISupportsArray getEmbeddedObjects
(); Parameters None. ...
... long aSelectionType); void pasteAsQuotation(in long aSelectionType); void rewrap(in boolean aRespectNewlines); void stripCites
(); Methods getEmbeddedObjects
() Get a list of IMG and OBJECT tags in the current document. nsISupportsArray getEmbeddedObjects
(); Parameters None. Return value An nsISupportsArray containing the IMG and OBJECT tags of the current document. insertAsCitedQuotation
() Insert a string as quoted text (whose representation is dependent on the editor type), replacing the selected text (if any), including, if possible, a "cite" attribute. nsIDOMNode insertAsCitedQuotation( in AString aQuotedText, in AString aCitation, in boolean aInsertHTML ); Parameters aQuotedText The actual text to be quoted. aCitation The "mid" URL of the source message. aInsertHTML Ins...
...ing the selected text (if any), including, if possible, a "cite" attribute. nsIDOMNode insertAsCitedQuotation( in AString aQuotedText, in AString aCitation, in boolean aInsertHTML ); Parameters aQuotedText The actual text to be quoted. aCitation The "mid" URL of the source message. aInsertHTML Insert as html? (vs plaintext) Return value The nsIDOMNode which was inserted. ...
...And 4 more matches
nsIEffectiveTLDService
e this interface for determining whether a given string "is a domain name". That question is unanswerable with 100% accuracy using the PSL, because what is a domain name is a property of the DNS, which is different for different people. Is "mail.intranet" actually a domain name? Depends who you ask - for some people it is, others not. Is "pretty.flowers" a domain name, according to getPublicSuffix
()? Depends on the age of the copy of the PSL you are working with. The TLD space is currently expanding at a fairly great rate, and the copy of the PSL Firefox has may not be totally up to date (because it's not dynamically updated data). Method overview ACString getBaseDomain(in nsIURI aURI, [optional] in PRUint32 aAdditionalParts); ACString getBaseDomainFromHost(in AUTF8String...
...ecause it's not dynamically updated data). Method overview ACString getBaseDomain(in nsIURI aURI, [optional] in PRUint32 aAdditionalParts); ACString getBaseDomainFromHost(in AUTF8String aHost, [optional] in PRUint32 aAdditionalParts); ACString getPublicSuffix(in nsIURI aURI); ACString getPublicSuffixFromHost(in AUTF8String aHost); Methods getBaseDomain
() Returns the base domain of a URI; that is, the public suffix with a given number of additional domain name parts. ACString getBaseDomain( in nsIURI aURI, [optional] in PRUint32 aAdditionalParts ); Parameters aURI The URI to be analyzed. aAdditionalParts The number of domain name parts to be returned in addition to the public suffix. Return value An ACString containing the base do...
...his exception is thrown if the hostname in aURI is empty. NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS This exception is thrown if there were insufficient subdomain levels in the hostname to satisfy the requested aAdditionalParts value. NS_ERROR_HOST_IS_IP_ADDRESS This exception is thrown if aURI is a numeric IPv4 or IPv6 address. NS_ERROR_UNEXPECTED Or other error returned by nsIIDNService.normalize
() when the hostname contains characters disallowed in URIs. getBaseDomainFromHost
() Returns the base domain of a host string. Otherwise identical to getBaseDomain
(). Note: It is strongly recommended that you use getBaseDomain
() if a suitable nsIURI is available. Only use this method if this is not the case. ACString getBaseDomainFromHost( in AUTF8String aHost, in PRUint32 aAdditionalParts...
...And 4 more matches
nsIFocusManager
AG_BYMOUSE 0x1000 Focus is changing due to a mouse operation, for instance the mouse was clicked on an element. FLAG_BYKEY 0x2000 Focus is changing due to a key operation, for instance pressing the tab key. This flag would normally be passed when MOVEFOCUS_FORWARD or MOVEFOCUS_BACKWARD is used. FLAG_BYMOVEFOCUS 0x4000 Focus is changing due to a call to MoveFocus
(). This flag will be implied when MoveFocus
() is called except when one of the other mechanisms (mouse or key) is specified, or when the type is MOVEFOCUS_ROOT or MOVEFOCUS_CARET. FLAG_SHOWRING 0x100000 Always show the focus ring or other indicator of focus, regardless of other state. MOVEFOCUS_FORWARD 1 Move focus forward one element, used when pressing TAB. ...
...ve focus to the first focusable element. MOVEFOCUS_LAST 6 Move focus to the last focusable element. MOVEFOCUS_ROOT 7 Move focus to the root element in the document. MOVEFOCUS_CARET 8 Move focus to a link at the position of the caret. This is a special value used to focus links as the caret moves over them in caret browsing mode. Methods clearFocus
() Clears the focused element within aWindow. If the current focusedWindow is a descendant of aWindow, sets the current focusedWindow to aWindow. void clearFocus( in nsIDOMWindow aWindow ); Parameters aWindow Exceptions thrown NS_ERROR_INVALID_ARG If aWindow is null. Native code only!contentRemoved Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)This ...
...ents( in nsIDocument aDocument ); Parameters aDocument Native code only!focusPlugin Indicate that a plugin wishes to take the focus. This is similar to a normal focus except that the widget focus is not changed. Updating the widget focus state is the responsibility of the caller. void focusPlugin( in nsIContent aPlugin ); Parameters aPlugin getFocusedElementForWindow
() nsIDOMElement getFocusedElementForWindow( in nsIDOMWindow aWindow, in PRBool aDeep, out nsIDOMWindow aFocusedWindow ); Parameters aWindow If equal to the current value of focusedWindow, then the returned element will be the application-wide focused element (the value of focusedElement). The return value will be null if no element is focused. aDeep If true, then child frame...
...And 4 more matches
nsIMemory
d deallocate memory segments from a heap. The implementation is free to define the heap. NS_GetMemoryManager returns the global nsIMemory instance. Method overview voidPtr alloc(in size_t size); Violates the XPCOM interface guidelines void free(in voidPtr ptr); Violates the XPCOM interface guidelines void heapMinimize(in boolean immediate); boolean isLowMemory
(); Deprecated since Gecko 2.0 voidPtr realloc(in voidPtr ptr, in size_t newSize); Violates the XPCOM interface guidelines Methods alloc Allocates a block of memory of a particular size. voidPtr alloc( in size_t size ); Parameters size The size of the block to allocate. Return value If the memory cannot be allocated (because of an out-of-memory condition), null is retur...
...uidelines Methods alloc Allocates a block of memory of a particular size. voidPtr alloc( in size_t size ); Parameters size The size of the block to allocate. Return value If the memory cannot be allocated (because of an out-of-memory condition), null is returned. Otherwise, it returns a pointer to the newly allocated memory segment. The result must be freed with a call to free
() when it is no longer needed. free Frees a previously allocated block of memory. void free( in voidPtr ptr ); Parameters ptr The address of the memory block to free. This may be null, in which case nothing happens. heapMinimize
() Attempts to shrink the size of the heap. A particular nsIMemory instance may choose not to implement this method. void heapMinimize( in boolean immediate...
...en the app is idle. isLowMemory Determine if we are in a low-memory situation (what constitutes low-memory is platform dependent). This can be used to trigger the memory pressure observers. Note: This method was deprecated in Gecko 2.0. If you need to monitor low memory conditions, you should watch for the Low memory notifications "memory-pressure" notifications instead. boolean isLowMemory
(); Parameters None. Return value true if we are in a low-memory situation. Otherwise false. Note: From Gecko 2.0 always returns false. See bug 592308. realloc
() Reallocates a block of memory to a new size. voidPtr realloc( in voidPtr ptr, in size_t newSize ); Parameters ptr The address of the memory block to reallocate. This may be null, in which case realloc behaves like alloc(...
...And 4 more matches
nsIMimeConverter
This should only be used by native code, as xpconnect translation causes it to not work properly. string encodeMimePartIIStr(in string header, in boolean structured, in string mailCharset, in long fieldnamelen, ...
...This should only be used by native code, as xpconnect translation causes it to not work properly. string encodeMimePartIIStr(in string header, in boolean structured, in string mailCharset, in long fieldnamelen, in long encode...
...operly. string encodeMimePartIIStr(in string header, in boolean structured, in string mailCharset, in long fieldnamelen, in long encodedWordSize); Parameters propertyName The name of the property to retrieve. Return Value The value of the property. encodeMimePartIIStr_UTF8
() Encodes a string into a MIME-encoded form according to RFC 2047. string encodeMimePartIIStr_UTF8(in AUTF8String header, in boolean structured, in string mailCharset, in long fieldnamelen, in long encodedWordSize); Parameters header The stri...
...And 4 more matches
nsIMsgHeaderParser
If any of the addresses doesn't have a mailbox, then the user name is used instead. AUTF8String extractHeaderAddressMailboxes( in string line ); Parameters line The header line to parse. Return value A comma-separated list of just the mailbox parts of the addresses...
...any of the addresses doesn't have a name, then the mailbox is used instead. AUTF8String extractHeaderAddressNames( in string line ); Parameters line The header line to parse. Return value A comma-separated list of just the name parts of the addresses. ...
... AString makeFullAddress( in AString aName, in AString aAddress ); Parameters aName The name of the sender. This should be in UTF-8. aAddress The address of the sender. ...
...And 4 more matches
nsIMsgIdentity
The nsIMsgIdentity interface contains all the personal outgoing mail information for a given person. Each identity is identified by a key, which is the id string in the identity preferences, such as in mail.identity.<id>.replyTo. ...
...John Doe email AString User's e-mail address, i.e. john@doe.com replyTo AString Optional replyTo address, i.e. johnNOSPAM@doe.com organization AString Optional organization composeHtml bo...
...Readonly: Default request for return receipt option for this identity. If this is set, the Return Receipt menu item on the compose window will be checked. receiptHeaderType long Readonly: requestDSN boolean Readonly: Default request for DSN option for this identity. If this is set, the DSN menu item on the compose window will be checked. Methods clearAllValues
() Note: This is really dangerous! This destroys all pref values; do not call this unless you know what you're doing! void clearAllValues
(); Parameters None. copy
() Copy the attributes of the identity we pass in. void copy(in nsIMsgIdentity identity); Parameters identity getUnicharAttribute
() Getter for Unicode attributes. Note: These attributes persist across sessions. AString g...
...And 4 more matches
nsIPrintingPrompt
ing the native Print Dialog. If an embedder implemented service returns any error code (other than NS_ERROR_ABORT) printing will terminate. Returning NS_OK assumes that the PrintSettings object was correctly filled in and if it does not have valid fields for printer name, and so on. it may also terminate. Defaults for platform service: showPrintDialog - displays a native dialog showPageSetup
() - displays a XUL dialog showProgress
() - displays a XUL dialog Summary for Windows embedders: Stated once again: There is no "fallback" native platform support in GFX for the displaying of the native print dialog. The current default implementation for Windows display a native print dialog but a XUL-based progress dialog. If you wish to have a native progress dialog on Windows you will have...
...ng will terminate and an error dialog will be displayed. Mac: The GFX layer still supports default toolkit behavior for displaying the Print Dialog. If an embedder implemented service returns NS_ERROR_NOT_IMPLEMENTED for "showPrintDialog" The toolkit will display the native print dialog. ...
...be displayed. Mac: The GFX layer still supports default toolkit behavior for displaying the Print Dialog. If an embedder implemented service returns NS_ERROR_NOT_IMPLEMENTED for "showPrintDialog" The toolkit will display the native print dialog. ...
...And 4 more matches
nsIPropertyBag2
Return value The property value as an ...
...etPropertyAsUint32(in AString prop); PRUint64 getPropertyAsUint64(in AString prop); PRBool hasKey(in AString prop); Methods get
() This method returns null if the value does not exist, or exists but is null. nsIVariant get( in AString prop ); Parameters prop Property to return the value of. Return value The property value as an nsIVariant. getPropertyAsACString
() ACString getPropertyAsACString( in AString prop ); Parameters prop Property to return the value of. Return value The property value as an ACString. Note: Accessing a property of a different type may attempt conversion to this type. getPropertyAsAString
() AString getPropertyAsAString( in AString prop ); Parameters prop Property to return the value of. Return value The pro...
...operty value as an ACString. Note: Accessing a property of a different type may attempt conversion to this type. getPropertyAsAString
() AString getPropertyAsAString( in AString prop ); Parameters prop Property to return the value of. Return value The property value as a String. Note: Accessing a property of a different type may attempt conversion to this type. getPropertyAsAUTF8String
() AUTF8String getPropertyAsAUTF8String( in AString prop ); Parameters prop Property to return the value of. Return value The property value as an AUTF8String. Note: Accessing a property of a different type may attempt conversion to this type. getPropertyAsBool
() boolean getPropertyAsBool( in AString prop ); Parameters prop Property to return the value of. Return value The ...
...And 4 more matches
nsISHistoryListener
n Gecko 1.7 A session history listener is notified when pages are added to, removed from, and loaded from session history. The listener can prevent any action (except adding a new session history entry) from happening by returning false from the corresponding callback method. ...
...Listener
() method. Method overview boolean OnHistoryGoBack(in nsIURI aBackURI); boolean OnHistoryGoForward(in nsIURI aForwardURI); boolean OnHistoryGotoIndex(in long aIndex, in nsIURI aGotoURI); void OnHistoryNewEntry(in nsIURI aNewURI); boolean OnHistoryPurge(in long aNumEntries); boolean OnHistoryReload(in nsIURI aReloadURI, in unsigned long aReloadFlags); Methods OnHistoryGoBack
() Called when navigating to a previous session history entry, for example due to an nsIWebNavigation.goBack
() call. boolean OnHistoryGoBack( in nsIURI aBackURI ); Parameters aBackURI The URI of the session history entry being navigated to. Return value true to allow the go back operation to proceed or false to cancel it. ...
...signed long aReloadFlags); Methods OnHistoryGoBack
() Called when navigating to a previous session history entry, for example due to an nsIWebNavigation.goBack
() call. boolean OnHistoryGoBack( in nsIURI aBackURI ); Parameters aBackURI The URI of the session history entry being navigated to. Return value true to allow the go back operation to proceed or false to cancel it. OnHistoryGoForward
() Called when navigating to a next session history entry, for example due to an nsIWebNavigation.goForward
() call. boolean OnHistoryGoForward( in nsIURI aForwardURI ); Parameters aForwardURI The URI of the session history entry being navigated to. Return value true to allow the go forward operation to proceed or false to cancel it. ...
...And 4 more matches
nsIScriptableInputStream
xpcom/io/nsIScriptableInputStream.idlScriptable This interface provides scriptable access to a nsIInputStream instance. Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview unsigned long available
(); void close
(); void init(in nsIInputStream aInputStream); string read(in unsigned long aCount); ACString readBytes(in unsigned long aCount); Methods available
() Return the number of bytes currently available in the stream. Note: This method should not be used to determine the total size of a stream, even if the stream corresponds to a local file. Moreover, since a stream may make available more than 2^32 bytes of data, this method is incapable of expressing the entire size...
...; Methods available
() Return the number of bytes currently available in the stream. Note: This method should not be used to determine the total size of a stream, even if the stream corresponds to a local file. Moreover, since a stream may make available more than 2^32 bytes of data, this method is incapable of expressing the entire size of the underlying data source. unsigned long available
(); Parameters None. Return value The number of bytes. Exceptions thrown NS_BASE_STREAM_CLOSED If called after the stream has been closed. close
() Closes the stream. Note: The close method may be called more than once, but subsequent calls are ignored. void close
(); Parameters None. init
() Wrap the given nsIInputStream with this nsIScriptableInputStream. Note: The init method may be call...
... Warning: If the data contains a null byte, then this method will return a truncated string. Note: It is also important to consider how a language bindings may interpret the string data type. ...
...And 4 more matches
nsISmsDatabaseService
lter filter, in boolean reverse, in long requestId, [optional] in unsigned long long processId); void getNextMessageInList(in long listId, in long requestId, [optional] in unsigned long long processId); void clearMessageList(in long listId); void markMessageRead(in long messageId, in boolean value, in long requestId, [optional] in unsigned long long processId) Methods saveReceivedMessage
() void saveReceivedMessage( in DOMString aSender, in DOMString aBody, in unsigned long long aDate ); Parameters aSender A DOMString with the sender of the text message. aBody A DOMString containing the body text of the message. aDate The timestamp of the message. saveSentMessage
() void saveSentMessage( in DOMString a Receiver, in DOMString aBody, in unsigned long long aDate ); Param...
.... aBody A DOMString containing the body text of the message. aDate The timestamp of the message. saveSentMessage
() void saveSentMessage( in DOMString a Receiver, in DOMString aBody, in unsigned long long aDate ); Parameters aReceiver A DOMString with the receiver of the text message. aBody A DOMString containing the body text of the message. aDate The timestamp of the message. getMessage
() void getMessage( in long messageId, in long requestId, [optional] in unsigned long long processId ); Parameters messageId A number representing the id of the message. requestId A number representing the id of the request. ...
... containing the body text of the message. aDate The timestamp of the message. getMessage
() void getMessage( in long messageId, in long requestId, [optional] in unsigned long long processId ); Parameters messageId A number representing the id of the message. requestId A number representing the id of the request. processId Optional A number representing the id of the process. deleteMessage
() void deleteMessage( in long messageId, in long requestId, [optional] in unsigned long long processId ); Parameters messageId A number representing the id of the message. requestId A number representing the id of the request. processId Optional A number representing the id of the process. ...
...And 4 more matches
nsITaskbarWindowPreview
blic/nsITaskbarWindowPreview.idlScriptable This interface is used on Microsoft Windows to represent the preview for a window in the taskbar. 1.0 66 Introduced Gecko 1.9.2 Inherits from: nsITaskbarPreview Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) You can't directly instantiate this interface; instead, call nsIWinTaskbar.getTaskbarWindowPreview
() to get the taskbar preview for a specific window. Window preview behavior By default, Windows implements much of the behavior for applications in a standard way. This interface's primary purpose is to let Gecko applications take control over parts of the preview; however, certain parts of the preview are not controlled using this interface. For example, the title and icon for each preview always ...
...let Gecko applications take control over parts of the preview; however, certain parts of the preview are not controlled using this interface. For example, the title and icon for each preview always match the title and icon of the corresponding window. If the enableCustomDrawing attribute is true, the controller you implement will start receiving calls to its nsITaskbarPreviewController.drawPreview
() and nsITaskbarPreviewController.drawThumbnail
() methods, as well as reads of its width, height, and thumbnailAccessRatio attributes. By default, however, Windows handles this drawing by itself. In addition, these previews are visible by default. When made invisible, the window disappears from the list of the application's windows in the taskbar. If a window has any visible nsITaskbarTabPreview ob...
...barWindowPreview for the corresponding window is automatically hidden. This is not reflected by the visible attribute. Note that even while the preview is hidden, its thumbnails and/or previews may still be requested by other parts of the operating system through the nsITaskbarWindowPreview's controller. ...
...And 4 more matches
nsIWebSocketListener
netwerk/protocol/websocket/nsIWebSocketListener.idlScriptable Implement this interface to receive WebSocket traffic events asynchronously after calling nsIWebSocketChannel.asyncOpen
(). 1.0 66 Introduced Gecko 8.0 Inherits from: nsISupports Last changed in Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5) Method overview void onAcknowledge(in nsISupports aContext, in PRUint32 aSize); void onBinaryMessageAvailable(in nsISupports aContext, in ACString aMsg); void onMessageAvailable(in nsISupports aContext, in AUTF8String aMsg); void onServerClose(in nsISupports aContext, in unsigned short aCode, in AUTF8String aReason); void onStart(in nsISupports aContext); void onStop(in nsISupports aContext, in nsres...
...void onBinaryMessageAvailable( i...
... void onMessageAvailable(in nsISupports aContext, in AUTF8String aMsg); void onServerClose(in nsISupports aContext, in unsigned short aCode, in AUTF8String aReason); void onStart(in nsISupports aContext); void onStop(in nsISupports aContext, in nsresult aStatusCode); Methods onAcknowledge
() Called to acknowledge a message sent via nsIWebSocketChannel.sendMsg
() or nsIWebSocketChannel.sendBinaryMsg
(). void onAcknowledge( in nsISupports aContext, in PRUint32 aSize ); Parameters aContext User defined context. aSize Number of bytes placed in OS send buffer. onBinaryMessageAvailable
() Called when a binary message has been received. void onBinaryMessageAvailable( in nsISupports aContext, in ACString aMsg ); Parameters aContext...
...And 4 more matches
nsIXFormsModelElement
nt.idlScriptable Defines scriptable methods for manipulating instance data and updating computed and displayed values. ...
...ines scriptable methods for manipulating instance data and updating computed and displayed values. ...
...thods for manipulating instance data and updating computed and displayed values. ...
...And 4 more matches
nsIXSLTProcessor
IXSLTProcessor.idlScriptable XSLT Processor Inherits from: nsISupports Last changed in Gecko 1.7 Implemented by: @mozilla.org/document-transformer;1?type=xslt. ...
...This will make the processor use the default-value for all paramete...
...ortStylesheet(in nsIDOMNode style); void removeParameter(in DOMString namespaceURI, in DOMString localName); void reset
(); void setParameter(in DOMString namespaceURI, in DOMString localName, in nsIVariant value); nsIDOMDocument transformToDocument(in nsIDOMNode source); nsIDOMDocumentFragment transformToFragment(in nsIDOMNode source, in nsIDOMDocument output); Methods clearParameters
() Removes all set parameters from this nsIXSLTProcessor. This will make the processor use the default-value for all parameters as specified in the stylesheet. void clearParameters
(); Parameters None. getParameter
() Gets a parameter if previously set by setParameter
(). Returns null otherwise. nsIVariant getParameter( in DOMString namespaceURI, in DOMString localName ); Parameters namespaceURI...
...And 4 more matches
wrappedJSObject
used to bypass them. Example component To see how the wrappedJSObject property works, we need an example XPCOM component implemented in JS. See How to Build an XPCOM Component in Javascript for details on creating one. For simplicity we omit the component registration code. Suppose we register the component below with the @myself.com/my-component;1 contract. // constructor function HelloWorld
() { }; HelloWorld.prototype = { hello: function
() { return "Hello World!"; }, QueryInterface: function(aIID) { if (!aIID.equals(Components.interfaces.nsISupports) && !aIID.equals(Components.interfaces.nsIHelloWorld)) throw Components.results.NS_ERROR_NO_INTERFACE; return this; } }; XPConnect wrapping Now let's get a reference to our component. In this exampl...
...equals(Components.interfaces.nsIHelloWorld)) throw Components.results.NS_ERROR_NO_INTERFACE; return this; } }; XPConnect wrapping Now let's get a reference to our component. ...
...elloWorld)) throw Components.results.NS_ERROR_NO_INTERFACE; return this; } }; XPConnect wrapping Now let's get a reference to our component. ...
...And 4 more matches
nsIMsgCloudFileProvider
ceedQuota 0x8055311b Returned when uploading has failed because the user has exceeded their storage quota. uploadExceedsFileLimit 0x8055311c Returned when uploading has failed because the file being uploaded is larger than the file size limit. uploadCanceled 0x8055311d Returned when uploading has stopped because it was cancelled by the user. Methods init
() Initializes an nsIMsgCloudFileProvider to be associated with a particular account. This should probably be called immediately after instantiation. void init(in string aAccountKey); Parameters uploadFile
() Starts a file upload for this account. aAccountKey The account key that this instance of the nsIMsgCloudFileProvider should be associated with. void uploadFile(in nsILocalFile aFile...
...uploadFile
() Starts a file upload for this account. aAccountKey The account key that this instance of the nsIMsgCloudFileProvider should be associated with. void uploadFile(in nsILocalFile aFile, in nsIRequestObserver aCallback); Parameters aFile The file to be uploaded. aCallback The nsIRequestObserver callback to receive request start and stop notices. urlForFile
() Returns the URL for a file that has been uploaded. ACString urlForFile(in nsILocalFile aFile); Parameters aFile The previously uploaded file to get the URL for. Return value The string representation of the URL for the uploaded file. If the file was not uploaded with this instance of the nsIMsgCloudFileProvider, returns undefined. ...
...start and stop notices. urlForFile
() Returns the URL for a file that has been uploaded. ACString urlForFile(in nsILocalFile aFile); Parameters aFile The previously uploaded file to get the URL for. Return value The string representation of the URL for the uploaded file. If the file was not uploaded with this instance of the nsIMsgCloudFileProvider, returns undefined. cancelFileUpload
() Cancels an upload currently in progress for some nsILocalFile. void cancelFileUpload(in nsILocalFile aFile); Parameters aFile The nsILocalFile that is currently being uploaded to cancel. refreshUserInfo
() Refreshes the data for this user account - for example, the storage quota, or the amount of storage being used. void refreshUserInfo(in boolean aWithUI, in nsIRe...
...And 4 more matches
Working with windows in chrome code
object (usually ChromeWindow) - the same type as the window variable. Technically speaking, it implements a number of interfaces, including nsIDOMJSWindow and nsIDOMWindow, but it also contains the user-defined properties for global variables and functions of the window. So, for example, to access the DOM document corresponding to the window, you can use win.document. Note however, that the open
() call returns before the window is fully loaded, so some calls, like win.document.getElementById
() will fail. To overcome this difficulty, you can move the initialization code to a load handler of the window being opened or pass a callback function, as described below. You can get a Window object from a document using document.defaultView. Content windows When a XUL window contains a widget cap...
...n XPCOM Object to a New Window when it has a more useful example Opener code: window.openDialog("chrome://test/content/progress.xul", "myProgress", "chrome,centerscreen", {status: "Reading remote data", maxProgress: 50, progress: 10} ); progress.xul: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window onload="onLoad
();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script><![CDATA[ var gStatus, gProgressMeter; var maxProgress = 100; function onLoad
() { gStatus = document.getElementById("status"); gProgressMeter = document.getElementById("progressmeter"); if("arguments" in window && window.arguments.length > 0) { maxProgress = window.arguments[0].maxProgress; setProgre...
...You can find the window's opener using its window.opener property or via a callback function passed to the window in a way described in the previous section. Let's add code ...
...And 4 more matches
Debugging Tips
Currently console.log doesn't show type information of CData. Running the following code shows only partial value information. ...
...e/modules/ctypes.jsm", {}); let i = ctypes.int32_t(10); console.log(i); let Point = ctypes.StructType("Point", [{ x: ctypes.int32_t }, { y: ctypes.int32_t }]) let p = Point(10, 20); console.log(p); let pp = p.address
(); console.log(pp); The result will be as following: CData { value: 10 } CData { x: 10, y: 20 } CData { contents: CData } To see more descriptive information, you can use .toSource
(). ...
...: ctypes.int32_t }]) let p = Point(10, 20); console.log(p); let pp = p.address
(); console.log(pp); The result will be as following: CData { value: 10 } CData { x: 10, y: 20 } CData { contents: CData } To see more descriptive information, you can use .toSource
(). let { ctypes } = Components.utils.import("resource://gre/modules/ctypes.jsm", {}); let i = ctypes.int32_t(10); console.log(i.toSource
()); let Point = ctypes.StructType("Point", [{ x: ctypes.int32_t }, { y: ctypes.int32_t }]) let p = Point(10, 20); console.log(p.toSource
()); let pp = p.address
(); console.log(pp.toSource
()); The result will be : ctypes.int32_t(10) Point(10, 20) Point.ptr(ctypes.UInt64("0x15fdafb08")) To see the complete type information, you can use .constructor.toSource
(), to print the source of CType. let { ...
...And 4 more matches
Flash Activation: Browser Comparison - Plugins
other content, users will probably not notice that Flash is required and will become confused. Even if the plugin element will eventually be hidden, pages should create the plugin element so that it's visible on the page, and should resize or hide it only after the user has activated the plugin. ...
...ent so that it's visible on the page, and should resize or hide it only after the user has activated the plugin. ...
... Using a script callback to determine when a plugin is activated Similarly, a site's script shouldn't attempt to script a plugin immediately upon creation. ...
...And 4 more matches
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
nt unless you have changed the preference as explained above.) Selecting the 'browser' context in the Scratchpad Enter the following code in the Scratchpad: // This simply defines the 'Debugger' constructor in this // Scratchpad; it doesn't actually start debugging anything. Components.utils.import('resource://gre/modules/jsdebugger.jsm'); addDebuggerToGlobal(window); (function
() { // The debugger we'll use to observe a tab's allocation. var dbg; // Start measuring the selected tab's main window's memory // consumption. This function is available in the browser // console. window.demoTrackAllocations = function
() { dbg = new Debugger; // This makes hacking on the demo *much* more // pleasant. dbg.uncaughtExceptionHook = handleUncaughtExceptio...
...'s main content window. var w = gBrowser.selectedBrowser.contentWindow; console.log("Tracking allocations in page: " + w.location.href); // Make that window a debuggee of our Debugger. dbg.addDebuggee(w.wrappedJSObject); // Enable allocation tracking in dbg's debuggees. dbg.memory.trackingAllocationSites = true; } window.demoPlotAllocations = function
() { // Grab the allocation log. var log = dbg.memory.drainAllocationsLog
(); // Neutralize the Debugger, and drop it on the floor // for the GC to collect. console.log("Stopping allocation tracking."); dbg.removeAllDebuggees
(); dbg = undefined; // Analyze and display the allocation log. plot(log); } function handleUncaughtException(ex) { console.log('De...
...Note that stack entries are '===' if // they represent the same site with the same callers. var counts = new Map; for (let site of log) { // This is a kludge, necessary for now. ...
...And 4 more matches
AddressErrors - Web APIs
eport validation errors in a physical address (typically a billing address or a shipping address). Any members which is present indicates that a validation error occurred for the member of the same name in an address described using PaymentAddress. AddressErrors is the type of the object returned by shippingAddressErrors in the PaymentDetailsUpdate passed into PaymentRequestUpdateEvent.updateWith
() by the shippingaddresschange event handler if a change to the address resulted in a validation error occurring. See the examples below to see how this works. Properties addressLine A DOMString which, if present, indicates that the addressLine property of the PaymentAddress could not be validated. The contents of the string provide a human-readable explanation of the validation failure, and ...
... Express, and Discover. defaultPaymentDetails describes the payment being requested. A description of the total amount being requested (including a label and the currency used), a list of the line items (in this case only one, "Original donation amount"), and a list of shipping options available; in this case only one. ...
...ribes the payment being requested. A description of the total amount being requested (including a label and the currency used), a list of the line items (in this case only one, "Original donation amount"), and a list of shipping options available; in this case only one. Process the payment The main payment processing code is found in the process
() method, up next. let request; function process
() { let options = {requestShipping: true}; try { request = new PaymentRequest(supportedHandlers, defaultPaymentDetails, options); // Add event listeners here. request.onshippingaddresschange = handleAddressChange; // Call show
() to trigger the browser's payment flow. request.show
().then(function(instrumentResponse) { // Do something with the response from the UI. ...
...And 4 more matches
AnalyserNode - Web APIs
Properties Inherits properties from its parent, AudioNode. AnalyserNode.fftSize Is an unsigned long value representing the size of the FFT (Fast Fourier Transform) to be used to determine the frequency domain. AnalyserNode.frequencyBinCount Read only Is an unsigned long value half that of the FFT size. This generally equates to the numb...
...alf that of the FFT size. This generally equates to the number of data values you will have to play with for the visualization. AnalyserNode.minDecibels Is a double value representing the minimum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values -- basically, this specifies the minimum value for the range of results when using getByteFrequencyData
(). AnalyserNode.maxDecibels Is a double value representing the maximum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values -- basically, this specifies the maximum value for the range of results when using getByteFrequencyData
(). AnalyserNode.smoothingTimeConstant Is a double value representing the averaging constant with the last analysis frame --...
...values -- basically, this specifies the maximum value for the range of results when using getByteFrequencyData
(). AnalyserNode.smoothingTimeConstant Is a double value representing the averaging constant with the last analysis frame -- basically, it makes the transition between values over time smoother. Methods Inherits methods from its parent, AudioNode. AnalyserNode.getFloatFrequencyData
() Copies the current frequency data into a Float32Array array passed into it. AnalyserNode.getByteFrequencyData
() Copies the current frequency data into a Uint8Array (unsigned byte array) passed into it. ...
...And 4 more matches
AudioBufferSourceNode.loopEnd - Web APIs
fferSourceNode.loopEnd; Value A floating-point number indicating the offset, in seconds, into the audio buffer at which each loop will loop return to the beginning of the loop (that is, the current play time gets reset to AudioBufferSourceNode.loopStart). This property is only used if the loop property is true. The default value is 0. Example In this example, the AudioContext.decodeAudioData
() function is used to decode an audio track and put it into an AudioBufferSourceNode. Buttons are provided to play and stop the audio playback, and slider controls are used to change the playbackRate, loopStart and loopEnd properties on the fly. When the audio is played to the end, it loops, but you can control how long the loops last by altering loopStart and loopEnd. For example, if you set thei...
...he end, it loops, but you can control how long the loops last by altering loopStart and loopEnd. For example, if you set their values to 20 and 25, respectively, then begin playback, the sound will play normally until it reaches the 25 second mark. ...
...f you set their values to 20 and 25, respectively, then begin playback, the sound will play normally until it reaches the 25 second mark. Then the current play position will loop back to the 20 second mark and continue playing until the 25 second mark, ad infinitum (or at least until stop
() is called). For a full working example, see this code running live, or view the source. ...
...And 4 more matches
AudioBufferSourceNode.playbackRate - Web APIs
r a sound buffer containing audio sampled at 44.1 kHz (44,100 samples per second). Let's see what a few values of playbackRate do: A playbackRate of 1.0 plays the audio at full speed, or 44,100 Hz. A playbackRate of 0.5 plays the audio at half speed, or 22,050 Hz. A playbackRate of 2.0 doubles the audio's playback rate to 88,200 Hz. Example In this example, the AudioContext.decodeAudioData
() function is used to decode an audio track, and put it into an AudioBufferSourceNode. Buttons are provided to play and stop the audio playback, and a slider control is used to change the playbackRate property value on the fly. You can run the example live (or view the source.) Play the song and alter the playback rate for some fun results. <input class="playback-rate-control" type="range" min=...
...vided to play and stop the audio playback, and a slider control is used to change the playbackRate property value on the fly. You can run the example live (or view the source.) Play the song and alter the playback rate for some fun results. ...
...and a slider control is used to change the playbackRate property value on the fly. You can run the example live (or view the source.) Play the song and alter the playback rate for some fun results. ...
...And 4 more matches
AudioBufferSourceNode - Web APIs
xt { fill: #0095DD; pointer-events: all;} An AudioBufferSourceNode has no inputs and exactly one output, which has the same number of channels as the AudioBuffer indicated by its buffer property. If there's no buffer set--that is, if buffer is null--the output contains a single channel of silence (every sample is 0). An AudioBufferSourceNode can only be played once; after each call to start
(), you have to create a new node if you want to play the same sound again. Fortunately, these nodes are very inexpensive to create, and the actual AudioBuffers can be reused for multiple plays of the sound. Indeed, you can use these nodes in a "fire and forget" manner: create the node, call start
() to begin playing the sound, and don't even bother to hold a reference to it. It will automatically be...
... the actual AudioBuffers can be reused for multiple plays of the sound. Indeed, you can use these nodes in a "fire and forget" manner: create the node, call start
() to begin playing the sound, and don't even bother to hold a reference to it. It will automatically be garbage-collected at an appropriate time, which won't be until sometime after the sound has finished playing. Multiple calls to stop
() are allowed. The most recent call replaces the previous one, if the AudioBufferSourceNode has not already reached the end of the buffer. Number of inputs 0 Number of outputs 1 Channel count defined by the associated AudioBuffer Constructor AudioBufferSourceNode
() Creates and returns a new AudioBufferSourceNode object. An AudioBufferSourceNode ca...
... Properties Inherits properties from its parent, AudioNode. ...
...And 4 more matches
AudioParam - Web APIs
ioParam.maxValue Read only Represents the maximum possible value for the parameter's nominal (effective) range. AudioParam.minValue Read only Represents the minimum possible value for the parameter's nominal (effective) range. AudioParam.value Represents the parameter's current value as of the current time; initially set to the value of defaultValue. Methods AudioParam.setValueAtTime
() Schedules an instant change to the value of the AudioParam at a precise time, as measured against AudioContext.currentTime. The new value is given by the value parameter. AudioParam.linearRampToValueAtTime
() Schedules a gradual linear change in the value of the AudioParam. The change starts at the time specified for the previous event, follows a linear ramp to the new value given in the value ...
...ime. The new value is given by the value parameter. AudioParam.linearRampToValueAtTime
() Schedules a gradual linear change in the value of the AudioParam. The change starts at the time specified for the previous event, follows a linear ramp to the new value given in the value parameter, and reaches the new value at the time given in the endTime parameter. AudioParam.exponentialRampToValueAtTime
() Schedules a gradual exponential change in the value of the AudioParam. The change starts at the time specified for the previous event, follows an exponential ramp to the new value given in the value parameter, and reaches the new value at the time given in the endTime parameter. AudioParam.setTargetAtTime
() Schedules the start of a change to the value of the AudioParam. The change starts at th...
... the time given in the endTime parameter. AudioParam.setTargetAtTime
() Schedules the start of a change to the value of the AudioParam. The change starts at the time specified in startTime and exponentially moves towards the value given by the target parameter. The exponential decay rate is defined by the timeConstant parameter, which is a time measured in seconds. AudioParam.setValueCurveAtTime
() Schedules the values of the AudioParam to follow a set of values, defined by an array of floating-point numbers scaled to fit into the given interval, starting at a given start time and spanning a given duration of time. AudioParam.cancelScheduledValues
() Cancels all scheduled future changes to the AudioParam. ...
...And 4 more matches
BiquadFilterNode.Q - Web APIs
The Q property of the BiquadFilterNode interface is an a-rate AudioParam, a double representing a Q factor, or quality factor. It is a dimensionless value with a default value of 1 and a nominal range of 0.0001 to 1000. Syntax var audioCtx = new AudioContext
(); var biquadFilter = audioCtx.createBiquadFilter
(); biquadfilter.Q.value = 100; Note: Though the AudioParam returned is read-only, the value it represents is not. Value An AudioParam. ...
...r.Q.value = 100; Note: Though the AudioParam returned is read-only, the value it represents is not. Value An AudioParam. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
... Value An AudioParam. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
...And 4 more matches
BiquadFilterNode.detune - Web APIs
The detune property of the BiquadFilterNode interface is an a-rate AudioParam representing detuning of the frequency in cents. Syntax var audioCtx = new AudioContext
(); var biquadFilter = audioCtx.createBiquadFilter
(); biquadFilter.detune.value = 100; Note: Though the AudioParam returned is read-only, the value it represents is not. Value An a-rate AudioParam. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
...ue = 100; Note: Though the AudioParam returned is read-only, the value it represents is not. Value An a-rate AudioParam. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
... An a-rate AudioParam. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
...And 4 more matches
BiquadFilterNode.frequency - Web APIs
The frequency property of the BiquadFilterNode interface Is a k-rate AudioParam, a double representing a frequency in the current filtering algorithm measured in hertz (Hz). frequency's default value is 350 with a nominal range of 10 to the Nyquist frequency -- that is, half of the sample rate. Syntax var audioCtx = new AudioContext
(); var biquadFilter = audioCtx.createBiquadFilter
(); biquadFilter.frequency.value = 3000; Note: Though the AudioParam returned is read-only, the value it represents is not. Value An AudioParam. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). var audioCtx = new (window.AudioContext || window.webkit...
...cy.value = 3000; Note: Though the AudioParam returned is read-only, the value it represents is not. Value An AudioParam. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
... Value An AudioParam. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
...And 4 more matches
BiquadFilterNode.gain - Web APIs
The gain property of the BiquadFilterNode interface Is a a-rate AudioParam, a double representing the gain used in the current filtering algorithm. When it takes a positive value it is a real gain, when negative it is an attenuation. It is expressed in dB, has a default value of 0 and can take a value in a nominal range of -40 to 40. Syntax var audioCtx = new AudioContext
(); var biquadFilter = audioCtx.createBiquadFilter
(); biquadfilter.gain.value = 25; Note: Though the AudioParam returned is read-only, the value it represents is not. Value An AudioParam. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). var audioCtx = new (win...
...gain.value = 25; Note: Though the AudioParam returned is read-only, the value it represents is not. Value An AudioParam. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
... Value An AudioParam. Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
...And 4 more matches
BiquadFilterNode.type - Web APIs
type values and their meaning type Description frequency Q gain lowpass Standard second-order resonant lowpass filter with 12dB/octave rolloff. Frequencies below the cutoff pass through; frequencies above it are attenuated. The cutoff frequency. ...
...on is at the medium frequency. The larger this parameter is, the sharper and larger the transition will be. Not used Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
...l be. Not used Example The following example shows basic usage of an AudioContext to create a Biquad filter node. For a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
...And 4 more matches
BluetoothRemoteGATTCharacteristic - Web APIs
Blueto...
... BluetoothRemoteGATTCharacteristic.uuidRead only Returns a DOMString containing the UUID of...
... BluetoothRemoteGATTCharacteristic.uuidRead only Returns a DOMString containing the UUID of the characteristic, for example '000...
...And 4 more matches
CSSPrimitiveValue.primitiveType - Web APIs
The primitiveType read-only property of the CSSPrimitiveValue interface represents the type of a CSS value. Syntax type = cssPrimitiveValue.primitiveType; Value An unsigned short representing the type of the value. Possible values are: Constant Description CSS_ATTR The value is an attr
() function. The value can be obtained by using the getStringValue
() method. CSS_CM The value is a <length> in centimeters. The value can be obtained by using the getFloatValue
() method. CSS_COUNTER The value is a counter or counters function. The value can be obtained by using the getCounterValue
() method. CSS_DEG The value is an <angle> in degrees. The value can be obtained by using the getFloatValue
() method. CSS_DIMENSION The val...
...atValue
() method. CSS_COUNTER The value is a counter or counters function. The value can be obtained by using the getCounterValue
() method. CSS_DEG The value is an <angle> in degrees. The value can be obtained by using the getFloatValue
() method. CSS_DIMENSION The value is a <number> with an unknown dimension. The value can be obtained by using the getFloatValue
() method. CSS_EMS The value is a <length> in em units. The value can be obtained by using the getFloatValue
() method. CSS_EXS The value is a <length> in ex units. The value can be obtained by using the getFloatValue
() method. CSS_GRAD The value is an <angle> in grads. The value can be obtained by using the getFloatValue
() method. CSS_HZ The value is a...
...he value can be obtained by using the getFloatValue
() method. CSS_GRAD The value is an <angle> in grads. The value can be obtained by using the getFloatValue
() method. CSS_HZ The value is a <frequency> in Hertz. The value can be obtained by using the getFloatValue method. CSS_IDENT The value is an identifier. The value can be obtained by using the getStringValue
() method. CSS_IN The value is a <length> in inches. The value can be obtained by using the getFloatValue
() method. CSS_KHZ The value is a <frequency> in Kilohertz. The value can be obtained by using the getFloatValue
() method. CSS_MM The value is a <length> in millimeters. The value can be obtained by using the getFloatValue
() method. CSS_MS The value...
...And 4 more matches
CSS Typed Object Model API - Web APIs
ssigned to CSS properties while enabling maintainable code that is both more understand and easier to write. Interfaces CSSStyleValue The CSSStyleValue interface of the the CSS Typed Object Model API is the base class of all CSS values accessible through the Typed OM API. An instance of this class may be used anywhere a string is expected. ...
... accessible through the Typed OM API. An instance of this class may be used anywhere a string is expected. CSSStyleValue.parse(property, cssText) The parse
() method of the CSSStyleValue interface allows a CSSNumericValue to be constructed from a CSS string. It sets a specific CSS property to the specified values and returns the first value as a CSSStyleValue object. CSSStyleValue.parseAll
() The parseAll
() method of the CSSStyleValue interface sets all occurences of a specific CSS property to the specified valueand returns an array of CSSStyleValue objects, each containing one of the supplied values. StylePropertyMap The StylePropertyMap interface of the the CSS Typed Object Model API provides a representation of a CSS declaration block that is an alternative to CSSStyleDeclarati...
...the CSSStyleValue interface sets all occurences of a specific CSS property to the specified valueand returns an array of CSSStyleValue objects, each containing one of the supplied values. StylePropertyMap The StylePropertyMap interface of the the CSS Typed Object Model API provides a representation of a CSS declaration block that is an alternative to CSSStyleDeclaration. ...
...And 4 more matches
DirectoryEntrySync - Web APIs
d, having failed to reach any substantial traction. Basic concepts If you want to create subdirectories, you have to create each child directory in sequence. If you try to create a directory using a full path that includes parent directories that do not exist yet, you get an error. So create the hierarchy by recursively adding a new path after creating the parent directory. Example The getFile
() method returns a FileEntrySync, which represents a file in the file system. The following creates an empty file called seekrits.txt in the root directory. var fileEntry = fs.root.getFile('seekrits.txt', {create: true}); The getDirectory
() method returns a DirectoryEntrySync, which represents a file in the file system. The following creates a new directory called superseekrit in the root direc...
... the root directory. var fileEntry = fs.root.getFile('seekrits.txt', {create: true}); The getDirectory
() method returns a DirectoryEntrySync, which represents a file in the file system. The following creates a new directory called superseekrit in the root directory. ...
... DirectoryReaderSync createReader ( ) raises (FileException); Returns DirectoryReaderSync Represents a directory in a file system. ...
...And 4 more matches
EffectTiming.easing - Web APIs
The value of easing corresponds directly to AnimationEffectTimingReadOnly.easing in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
...The value of easing corresponds directly to AnimationEffectTimingReadOnly.easing in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
...The value of easing corresponds directly to AnimationEffectTimingReadOnly.easing in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
...And 4 more matches
HTMLDialogElement - Web APIs
er-events: all;} Properties Inherits properties from its parent, HTMLElement. HTMLDialogElement.open A Boolean reflecting the open HTML attribute, indicating whether the dialog is available for interaction. HTMLDialogElement.returnValue A DOMString that sets or returns the return value for the dialog. Methods Inherits methods from its parent, HTMLElement. HTMLDialogElement.close
() Closes the dialog. An optional DOMString may be passed as an argument, updating the returnValue of the the dialog. HTMLDialogElement.show
() Displays the dialog modelessly, i.e. still allowing interaction with content outside of the dialog. HTMLDialogElement.showModal
() Displays the dialog as a modal, over the top of any other dialogs that might be present. Interaction outside the dialog is b...
...LDialogElement.showModal
() Displays the dialog as a modal, over the top of any other dialogs that might be present. Interaction outside the dialog is blocked. Events close Fired when the dialog is closed. Also available via the onclose property. Examples The following example shows a simple button that, when clicked, opens a <dialog> containing a form via the HTMLDialogElement.showModal
() function. From there you can click the Cancel button to close the dialog (via the HTMLDialogElement.close
() function), or submit the form via the submit button. <!-- Simple pop-up dialog box, containing a form --> <dialog id="favDialog"> <form method="dialog"> <section> <p><label for="favAnimal">Favorite animal:</label> <select id="favAnimal" name="favAnimal"> ...
...ption>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function
() { var updateButton = document.getElementById('updateDetails'); var cancelButton = document.getElementById('cancel'); var dialog = document.getElementById('favDialog'); dialog.returnValue = 'favAnimal'; function openCheck(dialog) { if(dialog.open) { console.log('Dialog open'); } else { console.log('Dialog closed'); } ...
...And 4 more matches
IDBCursor - Web APIs
ned. The cursor's key can be any data type. IDBCursor.primaryKey Read only Returns the cursor's current effective primary key. If the cursor is currently being iterated or has iterated outside its range, this is set to undefined. The cursor's primary key can be any data type. IDBCursor.request Read only Returns the IDBRequest that was used to obtain the cursor. ...
...ursor's current effective primary key. If the cursor is currently being iterated or has iterated outside its range, this is set to undefined. The cursor's primary key can be any data type. IDBCursor.request Read only Returns the IDBRequest that was used to obtain the cursor. Methods IDBCursor.advance
() Sets the number of times a cursor should move its position forward. IDBCursor.continue
() Advances the cursor to the next position along its direction, to the item whose key matches the optional key parameter. IDBCursor.continuePrimaryKey
() Sets the cursor to the given index key and primary key given as arguments. IDBCursor.delete
() Returns an IDBRequest object, and, in a separate thread, deletes the record at the cursor's position, without changing the cursor's position. This...
...This can be used to update specific records. Constants These constants are no longer available -- they were removed in Gecko 25. ...
...And 4 more matches
IDBIndexSync - Web APIs
ring The key path of this index. If this attribute is null, this index is not auto-populated. name readonly DOMString The name of this index. storeName readonly DOMString This index's referenced object store. unique readonly boolean If true, a key can have only one value within the index; if false, a key can have duplicate values. Methods add
() Stores the given value into this index, optionally with the specified key. If a record already exists with the given key, an exception is raised. any add( in any value, in optional any key ) raises (IDBDatabaseException); Parameters Returns Exceptions This method can raise a IDBDatabaseException with the following code: value The value to store into the index. key A key to use fo...
...n with the following code: value The value to store into the index. key A key to use for identifying the record. any The key for the stored record. CONSTRAINT_ERR If a record exists in this index with a key corresponding to the key parameter or the index is auto-populated, or if no record exists with a key corresponding to the value parameter in the index's referenced object store. get
() Retrieves the value from this index for the record that corresponds to the given key. any get ( in any key ) raises (IDBDatabaseException); Parameters key The key that identifies the record to be retrieved. Returns any The retrieved value from the index. Exceptions This method can raise an IDBDatabaseException with the following code: NOT_FOUND_ERR If no record exists in th...
...or the record that corresponds to the given key. any get ( in any key ) raises (IDBDatabaseException); Parameters key The key that identifies the record to be retrieved. Returns any The retrieved value from the index. Exceptions This method can raise an IDBDatabaseException with the following code: NOT_FOUND_ERR If no record exists in this index for the given key. getObject
() Retrieves and returns the value from this index's referenced object store that corresponds to the given key. any getObject ( in any key ) raises (IDBDatabaseException); Parameters key The key that identifies the record to be retrieved. Returns any The retrieved value from the referenced object store. Exceptions This method can raise a IDBDatabaseException with the following cod...
...And 4 more matches
KeyboardEvent.code - Web APIs
orward, left, backward, and right. This will use the same four keys physically regardless of what the actual corresponding characters are, such as if the user is using an AZERTY keyboard. HTML <p>Use the WASD (ZQSD on AZERTY) keys to move and steer.</p> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="world"> <polygon id="spaceship" points="15,0 0,30 30,30"/> </svg> <script>refresh
();</script> CSS .world { margin: 0px; padding: 0px; background-color: black; width: 400px; height: 400px; } #spaceship { fill: orange; stroke: red; stroke-width: 2px; } JavaScript The first section of the JavaScript code establishes some variables we'll be using. shipSize contains the size of the ship the player is moving around, for convenience. position is used to track the ...
...ointing straight up). Finally, spaceship is set to refer to the element with the ID "spaceship", which is the SVG polygon representing the ship the player controls. let shipSize = { width: 30, height: 30 }; let position = { x: 200, y: 200 }; let moveRate = 9; let turnRate = 5; let angle = 0; let spaceship = document.getElementById("spaceship"); Next comes the function updatePosition
(). This function takes as input the distance the ship is to be moved, where positive is a forward movement and negative is a backward movement. This function computes the new position of the ship given the distance moved and the current direction the ship is facing. It also handles ensuring that the ship wraps across the boundaries of the play field instead of vanishing. function updatePosition(of...
... instead of vanishing. ...
...And 4 more matches
MediaElementAudioSourceNode - Web APIs
The MediaElementAudioSourceNode interface represents an audio source consisting of an HTML5 <audio> or <video> element. It is an AudioNode that acts as an audio source. A MediaElementSourceNode has no inputs and exactly one output, and is created using the AudioContext.createMediaElementSource
() method. The amount of channels in the output equals the number of channels of the audio referenced by the HTMLMediaElement used in the creation of the node, or is 1 if the HTMLMediaElement has no audio. ...
...of channels of the audio referenced by the HTMLMediaElement used in the creation of the node, or is 1 if the HTMLMediaElement has no audio. Number of inputs 0 Number of outputs 1 Channel count defined by the media in the HTMLMediaElement passed to the AudioContext.createMediaElementSource method that created it. ...
...You can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. ...
...And 4 more matches
MediaStreamTrack - Web APIs
See Capabilities, constraints, and settings to learn how to correctly work with constrainable properties. ...
...See Capabilities, constraints, and settings to learn how to correctly work with constrainable properties. ...
...See Capabilities, constraints, and settings to learn how to correctly work with constrainable properties. ...
...And 4 more matches
Media Capabilities API - Web APIs
Different browsers support different media types and new media types are always being developed. With the Media Capabilities API, developers can ensure each user is getting the best bitrate and storage savings for their browser, device, a...
...ce uses hardware or software decoding impacts how smooth and power efficient the video decoding is and how efficient the playback will be. The Media Capabilities API enables determining which codecs are supported and how performant a media file will be both in terms of smoothness and power efficiency. The Media Capabilities API provide more powerful features than say MediaRecorder.isTypeSupported
() or HTMLMediaElement.canPlayType
(), which only address general browser support, not performance. The API also provides abilities to access display property information such as supported color gamut, dynamic range abilities, and real-time feedback about the playback. To test support, smoothness and power efficiency of a video or audio file, you define the media configuration you want to test, and...
...provides abilities to access display property information such as supported color gamut, dynamic range abilities, and real-time feedback about the playback. To test support, smoothness and power efficiency of a video or audio file, you define the media configuration you want to test, and then pass the audio or video configuration as the parameter of the MediaCapabilities interface's encodingInfo
() and decodingInfo
() methods. Media capabilities information enables websites to enable adaptative streaming to alter the quality of content based on actual user-perceived quality, and react to a pick of CPU/GPU usage in real time. Media Capabilities Interfaces MediaCapabilities Provides information about the decoding abilities of the device, system and browser based on codecs, profile, resol...
...And 4 more matches
OVR_multiview2 - Web APIs
port for rendering into multiple views simultaneously. This especially useful for virtual reality (VR) and WebXR. For more information, see also: Multiview on WebXR three.js multiview demo Multiview in babylon.js Optimizing Virtual Reality: Understanding Multiview Multiview WebGL Rendering for Oculus Browser 6.0+ WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: Support depends on the system's graphics driver (Windows+ANGLE and Android are supported; Windows+GL, Mac, Linux are not supported). This extension is only available to WebGL 2 contexts as it needs GLSL 3.00 and texture arrays. Currently, there is no way to use multiview to render to a multisampled ba...
...GL 2 contexts as it needs GLSL 3.00 and texture arrays. Currently, there is no way to use multiview to render to a multisampled backbuffer, so you should create contexts with antialias: false. However, the Oculus browser (6+) also supports multisampling using the OCULUS_multiview extension. See also this WebGL issue. Constants This extension exposes 4 constants that can be used in getParameter
() or getFramebufferAttachmentParameter
(). FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR Number of views of the framebuffer object attachment. FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR Base view index of the framebuffer object attachment. MAX_VIEWS_OVR The maximum number of views. Most VR headsets have two views, but there are prototypes of headset with ultra-wide FOV using 4 views w...
...upported by multiview. FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR If baseViewIndex is not the same for all framebuffer attachment points where the value of FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is not NONE, the framebuffer is considered incomplete. Calling checkFramebufferStatus for a framebuffer in this state returns FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR. ...
...And 4 more matches
OffscreenCanvas - Web APIs
The OffscreenCanvas interface provides a canvas that can be rendered off screen. It is available in both the window and worker contexts. Constructors OffscreenCanvas
() OffscreenCanvas constructor. Creates a new OffscreenCanvas object. Properties OffscreenCanvas.height The height of the offscreen canvas. OffscreenCanvas.width The width of the offscreen canvas. Methods OffscreenCanvas.getContext
() Returns a rendering context for the offscreen canvas. OffscreenCanvas.convertToBlob
() Creates a Blob object representing the image contained in the canvas. OffscreenCanvas.transferToImageBitmap
() Creates an ImageBitmap object from the most recently rendered image of the OffscreenCanvas. Examples Synchronous display of frames produced by an OffscreenCanvas O...
...This method returns an ImageBitmap object, which can be used in a variety of Web APIs and also in a second canvas without creating a transfer copy. To display the ImageBitmap, you can use a ImageBitmapRenderingContext context, which can be created by calling canvas.getContext("bitmaprenderer") on a (visible) canvas element. ...
...also in a second canvas without creating a transfer copy. To display the ImageBitmap, you can use a ImageBitmapRenderingContext context, which can be created by calling canvas.getContext("bitmaprenderer") on a (visible) canvas element. This context only provides functionality to replace the canvas's contents with the given ImageBitmap. A call to ImageBitmapRenderingContext.transferFromImageBitmap
() with the previously rendered and saved ImageBitmap from the OffscreenCanvas, will display the ImageBitmap on the canvas and transfer its ownership to the canvas. A single OffscreenCanvas may transfer frames into an arbitrary number of other ImageBitmapRenderingContext objects. Given these two <canvas> elements <canvas id="one"></canvas> <canvas id="two"></canvas> the following code will provid...
...And 4 more matches
PannerNode - Web APIs
dio source moves further from the listener. For distances greater than this the volume will be reduced based on rolloffFactor and distanceModel. PannerNode.rolloffFactor A double value describing how quickly the volume is reduced as the source moves away from the listener. This value is used by all distance models. Methods Inherits methods from its parent, AudioNode. PannerNode.setPosition
() Defines the position of the audio source relative to the listener (represented by an AudioListener object stored in the AudioContext.listener attribute.) PannerNode.setOrientation
() Defines the direction the audio source is playing in. PannerNode.setVelocity
() Defines the velocity vector of the audio source -- how fast it is moving and in what direction. In a previous version of the ...
...udio source -- how fast it is moving and in what direction. In a previous version of the specification, the PannerNode had a velocity that could pitch up or down AudioBufferSourceNodes connected downstream. This feature was not clearly specified and had a number of issues, so it was removed from the specification. Examples In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realist...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...And 4 more matches
PerformanceEntry.name - Web APIs
n URL PerformanceFrameTiming, PerformanceNavigationTiming frame, navigation The document's address. URL PerformanceResourceTiming resource The resolved URL of the requested resource. This value doesn't change even if the request is redirected. DOMString PerformanceMark mark The name used when the mark was created by calling performance.mark
(). ...
... URL PerformanceResourceTiming resource The resolved URL of the requested resource. This value doesn't change even if the request is redirected. DOMString PerformanceMark mark The name used when the mark was created by calling performance.mark
(). DOMString PerformanceMeasure measure name used when the measure was created by calling performance.measure
(). DOMString PerformancePaintTiming paint Either 'first-paint' or 'first-contentful-paint'. Example The following example shows the use of the name property. function run_PerformanceEntry
() { log("PerformanceEntry support ..."); if (performance.mark === undefined) { log("... performance.mark Not supported"); return; } // Create some performance entries v...
...DOMString PerformancePaintTiming paint Either 'first-paint' or 'first-contentful-paint'. Example The following example shows the use of the name property. function run_PerformanceEntry
() { log("PerformanceEntry support ..."); if (performance.mark === undefined) { log("... ...
...And 4 more matches
PerformanceEntry.startTime - Web APIs
The startTime property returns the first recorded timestamp of the performance entry. Note: This feature is available in Web Workers. The value returned by this property depends on the performance entry's type: "frame" - returns the timestamp when the frame was started. "mark" - returns the timestamp when the mark was created by a call to performance.mark
(). "measure" - returns the timestamp when the measure was created by a call to performance.measure
(). "navigation" - returns the timestamp with a value of "0". "resource" - returns the timestamp immediately before the browser starts fetching the resource. This property is Read only . Syntax entry.startTime; Return value A DOMHighResTimeStamp representing the first timestamp when the performance entry was created. Note: if t...
...e; Return value A DOMHighResTimeStamp representing the first timestamp when the performance entry was created. Note: if the performance entry has an entryType of "resource" (i.e. the entry is a PerformanceResourceTiming object), this property returns the PerformanceEntry.fetchStart timestamp. Example The following example shows the use of the startTime property. ...
...erformanceResourceTiming object), this property returns the PerformanceEntry.fetchStart timestamp. Example The following example shows the use of the startTime property. function run_PerformanceEntry
() { log("PerformanceEntry support ..."); if (performance.mark === undefined) { log("... ...
...And 4 more matches
Using the Performance API - Web APIs
Web performance interfaces are defined in a suite of standards. ...
...lues. The unit is milliseconds and should be accurate to 5 us (microseconds). However, if the browser is unable to provide a time value accurate to 5 microseconds (because of hardware or software constraints, for example), the browser can represent the value as a time in milliseconds accurate to a millisecond. ...
...milliseconds and should be accurate to 5 us (microseconds). However, if the browser is unable to provide a time value accurate to 5 microseconds (because of hardware or software constraints, for example), the browser can represent the value as a time in milliseconds accurate to a millisecond. The following code example shows the use of DOMHighResTimeStamp and the Performance.now
() method. ...
...And 4 more matches
Performance API - Web APIs
se cases including calculating frame-rates (potentially important in animations) and benchmarking (such as the time to load a resource). Since a platform's system clock is subject to various skews (such as NTP adjustments), the interfaces support a monotonic clock i.e. a clock that is always increasing. As such, the Performance API defines a DOMHighResTimeStamp type rather than using the Date.now
() interface. DOMHighResTimeStamp The DOMHighResTimeStamp type, as its name implies, represents a high resolution point in time. This type is a double and is used by the performance interfaces. The value could be a discrete point in time or the difference in time between two discrete points in time. The unit of DOMHighResTimeStamp is milliseconds and should be accurate to 5 us (microseconds). How...
...ime. The unit of DOMHighResTimeStamp is milliseconds and should be accurate to 5 us (microseconds). 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 ...
...nceEntry Provides methods and properties the encapsulate a single performance metric that is part of the performance timeline. PerformanceFrameTiming Provides methods and properties containing frame timing data about the browser's event loop. PerformanceMark An abstract interface for performance entries with an entry type of "mark". Entries of this type are created by calling performance.mark
() to add a named DOMHighResTimeStamp (the mark) to the browser's performance timeline. PerformanceMeasure An abstract interface for performance entries with an entry type of "measure". Entries of this type are created by calling performance.measure
() to add a namedDOMHighResTimeStamp (the measure) between two marks to the browser's performance timeline. PerformanceNavigationTiming Provides meth...
...And 4 more matches
RTCDataChannel - Web APIs
network channel which can be used for bidirectional peer-to-peer transfers of arbitrary data. Every data channel is associated with an RTCPeerConnection, and each peer connection can have up to a theoretical maximum of 65,534 data channels (the actual limit may vary from browser to browser). To create a data channel and ask a remote peer to join you, call the RTCPeerConnection's createDataChannel
() method. The peer being invited to exchange data receives a datachannel event (which has type RTCDataChannelEvent) to let it know the data channel has been added to the connection. PropertiesAlso inherits properties from: EventTargetbinaryType The property binaryType on the RTCDataChannel interface is a DOMString which specifies the type of JavaScript object which should be used to represent bin...
...dicates that the data channel has closed down.onclosing The RTCDataChannel.onclosing property is an EventHandler which specifies a function to be called by the browser when the closing event is received by the RTCDataChannel. This is a simple Event which indicates that the data channel is being closed, that is, RTCDataChannel transitions to "closing" state. For example, after RTCDataChannel.close
() was called but the underlying data transport might not have been closed yet.onerror The RTCDataChannel.onerror property is an EventHandler which specifies a function to be called when the error event is received. When an error occurs on the data channel, the function receives as input an ErrorEvent object describing the error which occurred.onmessage The RTCDataChannel.onmessage property stores...
... Events bufferedamountlow Sent to the channel's onbufferedamountlow event handler when the number of bytes of data in the outgoing data buffer f...
...And 4 more matches
ReadableStreamDefaultReader - Web APIs
The ReadableStreamDefaultReader interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (e.g. a fetch request). Constructor ReadableStreamDefaultReader
() Creates and returns a ReadableStreamDefaultReader object instance. Properties ReadableStreamDefaultReader.closed Read only Allows you to write code that responds to an end to the streaming process. Returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors. Methods ReadableStreamDefaultReader.cancel
() Cancels the stream, signaling a loss of interest in the stream by a consumer. The supplied reason argument will be given to the underlying source, which may or may not use it. ReadableStreamDefa...
...ng process. Returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors. Methods ReadableStreamDefaultReader.cancel
() Cancels the stream, signaling a loss of interest in the stream by a consumer. The supplied reason argument will be given to the underlying source, which may or may not use it. ReadableStreamDefaultReader.read
() Returns a promise providing access to the next chunk in the stream's internal queue. ReadableStreamDefaultReader.releaseLock
() Releases the reader's lock on the stream. Examples In the following example, an artifical Response is created to stream HTML fragments fetched from another resource to the browser. It demonstrates the usage of a ReadableStream in combination with a Uint8Array. fet...
...ableStreamDefaultReader.releaseLock
() Releases the reader's lock on the stream. Examples In the following example, an artifical Response is created to stream HTML fragments fetched from another resource to the browser. It demonstrates the usage of a ReadableStream in combination with a Uint8Array. ...
...And 4 more matches
Request - Web APIs
Properties Request.cache Read only Contains the cache mode of the request (e.g., default, reload, no-cache). Request.context Read only Contains the context of the request (e.g., audio, image, iframe, etc.) Request.credentials Read only Contains the credentials of the request (e.g., omit, same-origin, include). ...
...ferrer policy of the request (e.g., no-referrer). Request.url Read only Contains the URL of the request. Request implements Body, so it also inherits the following properties: body Read only A simple getter used to expose a ReadableStream of the body contents. bodyUsed Read only Stores a Boolean that declares whether the body has been used in a response yet. ...
...rits the following properties: body Read only A simple getter used to expose a ReadableStream of the body contents. bodyUsed Read only Stores a Boolean that declares whether the body has been used in a response yet. Methods Request.clone
() Creates a copy of the current Request object. Request implements Body, so it also has the following methods available to it: Body.arrayBuffer
() Returns a promise that resolves with an ArrayBuffer representation of the request body. ...
...And 4 more matches
Response - Web APIs
Properties Response.headers Read only The Headers object associated with the response. Response.ok Read only A boolean indicating whether the response was successful (status in the range 200-299) or not. ...
... Properties Response.headers Read only The Headers object associated with the response. Response.ok Read only A boolean indicating whether the response was successful (status in the range 200-299) or not. ...
... Properties Response.headers Read only The Headers object associated with the response. Response.ok Read only A boolean indicating whether the response was successful (status in the range 200-299) or not. ...
...And 4 more matches
SVGTextContentElement - Web APIs
nimatedLength reflecting the textLength attribute of the given element. SVGTextContentElement.lengthAdjust Read only An SVGAnimatedEnumeration reflecting the lengthAdjust attribute of the given element. The numeric type values represent one of the constant values above. Methods This interface also inherits methods from its parent, SVGGraphicsElement. ...
...c type values represent one of the constant values above. Methods This interface also inherits methods from its parent, SVGGraphicsElement. SVGTextContentElement.getNumberOfChars
() Returns a long representing the total number of addressable characters available for rendering within the current element, regardless of whether they will be rendered. SVGTextContentElement.getComputedTextLength
() Returns a float representing the computed length for the text within the element. SVGTextContentElement.getSubStringLength
() Returns a float representing the computed length of the formatted text advance distance for a substring of text within the element. Note that this method only accounts for the widths of the glyphs in the substring and any extra spacing inserted by the CSS 'letter-spacing...
...t representing the computed length of the formatted text advance distance for a substring of text within the element. Note that this method only accounts for the widths of the glyphs in the substring and any extra spacing inserted by the CSS 'letter-spacing' and 'word-spacing' properties. Visual spacing adjustments made by the 'x' attribute is ignored. SVGTextContentElement.getStartPositionOfChar
() Returns a DOMPoint representing the position of a typographic character after text layout has been performed. Note: In SVG 1.1 this method returned an SVGPoint. SVGTextContentElement.getEndPositionOfChar
() Returns a DOMPoint representing the trailing position of a typographic character after text layout has been performed. Note: In SVG 1.1 this method returned an SVGPoint. SVGTextConten...
...And 4 more matches
Screen Wake Lock API - Web APIs
n acquire the screen wake lock. There are plenty of use cases for keeping a screen on, including reading an ebook, map navigation, following a recipe, presenting to an audience, scanning a QR/barcode or applications that use voice or gesture control, rather than tactile input (the default way to keep a screen awake). You acquire a WakeLockSentinel object by calling the navigator.wakeLock.request
() Promise based method that resolves if the platform allows it. A request may be rejected for a number of reasons, including system settings (such as power save mode or low battery level) or if the document is not active or visible. The sentinel is attached to the underlying system wake lock. It can be released by the system, again if the battery power is too low or the document is not active or v...
...may be rejected for a number of reasons, including system settings (such as power save mode or low battery level) or if the document is not active or visible. The sentinel is attached to the underlying system wake lock. It can be released by the system, again if the battery power is too low or the document is not active or visible. It can also be released manually via the WakeLockSentinel.release
() method. It is good practice to store a reference to the sentinel object to control release later and also to reacquire the lock if need be. The Screen Wake Lock API should be used to keep the screen on to benefit usability. It's a good idea to show some feedback on the interface to show if wake lock is active and a way for the user to disable it if they wish. Screen Wake Lock API Interfaces ...
...questing a wake lock The following example demonstrates how to request a WakeLockSentinel object. The WakeLock.request method is Promise based and so we can create an asynchronous function, which in turn updates the UI to reflect the wake lock is active. ...
...And 4 more matches
ScriptProcessorNode - Web APIs
g the input audio data, one containing the processed output audio data. An event, implementing the AudioProcessingEvent interface, is sent to the object each time the input buffer contains new data, and the event handler terminates when it has filled the output buffer with data. The size of the input and output buffer are defined at the creation time, when the AudioContext.createScriptProcessor
() method is called (both are defined by AudioContext.createScriptProcessor
()'s bufferSize parameter). The buffer size must be a power of 2 between 256 and 16384, that is 256, 512, 1024, 2048, 4096, 8192 or 16384. Small numbers lower the latency, but large number may be necessary to avoid audio breakup and glitches. If the buffer size is not defined, which is recommended, the browser will pick one ...
...rpretation "speakers" Properties Inherits properties from its parent, AudioNode. ScriptProcessorNode.bufferSize Read only Returns an integer representing both the input and output buffer size. Its value can be a power of 2 value in the range 256-16384. Methods No specific methods; inherits methods from its parent, AudioNode. ...
...nts using addEventListener
() or by assigning an event listener to the oneventname property of this interface: audioprocess Fired when an input buffer of a ScriptProcessorNode is ready to be processed. Also available via the onaudioprocess event handler property. Examples The following example shows basic usage of a ScriptProcessorNode to take a track loaded via AudioContext.decodeAudioData
(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the AudioDestinationNode. For each channel and each sample frame, the scriptNode.onaudioprocess function takes the associated audioProcessingEvent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before s...
...And 4 more matches
Selection API - Web APIs
The Selection API provides functionality for reading and manipulating the range of text selected by the user. Concepts and usage To retrieve the current text range the user has selected, you can use the Window.getSelection
() or Document.getSelection
() method, storing the return value -- a Selection object -- in a variable for futher use. Once your selection is in a variable, you perform a variety of operations on it, for example copying the selection to a text string using Selection.toString
(), adding a range (as represented by a standard Range object) to the selection (or removing one) with Selection.addRange
()/Selection.removeRange
(), or changing the selection to be the entire contents of a DOM node using Selection.selectAllChildren
(). You can run code in response to the selection b...
... GlobalEventHandlers.onselectstart Represents the event handler that is called when a selectstart event is fired on the current object (i.e. ...
...run code in response to the selection being changed, or a new selection being started, using the GlobalEventHandlers.onselectionchange and GlobalEventHandlers.onselectstart event handlers. Selection API interfaces Selection Represents the range of text selected by the user or the current position of the caret. Extensions to other interfaces Window.getSelection
(), Document.getSelection
() Returns a Selection object representing the range of text selected by the user or the current position of the caret. Document.getSelection
() is basically an alias of Window.getSelection
(). GlobalEventHandlers.onselectstart Represents the event handler that is called when a selectstart event is fired on the current object (i.e. when a new range of text is about to be selected by the user). Glo...
...And 4 more matches
SharedWorkerGlobalScope - Web APIs
he 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. 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 on...
...ing the code to be called when the connect event is raised -- that is, when a MessagePort connection is opened between the associated SharedWorker and the main thread. Methods This interface inherits methods from the WorkerGlobalScope interface, and its parent EventTarget, and therefore implements methods from WindowTimers, WindowBase64, and WindowEventHandlers. SharedWorkerGlobalScope.close
() Discards any tasks queued in the SharedWorkerGlobalScope's event loop, effectively closing this particular scope. Inherited from WorkerGlobalScope WorkerGlobalScope.close
() Discards any tasks queued in the WorkerGlobalScope's event loop, effectively closing this particular scope. WorkerGlobalScope.dump
() Allows you to write a message to stdout -- i.e. in your terminal. This is the sa...
...tively closing this particular scope. Inherited from WorkerGlobalScope WorkerGlobalScope.close
() Discards any tasks queued in the WorkerGlobalScope's event loop, effectively closing this particular scope. WorkerGlobalScope.dump
() Allows you to write a message to stdout -- i.e. in your terminal. This is the same as Firefox's window.dump, but for workers. WorkerGlobalScope.importScripts
() Imports one or more scripts into the worker's scope. You can specify as many as you'd like, separated by commas. For example: importScripts('foo.js', 'bar.js'); Implemented from other places WindowBase64.atob
() Decodes a string of data which has been encoded using base-64 encoding. WindowBase64.btoa
() Creates a base-64 encoded ASCII string from a string of binary data. WindowTimers.clea...
...And 4 more matches
Storage - Web APIs
for example, the addition, modification, or deletion of stored data items. To manipulate, for instance, the session storage for a domain, a call to Window.sessionStorage is made; whereas for local storage the call is made to Window.localStorage. Properties Storage.length Read only Returns an integer representing the number of data items stored in the Storage object. Methods Storage.key
() When passed a number n, this method will return the name of the nth key in the storage. Storage.getItem
() When passed a key name, will return that key's value. Storage.setItem
() When passed a key name and value, will add that key to the storage, or update that key's value if it already exists. Storage.removeItem
() When passed a key name, will remove that key from the storage. Storage.c...
...en passed a number n, this method will return the name of the nth key in the storage. Storage.getItem
() When passed a key name, will return that key's value. Storage.setItem
() When passed a key name and value, will add that key to the storage, or update that key's value if it already exists. Storage.removeItem
() When passed a key name, will remove that key from the storage. Storage.clear
() When invoked, will empty all keys out of the storage. Examples Here we access a Storage object by calling localStorage. We first test whether the local storage contains data items using !localStorage.getItem('bgcolor'). If it does, we run a function called setStyles
() that grabs the data items using Storage.getItem
() and uses those values to update page styles. If it doesn't, we run another f...
...ty all keys out of the storage. Examples Here we access a Storage object by calling localStorage. We first test whether the local storage contains data items using !localStorage.getItem('bgcolor'). If it does, we run a function called setStyles
() that grabs the data items using Storage.getItem
() and uses those values to update page styles. If it doesn't, we run another function, populateStorage
(), which uses Storage.setItem
() to set the item values, then runs setStyles
(). ...
...And 4 more matches
URLSearchParams - Web APIs
The URLSearchParams interface defines utility methods to work with the query string of a URL. An object implementing URLSearchParams can directly be used in a for...of structure, for example the following two lines are equivalent: for (const [key, value] of mySearchParams) {} for (const [key, value] of mySearchParams.entries
()) {} Note: This feature is available in Web Workers. Constructor URLSearchParams
() Returns a URLSearchParams object instance. ...
... object implementing URLSearchParams can directly be used in a for...of structure, for example the following two lines are equivalent: for (const [key, value] of mySearchParams) {} for (const [key, value] of mySearchParams.entries
()) {} Note: This feature is available in Web Workers. Constructor URLSearchParams
() Returns a URLSearchParams object instance. Methods URLSearchParams.append
() Appends a specified key/value pair as a new search parameter. ...
...ample the following two lines are equivalent: for (const [key, value] of mySearchParams) {} for (const [key, value] of mySearchParams.entries
()) {} Note: This feature is available in Web Workers. Constructor URLSearchParams
() Returns a URLSearchParams object instance. Methods URLSearchParams.append
() Appends a specified key/value pair as a new search parameter. URLSearchParams.delete
() Deletes the given search parameter, and its associated value, from the list of all search parameters. URLSearchParams.entries
() Returns an iterator allowing iteration through all key/value pairs contained in this object. ...
...And 4 more matches
Hello vertex attributes - Web APIs
HTML5 canvas.</canvas> body { text-align : center; } canvas { width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } <script type="x-shader/x-vertex" id="vertex-shader"> #version 100 precision highp float; attribute float position; void main
() { gl_Position = vec4(position, 0.0, 0.0, 1.0); gl_PointSize = 64.0; } </script> <script type="x-shader/x-fragment" id="fragment-shader"> #version 100 precision mediump float; void main
() { gl_FragColor = vec4(0.18, 0.54, 0.34, 1.0); } </script> ;(function
(){ "use strict" window.addEventListener("load", setupWebGL, false); var gl, program; function setupWebGL (evt) { window.remov...
...script> <script type="x-shader/x-fragment" id="fragment-shader"> #version 100 precision mediump float; void main
() { gl_FragColor = vec4(0.18, 0.54, 0.34, 1.0); } </script> ;(function
(){ "use strict" window.addEventListener("load", setupWebGL, false); var gl, program; function setupWebGL (evt) { window.removeEventListener(evt.type, setupWebGL, false); if (!(gl = getRenderingContext
())) return; var source = document.querySelector("#vertex-shader").innerHTML; var vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader,source); gl.compileShader(vertexShader); source = document.querySelector("#fragment-shader").innerHTML var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader,source); gl.compileShader(fr...
...rySelector("#vertex-shader").innerHTML; var vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader,source); gl.compileShader(vertexShader); source = document.querySelector("#fragment-shader").innerHTML var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader,source); gl.compileShader(fragmentShader); program = gl.createProgram
(); gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); gl.detachShader(program, vertexShader); gl.detachShader(program, fragmentShader); gl.deleteShader(vertexShader); gl.deleteShader(fragmentShader); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { var linkErrLog = gl.getProgramInfoLog(program); cleanup
(); do...
...And 4 more matches
Web Locks API - Web APIs
tab could try to acquire a "my_net_db_sync" lock, but only one tab will succeed (the leader election pattern.) The API is used as follows: The lock is requested. Work is done while holding the lock in an asynchronous task. The lock is automatically released when the task completes. navigator.locks.request('my_resource', async lock => { // The lock has been acquired. await do_something
(); await do_something_else
(); // Now the lock will be released. }); While a lock is held, requests for the same lock from this execution context, or from other 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 shar...
...ask 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 when the callback returns, so usually the callback is an async function, which causes the lock to be released only when the async function has completely finished. The request
() method itself returns a promise which resolves once the lock has been released; within an async function, a script can await the call to make the asynchronous code flow linear. For example: await do_something_without_lock
(); // Request the lock. await navigator.locks.request('my_resource', async lock => { // The lock has been acquired. ...
...And 4 more matches
XMLHttpRequest.readyState - Web APIs
The XMLHttpRequest.readyState property returns the state an XMLHttpRequest client is in. An XHR client exists in one of the following states: Value State Description 0 UNSENT Client has been created. open
() not called yet. 1 OPENED open
() has been called. 2 HEADERS_RECEIVED send
() has been called, and headers and status are available. 3 LOADING Downloading; responseText holds partial data. 4 DONE The operation is complete. ...
... LOADING Response's body is being received. ...
... LOADING Response's body is being received. ...
...And 4 more matches
XRSystem - Web APIs
hat XRSession in hand, you can use it to interact with the Augmented Reality (AR) or Virtual Reality (VR) device. Properties While XRSystem directly offers no properties, it does inherit properties from its parent interface, EventTarget. Methods In addition to inheriting methods from its parent interface, EventTarget, the XRSystem interface includes the following methods: isSessionSupported
() Returns a promise which resolves to true if the browser supports the given XRSessionMode. Resolves to false if the specified mode isn't supported. requestSession
() Returns a promise that resolves to a new XRSession with the specified XRSessionMode. Events devicechange Sent when the set of available XR devices has changed. Also available using the ondevicechange event handler. Us...
...s devicechange Sent when the set of available XR devices has changed. Also available using the ondevicechange event handler. Usage notes Thsi interface was previously known as simply XR in earlier versions of the specification; if you see references to XR in code or documentation, simply replace that with XRSystem. ...
...Sent when the set of available XR devices has changed. Also available using the ondevicechange event handler. Usage notes Thsi interface was previously known as simply XR in earlier versions of the specification; if you see references to XR in code or documentation, simply replace that with XRSystem. Examples The following example shows how to use both isSessionSupported
() and requestSession
(). ...
...And 4 more matches
ARIA: button role - Accessibility
Enter key. In this case, the action is to add a new name to the list of names. Try the example by adding a name to the text box. The button will cause the name to be added to a list. ...
...e action is to add a new name to the list of names. Try the example by adding a name to the text box. The button will cause the name to be added to a list. ...
... // Don't add blank entries to the list. if(name.length > 0) { listItem = document.createElement('li'); listItem.appendChild(document.createTextNode(name)); // Add the new name to the list. let list = document.getElementById('nameList'); list.appendChild(listItem); } } To...
...And 4 more matches
@document - CSS: Cascading Style Sheets
of the document. It is designed primarily for user-defined style sheets, though it can be used on author-defined style sheets, too. @document url("https://www.example.com/") { h1 { color: green; } } Syntax An @document rule can specify one or more matching functions. If any of the functions apply to a given URL, the rule will take effect on that URL. The functions available are: url
(), which matches an exact URL. url-prefix
(), which matches if the document URL starts with the value provided. domain
(), which matches if the document URL is on the domain provided (or a subdomain of it). media-document
(), with the parameter of video, image, plugin or all. regexp
(), which matches if the document URL is matched by the regular expression provided. The expression must match the en...
...For example, a . ...
...For example, a . (period) matches any character in regular expressions. ...
...And 4 more matches
<easing-function> - CSS: Cascading Style Sheets
he animation to go farther than the final state, and then return. For some properties, such as left or right, this creates a kind of "bouncing" effect. However, certain properties will restrict the output if it goes outside an allowable range. For example, a color component greater than 255 or smaller than 0 will be clipped to the closest allowed value (255 and 0, respectively). Some cubic-bezier
() curves exhibit this property. Syntax There are three types of easing function: linear, cubic Bezier curves, and staircase functions. The value of an <easing-function> type describes the easing function using one of those three types. Easing functions CSS supports three kinds of easing functions: linear, the subset of the cubic Bezier curves that are functions, and staircase functions. The mos...
...ions: linear, the subset of the cubic Bezier curves that are functions, and staircase functions. The most useful of these functions are given a keyword that allows them to be easily referenced. The linear class of easing functions linear The animation moves from beginning to end at a constant rate. This keyword represents the easing function cubic-bezier(0.0, 0.0, 1.0, 1.0). The cubic-bezier
() class of easing functions The cubic-bezier
() functional notation defines a cubic Bezier curve. As these curves are continuous, they are often used to smooth down the start and end of the animation and are therefore sometimes called easing functions. A cubic Bezier curve is defined by four points P0, P1, P2, and P3. P0 and P3 are the start and the end of the curve and, in CSS these points are ...
... then slows down towards the end. This keyword represents the easing function cubic-bezier(0.42, 0.0, 0.58, 1.0). At the beginning, it behaves like the ease-in function; at the end, it is like the ease-out function. ease-out The animation starts abruptly, and then progressively slows down towards the end. This keyword represents the easing function cubic-bezier(0.0, 0.0, 0.58, 1.0). The steps
() class of easing functions The steps
() functional notation defines a step function dividing the domain of output values in equidistant steps.This subclass of step functions are sometimes also called staircase functions. Syntax steps(number_of_steps, direction) where: number_of_steps Is a strictly positive <integer>, representing the amount of equidistant treads composing the stepping func...
...And 4 more matches
EXSLT
"http://exslt.org/regular-expressions"> <xsl:template match="/"> ... <xsl:value-of select="regexp:replace(/root/@value, 'before', 'gi', 'AFTER')"/> ... </xsl:template> </xsl:stylesheet> Common The EXSLT Common package provides basic functions that expand upon the capabilities of XSLT. The namespace for the Common package is http://exslt.org/common. ...
...gular-expressions"> <xsl:template match="/"> ... <xsl:value-of select="regexp:replace(/root/@value, 'before', 'gi', 'AFTER')"/> ... </xsl:template> </xsl:stylesheet> Common The EXSLT Common package provides basic functions that expand upon the capabilities of XSLT. The namespace for the Common package is http://exslt.org/common. ...
... The EXSLT Common package provides basic functions that expand upon the capabilities of XSLT. The namespace for the Common package is http://exslt.org/common. Functions exsl:node-set
() exsl:object-type
() Math The EXSLT Math package provides functions for working with numeric values and comparing nodes. The namespace for the Math package is http://exslt.org/math. Functions math:highest
() math:lowest
() math:max
() math:min
() Regular expressions The EXSLT Regular Expressions package provides functions that allow testing, matching, and replacing text using JavaScript style regular expressions. ...
...And 4 more matches
<input type="file"> - HTML: Hypertext Markup Language
epresenting the path to the selected file. Events change and input Supported common attributes required Additional Attributes accept, capture, files, multiple IDL attributes files and value DOM interface HTMLInputElement Properties Properties that apply only to elements of type file Methods select
() Value A file input's value attribute contains a DOMString that represents the path to the selected file(s). If the user selected multiple files, the value represents the first file in the list of files they selected. The other files can be identified using the input's HTMLInputElement.files property. Note: If multiple files are selected, the string represents the first selected file. ...
... = 0; Note: opacity is used to hide the file input instead of visibility: hidden or display: none, because assistive technology interprets the latter two styles to mean the file input isn't interactive. Next, we add an event listener to the input to listen for changes to its selected value changes (in this case, when files are selected). The event listener invokes our custom updateImageDisplay
() function. input.addEventListener('change', updateImageDisplay); Whenever the updateImageDisplay
() function is invoked, we: Use a while loop to empty the previous contents of the preview <div>. Grab the FileList object that contains the information on all the selected files, and store it in a variable called curFiles. Check to see if no files were selected, by checking if curFiles.length is...
...e selected files, and store it in a variable called curFiles. Check to see if no files were selected, by checking if curFiles.length is equal to 0. If so, print a message into the preview <div> stating that no files have been selected. If files have been selected, we loop through each one, printing information about it into the preview <div>. ...
...And 4 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
d later. However, even though it has relatively broad support, it is still not standard and should not be used unless you have no alternative. Methods The following methods are provided by the HTMLInputElement interface which represents <input> elements in the DOM. Also available are those methods specified by the parent interfaces, HTMLElement, Element, Node, and EventTarget. checkValidity
() Immediately runs the validity check on the element, triggering the document to fire the invalid event at the element if the value isn't valid. reportValidity
() Returns true if the element's value passes validity checks; otherwise, returns false. select
() Selects the entire content of the <input> element, if the element's content is selectable. For elements with no selectable text content (su...
... event at the element if the value isn't valid. reportValidity
() Returns true if the element's value passes validity checks; otherwise, returns false. select
() Selects the entire content of the <input> element, if the element's content is selectable. For elements with no selectable text content (such as a visual color picker or calendar date input), this method does nothing. setCustomValidity
() Sets a custom message to display if the input element's value isn't valid. setRangeText
() Sets the contents of the specified range of characters in the input element to a given string. A selectMode parameter is available to allow controlling how the existing content is affected. setSelectionRange
() Selects the specified range of characters within a textual input element. Does nothing for inp...
... CSS Inputs, being replaced elements, have a few features not applicable to non form elements. ...
...And 4 more matches
contextmenu - HTML: Hypertext Markup Language
to use as the contextual menu for this element. A context menu is a menu that appears upon user interaction, such as a right-click. HTML5 now allows us to customize this menu. Here are some implementation examples, including nested menus. Example HTML <body contextmenu="share"> <menu type="context" id="share"> <menu label="share"> <menuitem label="Twitter" onclick="shareViaTwitter
()"></menuitem> <menuitem label="Facebook" onclick="shareViaFacebook
()"></menuitem> </menu> </menu> <ol> <li> Anywhere in the example you can share the page on Twitter and Facebook using the Share menu from your context menu. </li> <li contextmenu="changeFont" id="fontSizing"> On this specific list element, you can change the size of the text by usin...
...e the page on Twitter and Facebook using the Share menu from your context menu. ...
...r context menu. ...
...And 4 more matches
Feature-Policy - HTTP
ether the current document is allowed to gather information about the amount of light in the environment around the device through the AmbientLightSensor interface. autoplay Controls whether the current document is allowed to autoplay media requested through the HTMLMediaElement interface. When this policy is disabled and there were no user gestures, the Promise returned by HTMLMediaElement.play
() will reject with a DOMException. The autoplay attribute on <audio> and <video> elements will be ignored. battery Controls whether the use of the Battery Status API is allowed. When this policy is disabled, the Promise returned by Navigator.getBattery
() will reject with a NotAllowedError DOMException. camera Controls whether the current document is allowed to use video input devices. When this...
...on <audio> and <video> elements will be ignored. battery Controls whether the use of the Battery Status API is allowed. When this policy is disabled, the Promise returned by Navigator.getBattery
() will reject with a NotAllowedError DOMException. camera Controls whether the current document is allowed to use video input devices. When this policy is disabled, the Promise returned by getUserMedia
() will reject with a NotAllowedError DOMException. display-capture Controls whether or not the current document is permitted to use the getDisplayMedia
() method to capture screen contents. When this policy is disabled, the promise returned by getDisplayMedia
() will reject with a NotAllowedError if permission is not obtained to capture the display's contents. document-domain Controls whether the...
...hether the current document is allowed to set document.domain. When this policy is disabled, attempting to set document.domain will fail and cause a SecurityError DOMException to be be thrown. encrypted-media Controls whether the current document is allowed to use the Encrypted Media Extensions API (EME). When this policy is disabled, the Promise returned by Navigator.requestMediaKeySystemAccess
() will reject with a DOMException. execution-while-not-rendered Controls whether tasks should execute in frames while they're not being rendered (e.g. if an iframe is hidden or display: none). execution-while-out-of-viewport Controls whether tasks should execute in frames while they're outside of the visible viewport. fullscreen Controls whether the current document is allowed to use Eleme...
...And 4 more matches
Index - HTTP
embeds. 64 Feature-Policy: autoplay Directive, Feature Policy, Feature-Policy, HTTP, Reference, autoplay The HTTP Feature-Policy header autoplay directive controls whether the current document is allowed to autoplay media requested through the HTMLMediaElement interface. When this policy is enabled and there were no user gestures, the Promise returned by HTMLMediaElement.play
() will reject with a DOMException. The autoplay attribute on <audio> and <video> elements will be ignored. 65 Feature-Policy: camera Directive, Feature Policy, Feature-Policy, HTTP, Reference, camera The HTTP Feature-Policy header camera directive controls whether the current document is allowed to use video input devices. When this policy is enabled, the Promise returned by Me...
...Exception. The autoplay attribute on <audio> and <video> elements will be ignored. 65 Feature-Policy: camera Directive, Feature Policy, Feature-Policy, HTTP, Reference, camera The HTTP Feature-Policy header camera directive controls whether the current document is allowed to use video input devices. When this policy is enabled, the Promise returned by MediaDevices.getUserMedia
() will reject with a NotAllowedError. 66 Feature-Policy: encrypted-media Directive, EME, Feature Policy, Feature-Policy, HTTP, Reference The HTTP Feature-Policy header encrypted-media directive controls whether the current document is allowed to use the Encrypted Media Extensions API (EME). When this policy is enabled, the Promise returned by Navigator.requestMediaKeySystemAcce...
...ill reject with a NotAllowedError. 66 Feature-Policy: encrypted-media Directive, EME, Feature Policy, Feature-Policy, HTTP, Reference The HTTP Feature-Policy header encrypted-media directive controls whether the current document is allowed to use the Encrypted Media Extensions API (EME). When this policy is enabled, the Promise returned by Navigator.requestMediaKeySystemAccess
() will reject with a DOMException. 67 Feature-Policy: fullscreen Feature Policy, Feature-Policy, HTTP, fullscreen, header The HTTP Feature-Policy header fullscreen directive controls whether the current document is allowed to use Element.requestFullScreen
(). When this policy is enabled, the returned Promise rejects with a TypeError. 68 Feature-Policy: geolocation ...
...And 4 more matches
Grammar and types - JavaScript
efined let x; console.log('The value of x is ' + x); // The value of x is undefined console.log('The value of y is ' + y); // Uncaught ReferenceError: y is not defined let y; You can use undefined to determine whether a variable has a value. In the following code, the variable input is not assigned a value, and the if statement evaluates to true. var input; if (input === undefined) { doThis
(); } else { doThat
(); } The undefined value behaves as false when used in a boolean context. For example, the following code executes the function myFunction because 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 nul...
..."hoisted" (or "lifted") to the top of the function or statement. However, variables that are hoisted return a value of undefined. So even if you declare and initialize after you use or refer to this variable, it still returns undefined. ...
...r, variables that are hoisted return a value of undefined. So even if you declare and initialize after you use or refer to this variable, it still returns undefined. /** * Example 1 */ console.log(x === undefined); // true var x = 3; /** * Example 2 */ // will return a value of undefined var myvar = 'my value'; (function
() { console.log(myvar); // undefined var myvar = 'local value'; })
(); The above examples will be interpreted the same as: /** * Example 1 */ var x; console.log(x === undefined); // true x = 3; /** * Example 2 */ var myvar = 'my value'; (function
() { var myvar; console.log(myvar); // undefined myvar = 'local value'; })
(); Because of hoisting, all var statements in a function should be placed as near to the top of the function as possible. This best...
...And 4 more matches
Warning: expression closures are deprecated - JavaScript
wrong? The non-standard expression closure syntax (shorthand function syntax) is deprecated and shouldn't be used anymore. This syntax will be removed entirely in bug 1083458 and scripts using it will throw a SyntaxError then. Examples Deprecated syntax Expression closures omit curly braces or return statements from function declarations or from method definitions in objects. ...
...closure syntax (shorthand function syntax) is deprecated and shouldn't be used anymore. This syntax will be removed entirely in bug 1083458 and scripts using it will throw a SyntaxError then. Examples Deprecated syntax Expression closures omit curly braces or return statements from function declarations or from method definitions in objects. ...
...axError then. Examples Deprecated syntax Expression closures omit curly braces or return statements from function declarations or from method definitions in objects. var x = function
() 1; var obj = { count: function
() 1 }; Standard syntax To convert the non-standard expression closures syntax to standard ECMAScript syntax, you can add curly braces and return statements. ...
...And 4 more matches
BigInt - JavaScript
object that provides a way to represent whole numbers larger than 253 - 1, which is the largest number JavaScript can reliably represent with the Number primitive and represented by the Number.MAX_SAFE_INTEGER constant. BigInt can be used for arbitrarily large integers. Description A BigInt is created by appending n to the end of an integer literal -- 10n -- or by calling the function BigInt
(). const theBiggestInt = 9007199254740991n const alsoHuge = BigInt(9007199254740991) // ? 9007199254740991n const hugeString = BigInt("9007199254740991") // ? 9007199254740991n const hugeHex = BigInt("0x1fffffffffffff") // ? 9007199254740991n const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111") // ? 9007199254740991n BigInt is similar to Number in some ways, but ...
...ot 2.5n Comparisons A BigInt is not strictly equal to a Number, but it is loosely so: 0n === 0 // ? false 0n == 0 // ? true A Number and a BigInt may be compared as usual: 1n < 2 // ? true 2n > 1 // ? true 2 > 2 // ? false 2n > 2 // ? false 2n >= 2 // ? true They may be mixed in arrays and sorted: const mixed = [4n, 6, -12n, 10, 4, 0, 0n] // ? [4n, 6, -12n, 10, 4, 0, 0n] mixed.sort
() // default sorting behavior // ? [ -12n, 0, 0n, 10, 4n, 4, 6 ] mixed.sort((a, b) => a - b) // won't work since subtraction will not work with mixed types // TypeError: can't convert BigInt to number // sort with an appropriate numeric comparator mixed.sort((a, b) => (a < b) ? -1 : ((a > b) ? 1 : 0)) // ? [ -12n, 0, 0n, 4n, 4, 6, 10 ] Note that comparisons with Object-wrapped BigInts act as ...
...ean: via the Boolean function; when used with logical operators ||, &&, and !; or within a conditional test like an if statement. if (0n) { console.log('Hello from the if!') } else { console.log('Hello from the else!') } // ? "Hello from the else!" 0n || 12n // ? 12n 0n && 12n // ? 0n Boolean(0n) // ? false Boolean(12n) // ? true !12n // ? false !0n // ? true Constructor BigInt
() Creates a new bigint value. Static methods BigInt.asIntN
() Wraps a BigInt value to a signed integer between -2width-1 and 2width-1 - 1. BigInt.asUintN
() Wraps a BigInt value to an unsigned integer between 0 and 2width - 1. Instance methods BigInt.prototype.toLocaleString
() Returns a string with a language-sensitive representation of this number. Overrides the Object.prototype.toLoc...
...And 4 more matches
SharedArrayBuffer - JavaScript
Updating and synchronizing shared memory with atomic operations Shared memory can be created and updated simultaneously in workers or the main thread. Depending on the system (the CPU, the OS, the Browser) it can take a while until the change is propagated to all contexts. To synchronize, atomic operations are needed. ...
...ory with atomic operations Shared memory can be created and updated simultaneously in workers or the main thread. Depending on the system (the CPU, the OS, the Browser) it can take a while until the change is propagated to all contexts. To synchronize, atomic operations are needed. ...
...an be created and updated simultaneously in workers or the main thread. Depending on the system (the CPU, the OS, the Browser) it can take a while until the change is propagated to all contexts. To synchronize, atomic operations are needed. ...
...And 4 more matches
Symbol.toStringTag - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...prototype.toString.call([1, 2]); // "[object Array]" Object.prototype.toString.call(3); // "[object Number]" Object.prototype.toString.call(true); // "[object Boolean]" Object.prototype.toString.call(undefined); // "[object Undefined]" Object.prototype.toString.call(null); // "[object Null]" // ... ...
...pe.toString.call(3); // "[object Number]" Object.prototype.toString.call(true); // "[object Boolean]" Object.prototype.toString.call(undefined); // "[object Undefined]" Object.prototype.toString.call(null); // "[object Null]" // ... ...
...And 4 more matches
new.target - JavaScript
he 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
() // throws "Foo
() must be called with new" new.target in constructors In class constructors, new.target refers to the constructor that was directly invoked by new. This is also the case if the constructor is in a parent class and ...
... console.log('Foo instantiated with new') } new Foo
() // logs "Foo instantiated with new" Foo
() // throws "Foo
() must be called with new" new.target in constructors In class constructors, new.target refers to the constructor that was directly invoked by new. This is also the case if the constructor is in a parent class and was delegated from a child constructor. ...
...tiated with new" Foo
() // throws "Foo
() must be called with new" new.target in constructors In class constructors, new.target refers to the constructor that was directly invoked by new. This is also the case if the constructor is in a parent class and was delegated from a child constructor. ...
...And 4 more matches
Basic Transformations - SVG: Scalable Vector Graphics
/> <rect x="20" y="0" width="10" height="10" /> </g> </svg> All following transformations are summed up in an element's transform attribute. Transformations can be chained simply by concatenating them, separated by whitespace. Translation It may be necessary to move an element around, even though you can position it with the according attributes. ...
...slate
() transformation stands ready. <svg width="40" height="50" style="background-color:#bff;"> <rect x="0" y="0" width="10" height="10" transform="translate(30,40)" /> </svg> The example will render a rectangle, translated to the point (30,40) instead of (0,0). If the second value is not given, it is assumed to be 0. Rotation Rotating an element is quite a common task. Use the rotate
() transformation for this: <svg width="31" height="31"> <rect x="12" y="-10" width="20" height="20" transform="rotate(45)" /> </svg> This example shows a square that is rotated by 45 degrees. The value for rotate
() is given in degrees. Multiple transformations Transformations can be concatenated easily just by separating them with spaces. ...
...on task. Use the rotate
() transformation for this: <svg width="31" height="31"> <rect x="12" y="-10" width="20" height="20" transform="rotate(45)" /> </svg> This example shows a square that is rotated by 45 degrees. The value for rotate
() is given in degrees. Multiple transformations Transformations can be concatenated easily just by separating them with spaces. For example, translate
() and rotate
() are common used transformations. <svg width="40" height="50" style="background-color:#bff;"> <rect x="0" y="0" width="10" height="10" transform="translate(30,40) rotate(45)" /> </svg> This example shows again the small square shown above that this time is also rotated by 45 degrees. ...
...And 4 more matches
Web Components
. These can then be reused multiple times as the basis of a custom element's structure. The basic approach for implementing a web component generally looks something like this: Create a class in which you specify your web component functionality, using the ECMAScript 2015 class syntax (see Classes for more information). Register your new custom element using the CustomElementRegistry.define
() method, passing it the element name to be defined, the class or function in which its functionality is specified, and optionally, what element it inherits from. If required, attach a shadow DOM to the custom element using Element.attachShadow
() method. Add child elements, event listeners, etc., to the shadow DOM using regular DOM methods. If required, define an HTML template using <template> an...
...dow DOM to an element, add to the shadow DOM tree, style it, and more. Using templates and slots A guide showing how to define a reusable HTML structure using <template> and <slot> elements, and then use that structure inside your web components. Reference Custom elements CustomElementRegistry Contains functionality related to custom elements, most notably the CustomElementRegistry.define
() method used to register new custom elements so they can then be used in your document. Window.customElements Returns a reference to the CustomElementRegistry object. Life cycle callbacks Special callback functions defined inside the custom element's class definition, which affect its behavior: connectedCallback: Invoked when the custom element is first connected to the document's DOM. d...
...ment is moved to a new document. attributeChangedCallback: Invoked when one of the custom element's attributes is added, removed, or changed. Extensions for creating custom built-in elements The is global HTML attribute: Allows you to specify that a standard HTML element should behave like a registered custom built-in element. The "is" option of the Document.createElement
() method: Allows you to create an instance of a standard HTML element that behaves like a given registered custom built-in element. CSS pseudo-classes Pseudo-classes relating specifically to custom elements: :defined: Matches any element that is defined, including built in elements and custom elements defined with CustomElementRegistry.define
()). :host: Selects the shadow host of the sh...
...And 4 more matches
Basic Example - XSLT: Extensible Stylesheet Language Transformations
The .xsl file is then imported (xsltProcessor.importStylesheet(xslStylesheet)) and...
...The .xsl file is then imported (xsltProcessor.importStylesheet(xslStylesheet)) and the transformation run (xsltProcessor.transformToFragment(xmlDoc, docu...
...The .xsl file is then imported (xsltProcessor.importStylesheet(xslStylesheet)) and the transformation run (xsltProcessor.transformToFragment(xmlDoc, document)). This allows fetching of data after the page has been loade...
...And 4 more matches
Classes and Inheritance - Archive of obsolete content
perty the prototype of the newly created object: let shape = Shape(2, 3); Object.getPrototypeOf(shape) == Shape.prototype; // => true All instances of a class have the same prototype. This makes the prototype the perfect place to define properties that are shared between instances of the class. To illustrate this, let's add a member function to the class Shape: Shape.prototype.draw = function
() { throw Error("not yet implemented"); } let shape = Shape(2, 3); Shape.draw
(); // => Error: not yet implemented Inheritance and Constructors Suppose we want to create a new class, Circle, and inherit it from Shape. Since every Circle is also a Shape, the constructor for Shape must be called every time we call the constructor for Circle. Since JavaScript does not have native support for inh...
... use the above constructor to create instances of the class Circle: let circle = Circle(2, 3, 5); circle instanceof Circle; // => true circle.x; // => 2 circle.y; // => 3 circle.radius; // => 5 Inheritance and Prototypes There is a problem with the definition of Circle in the previous section that we have glossed over thus far. Consider the following: let circle = Circle(2, 3, 5); circle.draw
(); // => TypeError: circle.draw is not a function This is not quite right. The method draw is defined on instances of Shape, so we definitely want it to be defined on instances of Circle. The problem is that draw is defined on the prototype of Shape, but not on the prototype of Circle. We could of course copy every property from the prototype of Shape over to the prototype of Circle, but this is ...
...w to override the stub implementation of the method draw in Shape with a more specialized one in Circle. Recall that JavaScript returns the first property it finds when walking the prototype chain of an object from the bottom up. Consequently, overriding a method is as simple as providing a new definition on the prototype of the subclass: Circle.prototype.draw = function (ctx) { ctx.beginPath
(); ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false); ctx.fill
(); }; With this definition in place, we get: let shape = Shape(2, 3); shape.draw
(); // Error: not yet implemented let circle = Circle(2, 3, 5); circle.draw
(); // TypeError: ctx is not defined which is the behavior we were aiming for. Classes in the Add-on SDK We have shown how to emulate classical in...
...And 3 more matches
io/text-streams - Archive of obsolete content
Experimental Provides streams for reading and writing text. ...
... Experimental Provides streams for reading and writing text. ...
...f (fileIO.exists(filename)) { var TextReader = fileIO.open(filename, "r"); if (!TextReader.closed) { text = TextReader.read
(); TextReader.close
(); } } return text; } function writeTextToFile(text, filename) { var fileIO = require("sdk/io/file"); var TextWriter = fileIO.open(filename, "w"); if (!TextWriter.closed) { TextWriter.write(text); TextWriter.close
(); } } Globals Constructors TextReader(inputStream, charset) Creates a buffered input stream that reads text from a backing stream using a given text encoding. You can also create TextReader objects using io/file's open
() function. Parameters inputStream : stream The backing stream, an nsIInputStream. It must already be opened. charset : string inputStream is expected to be in the chara...
...And 3 more matches
system/child_process - Archive of obsolete content
Experimental An implementation of the node.js child_process API. This module enables you to execute a child program in a new process. Since it emulates the node.js child_process API, it's not documented separately here. ...
... Experimental An implementation of the node.js child_process API. This module enables you to execute a child program in a new process. Since it emulates the node.js child_process API, it's not documented separately here. ...
...tion of the node.js child_process API. This module enables you to execute a child program in a new process. Since it emulates the node.js child_process API, it's not documented separately here. However, there are a few differences to be aware of: you need to require
() the module using require("sdk/system/child_process") fork
() is not supported gid and uid are not supported in node.js, spawn
() and exec
() inherit the environment variables from the parent process, by default. ...
...And 3 more matches
window/utils - Archive of obsolete content
Functions for working with browser windows. Usage Private windows With this module your add-on will see private browser windows even if it has not explicitly opted into private browsing, so you need to take care not to store any user data derived from private browser windows. The exception is the windows
() function which returns an array of currently opened windows. Private windows will not be included in this list if your add-on has not opted into private browsing. To learn more about private windows, how to opt into private browsing, and how to support private browsing, refer to the documentation for the private-browsing module. Globals Functions getMostRecentBrowserWindow
() Get the topmost browser window, as an nsIDOMWindow instance. Returns nsIDOMWindow: the topmost bro...
...ied window's outer window. This function wraps nsIDOMWindowUtils.outerWindowID. Parameters window : nsIDOMWindow The window whose outer window we are interested in. Returns ID: the outer window's ID. ...
...ils.getMostRecentBrowserWindow
(); active instanceof Ci.nsIXULWindow // => false utils.getXULWindow(active) instanceof Ci.nsIXULWindow // => true Parameters window : nsIDOMWindow Returns nsIXULWindow getBaseWindow(window) Returns the nsIBaseWindow for the given nsIDOMWindow: var { Ci } = require('chrome'); var utils = require('sdk/window/utils'); var active = utils.getMostRecentBrowserWindow
(); active instanceof Ci.nsIBaseWindow // => false utils.getBaseWindow(active) instanceof Ci.nsIBaseWindow // => true Parameters window : nsIDOMWindow Returns nsIBaseWindow getToplevelWindow(window) Returns the toplevel nsIDOMWindow for the given child nsIDOMWindow: var { Ci } = require('chrome'); var utils = require('sdk/window/utils'); var browserWindow = utils.getMostRecentBrowserWindow
();...
...And 3 more matches
HTML to DOM - Archive of obsolete content
n the current page, then parsing the HTML fragment and attaching that fragment to the <div>. The <div> is returned, and it is never actually appended to the current page. ...
...erInfo').innerHTML); To parse a complete HTML page, load it into an iframe whose type is content (not chrome). See Using a hidden iframe element to parse HTML to a window's DOM below. Parsing Complete HTML to DOM Loading an HTML document seems much simpler if it's loaded using the XMLHttpRequest object. ...
...rame.addEventListener("load", function (event) { // the document of the HTML in the DOM var doc = event.originalTarget; // skip blank page or frame if (doc.location.href == "about:blank" || doc.defaultView.frameElement) return; // do something with the DOM of doc alert(doc.location.href); // when done remove frame or set location "about:blank" setTimeout(function
(){ var frame = document.getElementById("sample-frame"); // remove frame // frame.destroy
(); // if using browser element instead of iframe frame.parentNode.removeChild(frame); // or set location "about:blank" // frame.contentDocument.location.href = "about:blank"; },10); }, true); } // load a page frame.contentDocument.location.href = "http://www.mozill...
...And 3 more matches
Search Extension Tutorial (Draft) - Archive of obsolete content
ata, reason) { // No need to do this if this is app shutdown. if (reason == APP_SHUTDOWN) return; // Reset our changes if the values have not been changed // in the meantime. for (let [name, [origValue, value]] in Iterator(savedPrefs)) { if (defaultPrefs.getCharPref(name) == value) defaultPrefs.setCharPref(name, origValue); } } function install
() {} function uninstall
() {} Changing the Default Search Engine This change comes in two parts: 1) installing a new search engine (and removing it when your extension is disabled), and 2) setting it as a default (and restoring the previous default when your extension is uninstalled). Adding a New Search Engine Search engines may be added either directly via an API call, or indirectly via an XML de...
...bled. if (reason == ADDON_UNINSTALL || reason == ADDON_DISABLE) { let engine = Services.search.getEngineByName(ENGINE_DETAILS.name); // Only remove the engine if it appears to be the same one we // added. if (engine && engine.getSubmission("_searchTerms_").uri.spec == ENGINE_DETAILS.url) Services.search.removeEngine(engine); } } function install
() {} function uninstall
() {} The complex method requires two files, an XML search description file and a JavaScript file to register the engine. In non-restartless extensions, the XML search description may instead simply be placed in the searchplugins/ directory in the root of your XPI, as em:unpack is specified in your install.rdf file. As above, install and uninstall code is only provided for r...
...ENGINE_DETAILS = { name: "Example Engine", url: "https://www.example.com/search?q=_searchTerms_&source=search-box" }; // Get the engine URL based on our URL. const ENGINE_URL = "chrome://example-engine/content/search.xml"; // Keep track of whether this is the first run. var firstRun = false; // Decide whether to select the search engine. var selectSearch = false; function removeObserver
() { try { Services.obs.removeObserver(searchObserver, ENGINE_ADDED); } // If we've already removed this observer, ignore the error. catch (e) {} } // Observer called after our engine has been successfully added function searchObserver(engine, topic, data) { if (data != "engine-added") return; engine.QueryInterface(Ci.nsISearchEngine); if (engine.name ==...
...And 3 more matches
Localizing an extension - Archive of obsolete content
tually include the name of the localization to use. The Chrome Registry resolves the URIs based on the user's current locale setting and the data you provide in your Chrome manifest. Then we simply replace each text string in our XUL files with the corresponding entity. For example, in stockwatcher2.xul, we change this line: <menuitem label="Refresh Now" oncommand="StockWatcher.refreshInformation
()"/> to <menuitem label="&menu_refresh_now.label;" oncommand="StockWatcher.refreshInformation
()"/> Do this for every string used in each XUL file. Update the chrome manifest To let Firefox know about the locale files, we need to make a revision to our chrome.manifest file, adding one line for each localization: locale stockwatcher2 en-US chrome/locale/ This instructs Firefox that the en-US loc...
...m the stockwatcher2.properties file we've already created. Note: You should use a unique ID for each string bundle element for each file you use to avoid conflicts. (e.g. id="myextensionname-filename") Update the JavaScript code Now we're ready to revise the JavaScript code to load the strings from the string bundle instead of using literal strings. ...
...ote: You should use a unique ID for each string bundle element for each file you use to avoid conflicts. (e.g. id="myextensionname-filename") Update the JavaScript code Now we're ready to revise the JavaScript code to load the strings from the string bundle instead of using literal strings. ...
...And 3 more matches
Dehydra Function Reference - Archive of obsolete content
lass member functions. decl is a Variable Type object representing the function being processed body is an array of {loc:, statements:array of Variable Types} representing an outline of the function stripped down to variables, function calls and assignments. process_decl(decl) process_decl is called for every global variable, function, or template declaration. decl is a variable type input_end
() Called once at the end of the C++ source file before the compiler quits. This is useful for finalizing analyses. Builtin functions The following functions are provided by dehydra and may be called by the user: print(msg) Print a string to stdout (or stderr if the compiler is piping output). If the current callback is associated with a particular location, the location will be printed first. msg ...
...alizing analyses. Builtin functions The following functions are provided by dehydra and may be called by the user: print(msg) Print a string to stdout (or stderr if the compiler is piping output). If the current callback is associated with a particular location, the location will be printed first. msg is a string to output To customize the location info printed set this._loc before calling print
() include(file [, namespace]) Include a javascript file into a namespace. file is a string representing the file to include Optional: namespace is an object to include the file into. The default namespace is this The directories in sys.include_path are searched for the file, and the current working directory is searched last. Includes are guarded so a file is only included once and subsequent inc...
...s into the Map object require({version:, strict:, werror:, gczeal:}) require is used to set runtime execution flags. It also returns the current values of these flags. require supports optional named arguments via JavaScript object where each parameter is a property. If a property is not specified then it will not be passed to the runtime. ...
...And 3 more matches
Block and Line Layout Cheat Sheet - Archive of obsolete content
nsFrame The base class for all frames. mFlags Flags set on the frame to indicate its state. These flags can be grouped into two categories: flags which affect all frames ("public" flags), and flags that are reserved for an individual frame's private use ("private" flags). NS_FRAME_IN_REFLOW This bit is set when the frame is being actively being reflowed. By default it is set in WillReflow
(), and unset in DidReflow
(). Many frames' Reflow
() method verifies that the bit is set with an assertion. NS_FRAME_FIRST_REFLOW This flag is set on a newly created frame, and later cleared by the frame's Reflow
() method when the frame has had its initial reflow. NS_FRAME_SYNC_FRAME_AND_VIEW NS_FRAME_OUTSIDE_CHILDREN This flag is set if the combined area of a frame's children extend past the f...
...RENCE NS_FRAME_REPLACED_ELEMENT NS_FRAME_GENERATED_CONTENT NS_FRAME_HAS_LOADED_IMAGES NS_FRAME_OUT_OF_FLOW NS_FRAME_SELECTED_CONTENT NS_FRAME_IS_DIRTY NS_FRAME_IS_UNFLOWABLE An unflowable frame is an error condition; for example, due to system limitations. Currently, the only way to get an unflowable frame is to have a frame tree that is "too deep". (See nsFrame::IsFrameTreeTooDeep
().) NS_FRAME_HAS_DIRTY_CHILDREN NS_FRAME_HAS_VIEW NS_FRAME_INDEPENDENT_SELECTION NS_FRAME_IS_SPECIAL nsBlockFrame mFlags These flags are the private flags that are meaningful to block frames. NS_BLOCK_SHRINK_WRAP Causes the block to "shrink-wrap" around its content. This means the block will determine its children's width and make its content area that wide. Finally, it will add pad...
... to determine the final width. Is this where the "tending towards zero width" stuff comes in? NS_BLOCK_NO_AUTO_MARGINS NS_BLOCK_MARGIN_ROOT Indicates that this is a frame from which child margins can be calculated. The absence of this flag implies that child margin calculations should ignore the frame and look further up the parent chain. Used in nsBlockReflowContext::ComputeCollapsedTopMargin
(). This flag causes the nsBlockReflowState's constructor to set the BRS_ISTOPMARGINROOT and BRS_ISBOTTOMMARGINROOT flags. This is set by default for document, table cell inner, and absolutely positioned wrapper frames. NS_BLOCK_SPACE_MGR This indicates that a block frame should create its own space manager. This is required by each block frame that can contain floaters: the space manager is used ...
...And 3 more matches
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
stener, which corresponds to a docshell and handles most of the data types that Mozilla handles internally. nsIExternalHelperAppService If we can't do anything else with a load, we give it to the nsIExternalHelperAppService and let it look for a helper app, put up the "what do I do now?" dialog, and so forth. ...
...sIExternalHelperAppService If we can't do anything else with a load, we give it to the nsIExternalHelperAppService and let it look for a helper app, put up the "what do I do now?" dialog, and so forth. ...
...21,418,821,455,629,455,629,484,575,484" href="#CategoryManager" shape="poly"> <area alt="(12)" coords="539,133,583,163" href="#stream-converter"> <area alt="(11)" coords="485,133,537,163" href="#ContentHandler"> <area alt="(9)" coords="445,132,484,165" href="#nsDocumentOpenInfo::DispatchContent"> <area alt="(8)" coords="405,133,439,162" href="#OnStartRequest-innards"> <area alt="(7) OnStartRequest
()" coords="639,129,703,129,703,165,833,165,833,204,639,204" href="#OnStartRequest" shape="poly"> <area alt="(6) AsyncOpen
()" coords="637,121,709,121,709,96,783,96,783,58,637,58" href="#AsyncOpen" shape="poly"> <area alt="(5) Open
()" coords="311,306,432,371" href="#Open"> <area alt="(4)" coords="90,384,127,417" href="#openURI-innards"> <area alt="(0) RegisterContentListener
()" coords="37,474,346,474...
...And 3 more matches
confirm - Archive of obsolete content
ys a modal confirmation dialog. Method of Install object Syntax int confirm( String aText ); int confirm( String aText, String aDialogTitle, Number aButtonFlags, String aButton0Title, String aButton1Title, String aButton2Title, String aCheckMsg, Object aCheckState ); Parameters The second, extended confirm
() method is supported starting with Gecko 1.8. It accepts any number of parameters up to 8. Previous Gecko versions only support the first, one-parameter method and will throw an error on occuring the extended form. See the notes at the end of this document for a safe way to implement a fallback. aText The string to be displayed in the confirmation dialog. This string is typically in...
...el' buttons. If you leave out aButtonFlags, this is the default. STD_YES_NO_BUTTONS: Use this instead of the constants above to have standard 'Yes' and 'No' buttons. Warning: do not make any assumptions on the button placement - the underlying implementation can freely decide where each of the three buttons is placed. The following examples show the result of calling confirm
() with three buttons 0='A', 1='B' and 2='C'. Firefox on Linux Mozilla Application Suite on Win32 It is therefore recommended to only use two buttons wherever possible, and to keep in mind that button 1 has the same return value as "window closed" (see below). aButton0Title Custom title for button 0. aButton1Title Custom title for button 1. ...
... well", check); Returns The return value is an integer indicating which button the user selected: Value Button 0 'Cancel' or button 1. ...
...And 3 more matches
Dynamically modifying XUL-based user interface - Archive of obsolete content
UL applications JavaScript defines the behavior, using DOM APIs to access the XUL document. So what are the Document Object Model APIs? They are the interfaces that are used in any interaction of a script and a document. If you have ever written a script that interacts with a XUL (or HTML) document, you have already used DOM calls. The most well known DOM method is probably document.getElementById
(), which returns an element, given its id. You may also have used other calls, such as element.setAttribute
(), or, if you wrote an extension, the addEventListener
() method. All of these are defined in DOM. There are also DOM methods that create, move, or delete elements from a document. They will be demonstrated in a later section. Right now, let's learn what a document is. What is a document? A ...
... window, when there is an <iframe>, <browser>, or a <tabbrowser> element. You must be sure to always manipulate the correct document. (Read more about this in Working with windows in chrome code.) When your script is included using a <script> tag, the document property references the DOM document that includes the script. Examples: Using DOM methods This section demonstrates the use of appendChild
(), createElement
(), insertBefore
(), and removeChild
() DOM methods. Removing all children of an element This example removes all children of an element with id=someElement from the current document, by calling removeChild
() method to remove the first child, until there are no children remaining. Note, that hasChildNodes
() and firstChild are also part of the DOM API. var element = document.getElement...
...
() DOM methods. Removing all children of an element This example removes all children of an element with id=someElement from the current document, by calling removeChild
() method to remove the first child, until there are no children remaining. Note, that hasChildNodes
() and firstChild are also part of the DOM API. var element = document.getElementById("someElement"); while(element.hasChildNodes
()){ element.removeChild(element.firstChild); } Inserting menu items to a menu This example adds two new menu items to a <menupopup>: to the start and to the end of it. It uses document.createElementNS
() method to create the items, and insertBefore
() with appendChild
() to insert the created xml elements within the document. ...
...And 3 more matches
Moving, Copying and Deleting Files - Archive of obsolete content
help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. There are several methods of the nsIFile object which may be used to move and copy files on disk. nsIFile.copyTo
() is used to copy a file, while nsIFile.moveTo
() is used to move files. nsIFile.remove
() may be used to delete a file. Copying a File nsIFile.copyTo
() is used to copy files or directories, and should be called on the source file to copy. This method takes two arguments, the first is the destination directory in which to copy the file to, and the second argument is the new name of the file, if you...
...me", "source.txt"); var destination = IO.newFile("Desktop", ""); file.copyTo(destination, "destination.txt"); This example copies a file called 'source.txt' within the user's home directory to the desktop. In addition, the file is renamed to 'destination.txt'. Two file objects are created, the first is the file to copy, and the second is the directory in which to copy the file to. nsIFile.copyTo
() of the former is called, passing the latter as the first argument to nsIFile.copyTo
(). Naturally, the destination must be a directory or an error will occur. In this case, we assume that 'source.txt' is a file. If the item to copy is a directory, it can be copied in the same manner as above without changes. This allows an entire directory and its contents to be copied from one location to anothe...
...be copied from one location to another. You might use this to make a backup of a directory of files for instance. var file = IO.newFile("Home", "importantData"); var destination = IO.newFile("Desktop", ""); destination.append("backups"); file.copyTo(destination, ""); This example copies an item called 'importantData' into a directory called 'backups' within the desktop directory. nsIFile.append
() is used to retrieve the 'backups' subdirectory. This method is used to navigate into subdirectories. For more information about nsIFile.append
(), see Working with Directories. In this last example, the destination filename is set to an empty string. This causes the item to be copied without changing its name. This will be the usual behaviour when copying to a different directory, but you would w...
...And 3 more matches
How to implement a custom XUL query processor component - Archive of obsolete content
/xul-query-processor;1?name=xxx", where the xxx is the querytype used in the XUL template block. ...
... this._id = Math.random(100000).toString
(); } TemplateResult.prototype = { QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIXULTemplateResult]), // private storage _data: null, // right now our results are flat lists, so no containing/recursion take place isContainer: false, isEmpty: true, mayProcessChildren: false, resource: null, type: "simple-item", get id
() { return this._id; }, // return the value of that bound variable such as ?name getBindingFor: function(aVar) { // strip off the ? ...
... ruleMatched: function(aQuery, aRuleNode) { }, // the output for a result has been removed and the result is no longer being ...
...And 3 more matches
Adding Methods to XBL-defined Elements - Archive of obsolete content
<< PreviousNext >> Next, we'll find out how to add custom methods to XBL-defined elements. Methods In addition to adding script properties to the XBL-defined element, you can also add methods. These methods can be called from a script. Methods are the functions of objects, such as Window interface's open
() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. If the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">Window.open
(). You can define custom methods for your elements using the method element. The general syntax of methods is as follows: <implementation> <method name="method-name"> <parameter name="parameter-name1"/> <parameter name="parameter-...
...uage, and JavaScript is a non-typed language, you do not need to specify the types of the parameters. However, in the future, other languages may be used with XBL. Methods are only available to call after the page is rendered, which may cause problems if using createElement. For example, the following code will probably fail: var element = document.createElement("my_element"); element.getMaximum
() // this will fail By the way, it is safe to call methods from the constructor, other methods on the object and event handlers. Accessing the Anonymous Content There may be times when you want to modify some aspect of the elements defined in the content element, either from a method body or elsewhere. These elements are created anonymously and are not accessible from the regular DOM functions. ...
...it. However, there is a special way of getting this anonymous content. Elements with an XBL behavior attached to them have a special property which holds an array of the anonymous child elements inside it. Each element of the array stores each direct child element of the XBL-defined element. This special property cannot be accessed directly. Instead, you must call the document's getAnonymousNodes
() method: var value=document.getAnonymousNodes(element); Here, 'element' should be set to a reference to the element that you want to get the anonymous content of. The function returns an array of elements, which is the anonymous content. To get elements below that, you can use the regular DOM functions because they aren't hidden. Note that it is possible for an XBL-bound element to be placed ins...
...And 3 more matches
Creating Dialogs - Archive of obsolete content
<< PreviousNext >> A XUL application will often require dialogs to be displayed. This section describes how one might construct them. Creating a Dialog The openDialog
() function is used to open a dialog, and is related to open
(). This function differs from open
() in several ways. It displays a dialog instead of a window, which implies that it is asking something of the user. It also has subtle differences in the way it works and appears to the user. These differences will vary depending on the platform the application is running on. In addition, the openDialog
() function can take additional arguments beyond the first three. These arguments are passed to the new dialog and placed in an array stored in the new window's arguments property. You can pass as many arguments as yo...
... to pass values to the new window. You can pass values back from the opened window to the original window in one of two ways. First, you could use the window.opener property which holds the window that opened the dialog. Second, you could pass a function or object as one of the arguments when creating the dialog, then call that function or modify the object in the opened dialog. Note: openDialog
() requires UniversalBrowserWrite privilege. This means it will not work on remote sites; for those, use window.open
() instead. The Dialog Element The dialog element should be used in place of the window element when creating a dialog. It provides the useful ability to construct up to four buttons along the bottom of the dialog forOK,Cancel, and so on. You do not need to include the XUL for each ...
...ry because different platforms have a specific order in which the buttons appear. Example Dialog Source View <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/global.css" type="text/css"?> <dialog id="donothing" title="Dialog example" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" buttons="accept,cancel" ondialogaccept="return doOK
();" ondialogcancel="return doCancel
();"> <script> function doOK
(){ alert("You pressed OK!"); return true; } function doCancel
(){ alert("You pressed Cancel!"); return true; } </script> <description value="Select a button"/> </dialog> You may place any elements that you wish in a dialog. The dialog element has some additional attributes that windows do not have. The buttons attr...
...And 3 more matches
Styling a Tree - Archive of obsolete content
ne additional property, the id of the column or column the cell is in will be set. Setting Properties for the RDF-built Trees For RDF-built trees, you can use the same syntax. However, you will often set the properties based on values in the datasource. ...
... the id of the column or column the cell is in will be set. Setting Properties for the RDF-built Trees For RDF-built trees, you can use the same syntax. However, you will often set the properties based on values in the datasource. ...
... column the cell is in will be set. Setting Properties for the RDF-built Trees For RDF-built trees, you can use the same syntax. However, you will often set the properties based on values in the datasource. Setting Properties for the Custom View For trees with a custom view script, you can set properties by supplying the functions getRowProperties
(), getColumnProperties
() and getCellProperties
() in the view. These return information about an individual row, column and cell. Arguments to these functions indicate which row and/or column. Prior to Gecko 22 the last argument to each of these functions is a properties list which the view is expected to fill with a list of properties. The function getColumnProperties
() also supplies the corresponding treecol element for the column. getRowPro...
...And 3 more matches
NPN_DestroyStream - Archive of obsolete content
in to the browser. NPRES_USER_BREAK: Plug-in is terminating the stream due to a user request. NPRES_NETWORK_ERR: Stream failed due to network problems. Returns If successful, the function returns NPERR_NO_ERROR. If unsuccessful, the plug-in is not loaded and the function returns an error code. ...
...ork problems. Returns If successful, the function returns NPERR_NO_ERROR. If unsuccessful, the plug-in is not loaded and the function returns an error code. For possible values, see Error Codes. Description The plug-in calls the NPN_DestroyStream
() function to close and delete a stream. ...
...R_NO_ERROR. If unsuccessful, the plug-in is not loaded and the function returns an error code. For possible values, see Error Codes. Description The plug-in calls the NPN_DestroyStream
() function to close and delete a stream. ...
...And 3 more matches
NPN_ForceRedraw - Archive of obsolete content
valid areas. Note: As of Firefox 4, this function no longer has any effect when running with separate plugin processes. Syntax #include <npapi.h> void NPN_ForceRedraw(NPP instance); Parameters The function has the following parameters: instance Plug-in instance for which the function forces redrawing. ...
...irefox 4, this function no longer has any effect when running with separate plugin processes. Syntax #include <npapi.h> void NPN_ForceRedraw(NPP instance); Parameters The function has the following parameters: instance Plug-in instance for which the function forces redrawing. ...
...any effect when running with separate plugin processes. Syntax #include <npapi.h> void NPN_ForceRedraw(NPP instance); Parameters The function has the following parameters: instance Plug-in instance for which the function forces redrawing. ...
...And 3 more matches
NPVariant - Archive of obsolete content
ype NPVariantType undefined NPVariantType_Void null NPVariantType_Null boolean NPVariantType_Bool number NPVariantType_Int32 or NPVariantType_Double string NPVariantType_String All other types NPVariantType_Object Functions NPN_ReleaseVariantValue
() NPN_GetStringIdentifier
() NPN_GetStringIdentifiers
() NPN_GetIntIdentifier
() NPN_IdentifierIsString
() NPN_UTF8FromIdentifier
() NPN_IntFromIdentifier
() Macros Plugin developers are not expected to directly manipulate or access the members of the NPVariant instance, instead, the function NPN_ReleaseVariantValue
(), and the following macros are provided: NPVARIANT_IS_VOID
() Evaluat...
...tIntIdentifier
() NPN_IdentifierIsString
() NPN_UTF8FromIdentifier
() NPN_IntFromIdentifier
() Macros Plugin developers are not expected to directly manipulate or access the members of the NPVariant instance, instead, the function NPN_ReleaseVariantValue
(), and the following macros are provided: NPVARIANT_IS_VOID
() Evaluates to true if v is of type NPVariantType_Void. NPVARIANT_IS_NULL
() Evaluates to true if v is of type NPVariantType_Null. NPVARIANT_IS_BOOLEAN
() Evaluates to true if v is of type NPVariantType_Bool. NPVARIANT_IS_INT32
() Evaluates to true if v is of type NPVariantType_Int32. NPVARIANT_IS_DOUBLE
() Evaluates to true if v is of type NPVariantType_Double. NPVARIANT_IS_STRING
() Evaluates to true if v is of type NPVariantType_String. NPVARIANT_IS_OBJ...
...Evaluates to true if v is of type NPVariantType_Null. NPVARIANT_IS_BOOLEAN
() Evaluates to true if v is of type NPVariantType_Bool. NPVARIANT_IS_INT32
() Evaluates to true if v is of type NPVariantType_Int32. NPVARIANT_IS_DOUBLE
() Evaluates to true if v is of type NPVariantType_Double. NPVARIANT_IS_STRING
() Evaluates to true if v is of type NPVariantType_String. NPVARIANT_IS_OBJECT
() Evaluates to true if v is of type NPVariantType_Object. NPVARIANT_TO_BOOLEAN
() Extracts the boolean value from v. NPVARIANT_TO_INT32
() Extracts a signed 32-bit integer value from v. NPVARIANT_TO_DOUBLE
() Extracts a double precision floating point value from v. NPVARIANT_TO_STRING
() Extracts the NPString value from v. NPVARIANT_TO_OBJECT
() Extracts the NPObject value from v. ...
...And 3 more matches
Using IO Timeout And Interrupt On NT - Archive of obsolete content
tions. NSPR IO on NT The IO model of NSPR 2.0 is synchronous and blocking. A thread calling an IO function is blocked until the IO operation finishes, either due to a successful IO completion or an error. If the IO operation cannot complete before the specified timeout, the IO function returns with <tt>PR_IO_TIMEOUT_ERROR</tt>. If the thread gets interrupted by another thread's <tt>PR_Interrupt
()</tt> call, the IO function returns with <tt>PR_PENDING_INTERRUPT_ERROR</tt>. On Windows NT, NSPR IO is implemented using NT's overlapped (also called asynchronous) IO. When a thread calls an IO function, the thread issues an overlapped IO request using the overlapped buffer in its <tt>PRThread</tt> structure. Then the thread is put to sleep. In the meantime, there are dedicated internal threads (...
...eout and Interrupt However, NSPR may wake up the thread in two other situations: if the overlapped IO request is not completed before the specified timeout. (Note that we can't specify timeout on overlapped IO requests, so the timeouts are all handled at the NSPR level.) In this case, the error is <tt>PR_IO_TIMEOUT_ERROR</tt>. if the thread gets interrupted by another thread's <tt>PR_Interrupt
()</tt> call. In this case, the error is <tt>PR_PENDING_INTERRUPT_ERROR</tt>. These two errors are generated by the NSPR layer, so the OS is oblivious of what is going on and the overlapped IO request is still in progress. The OS still has a pointer to the overlapped buffer in the thread's <tt>PRThread</tt> structure. If the thread subsequently exists and its <tt>PRThread</tt> structure gets delete...
...pped buffer in the thread's <tt>PRThread</tt> structure. If the thread subsequently exists and its <tt>PRThread</tt> structure gets deleted, the pointer to the overlapped buffer will be pointing to freed memory. This is problematic. Canceling Overlapped IO by Closing the File Descriptor Therefore, we need to cancel the outstanding overlapped IO request before the thread exits. NT's <tt>CancelIo
()</tt> function would be ideal for this purpose. Unfortunately, <tt>CancelIo
()</tt> is not available on NT 3.51. So we can't go this route as long as we are supporting NT 3.51. The only reliable way to cancel outstanding overlapped IO request that works on both NT 3.51 and 4.0 is to close the file descriptor, hence the rule of thumb stated at the beginning of this memo. Limitations This seemingl...
...And 3 more matches
Using the W3C DOM - Archive of obsolete content
ripts that use these properties will throw errors in most standards-compliant browsers. Instead, use the W3C DOM properties and methods (examples in the next section). These are supported by Internet Explorer too so there is no need to use MSIE-specific attributes and methods. Accessing Elements with the W3C DOM The basic method for referencing elements in an HTML page is document.getElementById
(). All modern browsers support it. The method returns a reference to the uniquely identified element, which can then be used to script the element. For example, the following short sample dynamically sets the left margin of a <div> element with an id of "inset" to half an inch: // in the HTML: <div id="inset">Sample Text</div> document.getElementById("inset").style.marginLeft = ".5in"; Note: Int...
...niquely identified element, which can then be used to script the element. ...
...ementById("inset").style.marginLeft = ".5in"; Note: Internet Explorer 5 through 7 have a flawed implementation of getElementById
(), which returns the first element with a matching NAME or ID (Id versus name when using getElementById, MSDN: getElementById Method). ...
...And 3 more matches
Browser Feature Detection - Archive of obsolete content
0% 98% 67% 71% / 83% 38% / 42% Test Results Cross Reference DOM Core Level 1 Support for properties/methods in document name Firefox 1.5 IE 6 & 7 Opera 8.54 - 9.01 Document.doctype true true true Document.implementation true true true Document.documentElement true true true Document.createElement
() true true true Document.createDocumentFragment
() true true true Document.createTextNode
() true true true Document.createComment
() true true true Document.createCDATASection
() true false true Document.createProcessingInstruction
() true false true Document.createAttribute
() true true ...
...eateDocumentFragment
() true true true Document.createTextNode
() true true true Document.createComment
() true true true Document.createCDATASection
() true false true Document.createProcessingInstruction
() true false true Document.createAttribute
() true true true Document.createEntityReference
()Obsolete since Gecko 7 (method present but only returns null: bug 9850) false false Document.getElementsByTagName
() true true true DOM Core Level 2 Support for properties/methods in document name Firefox 1.5 IE 6 & 7 Opera 8.54 - 9.01 Document.doctype true true true Document.implementation true true true ...
... false Document.getElementsByTagName
() true true true DOM Core Level 2 Support for properties/methods in document name Firefox 1.5 IE 6 & 7 Opera 8.54 - 9.01 Document.doctype true true true Document.implementation true true true Document.documentElement true true true Document.createElement
() true true true Document.createDocumentFragment
() true true true Document.createTextNode
() true true true Document.createComment
() true true true Document.createCDATASection
() true false true Document.createProcessingInstruction
() true false true Document.createAttribute
() true true ...
...And 3 more matches
Array comprehensions - Archive of obsolete content
wo kinds of components are allowed: for...of and if The for-of iteration is always the first component. Multiple for-of iterations or if statements are allowed. Array comprehension was previously proposed to be standardized in ECMAScript 2016, it provide a useful shortcut for constructing a new array based on the contents of another. ...
...omponents are allowed: for...of and if The for-of iteration is always the first component. Multiple for-of iterations or if statements are allowed. Array comprehension was previously proposed to be standardized in ECMAScript 2016, it provide a useful shortcut for constructing a new array based on the contents of another. ...
...e contents of another. Comprehensions can often be used in place of calls to map
() and filter
(), or as a way of combining the two. The following comprehension takes an array of numbers and creates a new array of the double of each of those numbers. var numbers = [1, 2, 3, 4]; var doubled = [for (i of numbers) i * 2]; console.log(doubled); // logs 2,4,6,8 This is equivalent to the following map
() operation: var doubled = numbers.map(i => i * 2); Comprehensions can also be used to select items that match a particular expression. ...
...And 3 more matches
Generator comprehensions - Archive of obsolete content
tegers. We want to create a new iterator that will iterate over their doubles. ...
...er their doubles. ...
...nsion, you would only have to loop over the 'obj' structure once, total, as opposed to once when comprehending the array, and again when iterating through it. ...
...And 3 more matches
Enumerator.atEnd - Archive of obsolete content
Non-standard. Do not use! ...
...yntax myEnum.atEnd
() Remarks The required myEnum reference is any Enumerator object. The atEnd method returns true if the current item is the last one in the collection, the collection is empty, or the current item is undefined. Otherwise, it returns false. ...
...llection is empty, or the current item is undefined. Otherwise, it returns false. ...
...And 3 more matches
Enumerator.item - Archive of obsolete content
Non-standard. Do not use! ...
... This object is a Microsoft extension and is only supported in Internet Explorer. The Enumerator.item method returns the current item in the collection. Syntax enumObj.item
() Remarks The required enumObj reference is any Enumerator object. The item method returns the current item. If the collection is empty or the current item is undefined, it returns undefined. ...
...arks The required enumObj reference is any Enumerator object. The item method returns the current item. If the collection is empty or the current item is undefined, it returns undefined. ...
...And 3 more matches
New in JavaScript 1.1 - Archive of obsolete content
ipt language versions. <SCRIPT LANGUAGE="JavaScript"> <!-- JavaScript for Navigator 2.0. --> <SCRIPT LANGUAGE="JavaScript1.1"> <!-- JavaScript for Navigator 3.0. ...
...RIPT LANGUAGE="JavaScript"> <!-- JavaScript for Navigator 2.0. --> <SCRIPT LANGUAGE="JavaScript1.1"> <!-- JavaScript for Navigator 3.0. ...
...t"> <!-- JavaScript for Navigator 2.0. --> <SCRIPT LANGUAGE="JavaScript1.1"> <!-- JavaScript for Navigator 3.0. ...
...And 3 more matches
JSException - Archive of obsolete content
patibility JavaScript 1.1 through 1.3 JSException had three public constructors which optionally took a string argument, specifying the detail message or other information for the exception. The getWrappedException method was not available. JSException constructors, deprecated in JavaScript 1.4, constructs a JSException object with an optional detail message. Declaration 1. public JSException
() 2. public JSException(String s) 3. public JSException(String s, String filename, int lineno, String source, int tokenIndex) Arguments s The detail message. filename The URL of the file where the error occurred, if possible. lineno The line number of the file, if possible. source The string containing the JavaScript code being evaluated. tokenIndex The ...
...detail message. filename The URL of the file where the error occurred, if possible. lineno The line number of the file, if possible. source The string containing the JavaScript code being evaluated. tokenIndex The index into the source string where the error occurred. getWrappedException Instance method getWrappedException. ...
...L of the file where the error occurred, if possible. lineno The line number of the file, if possible. source The string containing the JavaScript code being evaluated. tokenIndex The index into the source string where the error occurred. getWrappedException Instance method getWrappedException. ...
...And 3 more matches
Bounding volume collision detection with THREE.js - Game development
in our 3D world (like a character.) In Three.js, Geometry instances have a boundingBox property with min and max boundaries for the object. Keep in mind that in order for this property to be defined, you need to manually call Geometry.computeBoundingBox beforehand. var knot = new THREE.Mesh( new THREE.TorusKnotGeometry(0.5, 0.1), new MeshNormalMaterial({})); knot.geometry.computeBoundingBox
(); var knotBBox = new Box3( knot.geometry.boundingBox.min, knot.geometry.boundingBox.max); Note: The boundingBox property takes the Geometry itself as reference, and not the Mesh. So any transformations such as scale, position, etc. applied to the Mesh will be ignored while computing the calculating box. A more simple alternative that fixes the previous issue is to set those boundaries l...
...ing the calculating box. A more simple alternative that fixes the previous issue is to set those boundaries later on with Box3.setFromObject, which will compute the dimensions taking into account a 3D entity's transformations and any child meshes as well. var knot = new THREE.Mesh( new THREE.TorusKnotGeometry(0.5, 0.1), new MeshNormalMaterial({})); var knotBBox = new Box3(new THREE.Vector3
(), new THREE.Vector3
()); knotBBox.setFromObject(knot); Instantiating spheres Instantiating Sphere objects is similar. We need to provide the sphere's center and radius, which can be added to the boundingSphere property available in Geometry. var knot = new THREE.Mesh( new THREE.TorusKnotGeometry(0.5, 0.1), new MeshNormalMaterial({})); var knotBSphere = new Sphere( knot.position, knot.ge...
...rsectsSphere(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. ...
...And 3 more matches
Building up a basic demo with PlayCanvas editor - Game development
to a code editor. As you can see, the file contains some boilerplate code already: pc.script.create('boxAnimation', function (app) { // Creates a new BoxAnimation instance var BoxAnimation = function (entity) { this.entity = entity; }; BoxAnimation.prototype = { // Called once after all resources are loaded and before the first update initialize: function
() { }, // Called every frame, dt is time in seconds since last update update: function (dt) { } }; return BoxAnimation; }); The most interesting part is the update
() function, which is where we can put any code that we want repeated on every frame. Add the following line inside this function, to rotate the cube on every frame: this.entity.rotate(dt*10, dt...
... box object. The cylinder Now we'll do the same steps for cylinder. First: Create a new Script asset. Name it cylinderAnimation.js. Double click the script icon to launch the code editor. This time instead of rotating the object we will try to scale it. For that we'll need a timer to store the total amount of time passed since the start of the animation. ...
...ylinder. First: Create a new Script asset. Name it cylinderAnimation.js. Double click the script icon to launch the code editor. This time instead of rotating the object we will try to scale it. For that we'll need a timer to store the total amount of time passed since the start of the animation. ...
...And 3 more matches
Buttons - Game development
variable to store a boolean value representing whether the game is currently being played or not, and another one to represent our button. Add these lines below your other variable definitions: var playing = false; var startButton; Loading the button spritesheet We can load the button spritesheet the same way we loaded the ball's wobble animation. ...
...he preload
() function: game.load.spritesheet('button', 'img/button.png', 120, 40); A single button frame is 120 pixels wide and 40 pixels high. You also need to grab the button spritesheet from Github, and save it in your /img directory. Adding the button to the game Adding the new button to the game is done by using the add.button method. ...
...ab the button spritesheet from Github, and save it in your /img directory. Adding the button to the game Adding the new button to the game is done by using the add.button method. Add the following lines to the bottom of your create
() function: startButton = game.add.button(game.world.width*0.5, game.world.height*0.5, 'button', startGame, this, 1, 0, 2); startButton.anchor.set(0.5); The button
() method's parameters are as follows: The button's x and y coordinates The name of the graphic asset to be displayed for the button A callback function that will be executed when the button is pressed A reference to this to specify the execution context The frames that will be used for the over, out and down events. Note: The over event is the same as hover, out is when the pointer moves ...
...And 3 more matches
Physics - Game development
fferent physics engines -- Arcade Physics, P2 and Ninja Physics -- with a fourth option, Box2D, being available as a commercial plugin. For simple games like ours, we can use the Arcade Physics engine. We don't need any heavy geometry calculations -- after all it's just a ball bouncing off walls and bricks. First, let's initialize the Arcade Physics engine in our game. ...
... initialize the Arcade Physics engine in our game. Add the physics.startSystem
() method at the beginning of the create function (make it the first line inside the function), as shown below: game.physics.startSystem(Phaser.Physics.ARCADE); Next, we need to enable our ball for the physics system -- Phaser object physics is not enabled by default. Add the following line at the bottom of the create
() function: game.physics.enable(ball, Phaser.Physics.ARCADE); Next, if we want to move our ball on the screen, we can set velocity on its body. ...
...cs.startSystem(Phaser.Physics.ARCADE); Next, we need to enable our ball for the physics system -- Phaser object physics is not enabled by default. Add the following line at the bottom of the create
() function: game.physics.enable(ball, Phaser.Physics.ARCADE); Next, if we want to move our ball on the screen, we can set velocity on its body. ...
...And 3 more matches
How to build custom form controls - Learn web development
the elements, but it is still available to screen readers. Now we need a JavaScript switch to determine if the script is running or not. This switch is a couple of lines: if at page load time our script is running, it will remove the no-widget class and add the widget class, thereby swapping the visibility of the <select> element and the custom control. ...
...it's far better to just add the widget class to hide the <select> elements, and to dynamically add the DOM tree representing the custom control after every <select> element in the page. Making the job easier In the code we are about to build, we will use the standard JavaScript and DOM APIs to do all the work we need. The features we plan to use are the following: classList addEventListener
() forEach querySelector
() and querySelectorAll
() Beyond the availability of those specific features, there is still one issue remaining before starting. The object returned by the querySelectorAll
() function is a NodeList rather than an Array. This is important because Array objects support the forEach function, but NodeList doesn't. Because NodeList really looks like an Array and because forEa...
... optionList.forEach(function (other) { other.classList.remove('highlight'); }); // We highlight the right option option.classList.add('highlight'); }; You need these in order to handle the various states of the custom control. Next, we bind these functions to the appropriate events: // We handle the event binding when the document is loaded. ...
...And 3 more matches
General asynchronous programming concepts - Learn web development
at a couple of examples that show what we mean by blocking. ...
...ml example (see it running live), we add a click event listener to a button so that when clicked, it runs a time-consuming operation (calculates 10 million dates then logs the final one to the console) and then adds a paragraph to the DOM: const btn = document.querySelector('button'); btn.addEventListener('click',
() => { let myDate; for(let i = 0; i < 10000000; i++) { let date = new Date
(); myDate = date } console.log(myDate); let pElem = document.createElement('p'); pElem.textContent = 'This is a newly-added paragraph.'; document.body.appendChild(pElem); }); When running the example, open your JavaScript console then click the button -- you'll notice that the paragraph does not appear until after the dates have finished being calculated and the console message has...
... it live), we simulate something slightly more realistic that you might come across on a real page. We block user interactivity with the rendering of the UI. In this example, we have two buttons: A "Fill canvas" button that when clicked fills the available <canvas> with 1 million blue circles. A "Click me for alert" button that when clicked shows an alert message. ...
...And 3 more matches
Framework main features - Learn web development
this data: { subject: "World" } Handlebars will build HTML like this: <header> <h1>Hello, World!</h1> </header> TypeScript TypeScript is a superset of JavaScript, meaning it extends JavaScript -- all JavaScript code is valid TypeScript, but not the other way around. TypeScript is useful for the strictness it allows developers to enforce on their code. For instance, consider a function add
(), which takes integers a and b and returns their sum. In JavaScript, that function could be written like this: function add(a, b) { return a + b; } This code might be trivial for someone accustomed to JavaScript, but it could still be clearer. JavaScript lets us use the + operator to concatenate strings together, so this function would technically still work if a and b were strings -- it just...
...h component may have data to control the state of. This stage will persist in some way as long as the component is in use. Like props, state can be used to affect how a component is rendered. As an example, consider a button that counts how many times it has been clicked. ...
...onent is in use. Like props, state can be used to affect how a component is rendered. As an example, consider a button that counts how many times it has been clicked. This component should be responsible for tracking its own count state, and could be written like this: function CounterButton
() { const [count] = useState(0); return ( <button>Clicked {count} times</button> ); } useState
() is a React hook which, given an initial data value, will keep track of that value as it is updated. The code will be initially rendered like so in the browser: <button>Clicked 0 times</button> The useState
() call keeps track of the count value in a robust way across the app, without you needing to write code to do that yourself. Events In order to be interactive, components need ways to respo...
...And 3 more matches
Chrome Worker Modules
The preferred way to define and load modules for Chrome Workers is to use the Chrome Worker Module Loader. This module loader should not surprise developers familiar with CommonJS, as it implements a minimal CommonJS require
(). Loading modules Loading a module is simple. Start by importing the module loader. You only need to do it once for each worker, from within the chrome worker itself: importScripts("resource://gre/modules/workers/require.js"); Note: Although you only need to do this once for each worker, it doesn't hurt if you do it more than once. ...
...If the your module URI ends with ".js", you can omit the extension. ...
...ugh you only need to do this once for each worker, it doesn't hurt if you do it more than once. This defines a global value require
(), that you may now use as follows: // Import the module // (here, we import the core of OS.File) let Core = require("resource://gre/modules/osfile/osfile_shared_allthreads.jsm"); // We may now use module Core. Core.declareFFI(...) Note that, for the moment, require
() only accepts absolute URIs. If the your module URI ends with ".js", you can omit the extension. Creating modules Creating a module is just as simple. A module is a file, whose filename generally ends with either ".js" or ".jsm", and designed to be opened through require
(). Any value you define in that file is private by default. To make the value public, you just have to add it to either global v...
...And 3 more matches
Frame script loading and lifetime
Loading frame scripts To load a frame script use the loadFrameScript
() function. This line of code loads a frame script into the currently selected tab. The script just writes "foo" to the command line: // chrome script var mm = gBrowser.selectedBrowser.messageManager; mm.loadFrameScript('data:,dump("foo\\n")', true); loadFrameScript
() takes two mandatory parameters: A URL that points to the frame script you want to load A boolean flag, allowDelayedLoad Note: if the message manager is a global frame message manager or a window message manager, loadFrameScript
() may load the script multiple times, once in each applicable frame. chrome: URLs Extension developers usually use a chrome:// URL to refer to the frame scripts. To define the mapping between a chrome:// URL and a f...
...For example: var mm = window.messageManager; mm.loadFrameScript("chrome://my-e10s-extension/content/frame-script.js", true); The script will be loaded into all tabs currently open in this window, and all new tabs opened afterwards. If allowDelayedLoad is false, the script will only be loaded into frames which are open when the call was made. If the message manager is a browser me...
...ript will be loaded into all tabs currently open in this window, and all new tabs opened afterwards. If allowDelayedLoad is false, the script will only be loaded into frames which are open when the call was made. If the message manager is a browser message manager, you should always pass true here. Because a browser message manager only corresponds to a single browser tab, its loadFrameScript
() function will only ever load the frame script into that one tab. Passing allowDelayedLoad is a way to ensure that the script is loaded correctly, in case the tab is not ready when making the call. If you use allowDelayedLoad, you can cancel it by using removeDelayedFrameScript: var mm = window.messageManager; mm.removeDelayedFrameScript("chrome://my-e10s-extension/content/frame-script.js"); Th...
...And 3 more matches
Message manager overview
but this usage is deprecated because the Add-on SDK uses "content script" to refer to a similar but different kind of script. There are three different subtypes of frame message manager: the global message manager, the window message manager, and the browser message manager. All three enable chrome code to: load a script into a frame in the content the content process using a loadFrameScript
() function. These scripts are called "frame scripts". communicate with frame scripts using addMessageListener
() and broadcastAsyncMessage
() or sendAsyncMessage
() functions. Note that in this context, "browser" refers to the XUL <browser> object, which is a frame that hosts a single Web document. It does not refer to the more general sense of a Web browser. Global message manager The global ...
...geListener
() and broadcastAsyncMessage
() or sendAsyncMessage
() functions. Note that in this context, "browser" refers to the XUL <browser> object, which is a frame that hosts a single Web document. It does not refer to the more general sense of a Web browser. Global message manager The global message manager operates on every <browser> (that is, every open content tab). loadFrameScript
() loads the given script into every <browser> in every browser window. broadcastAsyncMessage
() sends the message to every <browser> in every browser window. It's a ChromeMessageBroadcaster object, which implements the following interfaces: nsIFrameScriptLoader nsIMessageListenerManager nsIMessageBroadcaster You can access the global message manager like this: // chrome script let globalM...
... It's a ChromeMessageBroadcaster object, which implements the following interfaces: nsIFrameScriptLoader nsIMessageListenerManager nsIMessageBroadcaster The window message manager can be accessed as a property of the browser window: // c...
...And 3 more matches
JavaScript-DOM Prototypes in Mozilla
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 things like modify how all instances of a given class works by modifying the prototype of one instance. As an example: function bar
() { alert("Hello world!"); } document.images[0].__proto__.foo = bar; This would make every image in this document have a callable foo property (i.e. a foo
() method). Alternatively, one can access and modify the prototype of an HTMLImageElement through the prototype property of the constructor: HTMLImageElement.prototype.foo = bar; Modifying the prototype of a Host object is not guaranteed ...
... to all objects that implement Node. This means you can add a property to every node in a DOM tree by doing something like this: Node.prototype.foo = bar; Again, modifying host objects is an unsafe practice. It is not guaranteed to work or be error-free in any implementation. It is not standard and cannot be expected to have any result. Here is an attempt to modify a host object: (function
(){ try { Image.prototype.src = 1; } catch(ex){ alert(ex); } })
(); This demonstrates that the Image constructor, a host object supported in nearly all browsers for Mac and Windows, has a prototype property, and that an attempt to modify the prototype's src - property results in an error. Another example would be modifying the pageX property of a MouseEvent insta...
...assInfo code uses the registry every time a named property is resolved on a global object (because of this, the nsScriptNameSpaceManager needs to be pretty fast at looking things up in its registry; that's why it is a hash table). When a property is resolved on the global object, the nsDOMClassInfo code will ask the nsScriptNameSpaceManager if the name is a known name (in nsWindowSH::GlobalResolve
()), and if the name is known, the code will look at the type of the name and act accordingly. If a class constructor or class prototype name is resolved, the class info code will define the constructor for that class, and also define the prototype property of that constructor (i.e. HTMLImageElement.prototype). The prototype of a constructor will either be the prototype object that XPConnect create...
...And 3 more matches
DownloadList
A DownloadList object represents a collection of Download objects that can be viewed and managed by the user interface, and persisted across sessions. A reference to a DownloadList object can be obtained using the Downloads.getList
() function. Method overview Promise<Array<Download>> getAll
(); Promise add(Download aDownload); Promise remove(Download aDownload); Promise addView(Object aView); Promise removeView(Object aView); void removeFinished([optional] Function aFilterFn); Methods getAll
() Retrieves a snapshot of the downloads that are currently in the list. The returned array does not change when downloads are added or removed, though the Download objects it contains are still ...
...ct aView); Promise removeView(Object aView); void removeFinished([optional] Function aFilterFn); Methods getAll
() Retrieves a snapshot of the downloads that are currently in the list. The returned array does not change when downloads are added or removed, though the Download objects it contains are still updated in real time. Promise<Array<Download>> getAll
(); Parameters None. Promise resolves to An array of Download objects. add
() Adds a new download to the end of the items list. ...
...If the download was already removed, this method has no effect. ...
...And 3 more matches
FileUtils.jsm
Corresponds to the PR_CREATE_FILE parameter to PR_OPEN MODE_APPEND 0x10 Corresponds to the PR_APPEND parameter to PR_OPEN MODE_TRUNCATE 0x20 Corresponds to the PR_TRUNCATE parameter to PR_OPEN PERMS_FILE 0644 Default permissions when creating files. PERMS_DIRECTORY 0755 Default permissions when creating directories Methods getFile
() Gets a file at the specified hierarchy under a nsIDirectoryService key. nsIFile getFile( string key, array pathArray, bool followLinks ); Parameters key The nsIDirectoryService key to start from (see Getting special files for more info) pathArray An array of path components to locate beneath the directory specified by key. The last item in this array must be the leaf name of a fil...
...nfo) pathArray An array of path components to locate beneath the directory specified by key. The last item in this array must be the leaf name of a file. followLinks Optional True if links should be followed, false otherwise. Return value Returns a nsIFile object for the file specified. The file is NOT created if it does not exist, however all required directories along the way are. getDir
() Gets a directory at the specified hierarchy under a nsIDirectoryService key. nsIFile getDir( string key, array pathArray, bool shouldCreate, bool followLInks ); Parameters key The nsIDirectoryService key to start from (see Getting special files for more info) pathArray An array of path components to locate beneath the directory specified by key. shouldCreate Optional True if t...
...cation specified. Return value Returns a nsIFile object for the location specified. If the directory requested does not exist, it is created, along with any parent directories that need to be created. Note: If you want to use the full path to get to the directory you cannot use getDir. Instead use the file constructor, so simply: var dir = new FileUtils.File('C:\\blah\\blah'); if (dir.exists
()) { //yes directory exists } openFileOutputStream
() Opens a file output stream for writing. The stream is opened with the DEFER_OPEN nsIFileOutputStream.Behavior flag constant this means the file is not actually opened until the first time it's accessed. nsIFileOutputStream openFileOutputStream( nsIFile file, int modeFlags ); Parameters file The file to write to. modeFlags Optio...
...And 3 more matches
NetUtil.jsm
newChannel(aWhatToLoad, [optional] aOriginCharset, [optional] nsIURI aBaseURI) nsIURI newURI(aTarget, [optional] aOriginCharset, [optional] nsIURI aBaseURI) String readInputStreamToString(aInputStream, aCount, aOptions) Attributes Attribute Type Description ioService nsIIOService Returns a reference to nsIIOService. Methods asyncCopy
() The asyncCopy
() method performs a simple asynchronous copy of data from a source input stream to a destination output stream. Both streams are automatically closed when the copy operation is completed. nsIAsyncStreamCopier asyncCopy( aSource, aSink, aCallback ); Parameters aSource The input stream from which to read the source data. This must be an nsIInputStream based object. aSin...
...inally, we need an input stream to take data from. const TEST_DATA = "this is a test string"; let istream = Cc["@mozilla.org/io/string-input-stream;1"]. createInstance(Ci.nsIStringInputStream); istream.setData(TEST_DATA, TEST_DATA.length); NetUtil.asyncCopy(istream, ostream, function(aResult) { if (!Components.isSuccessCode(aResult)) { // an error occurred! } }) asyncFetch
() The asyncFetch
() method opens an input source, asynchronously, and gives an nsIInputStream containing the data obtained to the callback provided. The callback may then consume data from the input stream passed to the callback. Note: Prior to Gecko 2, the input source was required to be specified as an nsIChannel. Note: Support for specifying an nsIInputStream as the input source was added i...
..., function(aInputStream, aResult) { // Check that we had success. if (!Components.isSuccessCode(aResult)) { // Handle error return; } // Consume the input stream. }); Remarks Note: If you specify an nsIChannel as the input source, and its notification callbacks have already been set, callers are responsible for implementing nsIBadCertListener and nsISSLErrorListener. newChannel
() Creates a new channel for the specified URI string, nsIURI, or nsIFile. nsIChannel newChannel( aWhatToLoad, [optional] aOriginCharset, [optional] aBaseURI ); Parameters Return value An nsIChannel allowing access to the specified data source. aWhatToLoad A string specifying a URI, or an nsIURI or nsIFile object. The returned method will allow access to the specified data. aOriginC...
...And 3 more matches
PerfMeasurement.jsm
ce://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
(); Member fields Recorded data variables These variables provide access to the recorded data. Any measurable event that was not being recorded has a value of -1 (that is, 0xFFFFFFFFFFFFFFFF). Note: These values are all zeroed (or set to -1, for events not being measured) when you initialize the PerfMeasurement object, then they are not zeroed aga...
...This lets you accumulate measurements over multiple passes through code that you want to analyze. Variable Type Description cpu_cycles uint64 The number of CPU cycles elapsed. instructions uint64 The number of instructions executed. cache_references uint64 The number of memory accesses that occurred. ...
...nt( EventMask toMeasure ); Parameters toMeasure A mask of all of the event types you want to record; see Event mask constants for a list of values. OR together all the event types you want to record, and pass that value here. Pass PerfMeasurement.ALL to record all event types. Return value A new PerfMeasurement object configured to record the specified event types. ...
...And 3 more matches
Encrypt Decrypt MAC Keys As Session Objects
kenKeyGen(slot, mechanism, NULL, keySize, keyID, PR_TRUE, pwdata); if (!key) { PR_fprintf(PR_STDERR, "Symmetric Key Generation Failed \n"); } return key; } /* * MacInit */ SECStatus MacInit(PK11Context *ctx) { SECStatus rv = PK11_DigestBegin(ctx); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : PK11_DigestBegin
()\n"); } return rv; } /* * MacUpdate */ SECStatus MacUpdate(PK11Context *ctx, unsigned char *msg, unsigned int msgLen) { SECStatus rv = PK11_DigestOp(ctx, msg, msgLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : DigestOp
()\n"); } return rv; } /* * Finalize MACing */ SECStatus MacFinal(PK11Context *ctx, unsigned char *...
...CSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : DigestOp
()\n"); } return rv; } /* * Finalize MACing */ SECStatus MacFinal(PK11Context *ctx, unsigned char *mac, unsigned int *macLen, unsigned int maxLen) { SECStatus rv = PK11_DigestFinal(ctx, mac, macLen, maxLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : PK11_DigestFinal
()\n"); } return SECSuccess; } /* * Compute Mac */ SECStatus ComputeMac(PK11Context *ctxmac, unsigned char *ptext, unsigned int ptextLen, unsigned char *mac, unsigned int *macLen, unsigned int maxLen) { SECStatus rv = MacInit(ctxmac); if (rv != SECSuccess) return rv; rv = MacUpdate(ctxmac, ptext, ptextLen); if (rv != SECSuccess) return rv; ...
... "Could not authenticate to token %s.\n", PK11_GetTokenName(slot)); if (slot) { PK11_FreeSlot(slot); } return NULL; } } key = PK11_FindFixedKey(slot, mechanism, keyBuf, 0); if (!key) { PR_fprintf(PR_STDERR, "PK11_FindFixedKey failed (err %d)\n", PR_GetError
()); PK11_FreeSlot(slot); return NULL; } return key; } /* * Decrypt and Verify MAC */ SECStatus DecryptAndVerifyMac(const char* outFileName, char *encryptedFileName, SECItem *cItem, SECItem *macItem, PK11SymKey* ek, PK11SymKey* mk, SECItem *ivItem, SECItem *padItem) { SECStatus rv; PRFileDesc* inFile; PRFileDesc* outFile; unsigned ch...
...And 3 more matches
Encrypt and decrypt MAC using token
kenKeyGen(slot, mechanism, NULL, keySize, keyID, PR_TRUE, pwdata); if (!key) { PR_fprintf(PR_STDERR, "Symmetric Key Generation Failed \n"); } return key; } /* * MacInit */ SECStatus MacInit(PK11Context *ctx) { SECStatus rv = PK11_DigestBegin(ctx); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : PK11_DigestBegin
()\n"); } return rv; } /* * MacUpdate */ SECStatus MacUpdate(PK11Context *ctx, unsigned char *msg, unsigned int msgLen) { SECStatus rv = PK11_DigestOp(ctx, msg, msgLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : DigestOp
()\n"); } return rv; } /* * Finalize MACing */ SECStatus MacFinal(PK11Context *ctx, unsigned char *...
...CSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : DigestOp
()\n"); } return rv; } /* * Finalize MACing */ SECStatus MacFinal(PK11Context *ctx, unsigned char *mac, unsigned int *macLen, unsigned int maxLen) { SECStatus rv = PK11_DigestFinal(ctx, mac, macLen, maxLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : PK11_DigestFinal
()\n"); } return SECSuccess; } /* * Compute Mac */ SECStatus ComputeMac(PK11Context *ctxmac, unsigned char *ptext, unsigned int ptextLen, unsigned char *mac, unsigned int *macLen, unsigned int maxLen) { SECStatus rv = MacInit(ctxmac); if (rv != SECSuccess) return rv; rv = MacUpdate(ctxmac, ptext, ptextLen); if (rv != SECSuccess) return rv; ...
... "Could not authenticate to token %s.\n", PK11_GetTokenName(slot)); if (slot) { PK11_FreeSlot(slot); } return NULL; } } key = PK11_FindFixedKey(slot, mechanism, keyBuf, 0); if (!key) { PR_fprintf(PR_STDERR, "PK11_FindFixedKey failed (err %d)\n", PR_GetError
()); PK11_FreeSlot(slot); return NULL; } return key; } /* * Decrypt and Verify MAC */ SECStatus DecryptAndVerifyMac(const char* outFileName, char *encryptedFileName, SECItem *cItem, SECItem *macItem, PK11SymKey* ek, PK11SymKey* mk, SECItem *ivItem, SECItem *padItem) { SECStatus rv; PRFileDesc* inFile; PRFileDesc* outFile; unsigned ch...
...And 3 more matches
Encrypt Decrypt_MAC_Using Token
*/ SECStatus MacFinal(PK11Context *ctx, unsigned char ...
...11_DigestBegin(ctx); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : PK11_DigestBegin
()\n"); } return rv; } /* * MacUpdate */ SECStatus MacUpdate(PK11Context *ctx, unsigned char *msg, unsigned int msgLen) { SECStatus rv = PK11_DigestOp(ctx, msg, msgLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : DigestOp
()\n"); } return rv; } /* * Finalize MACing. */ SECStatus MacFinal(PK11Context *ctx, unsigned char *mac, unsigned int *macLen, unsigned int maxLen) { SECStatus rv = PK11_DigestFinal(ctx, mac, macLen, maxLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : PK11_DigestFinal
()\n"); } return SECSuccess; } /* * Compute Mac. */ SECStatus ...
... */ SECStatus DecryptAndVerifyMac(const char* outFileName, char *encryptedFileName, SECItem *cItem, SECItem *macItem, PK11SymKey* ek, PK11SymKey* mk, SECItem *ivItem, SECItem *padItem) { SECStatus rv; PRFileDesc* inFile; PRFileDesc* outFile; unsigned c...
...And 3 more matches
NSS Sample Code Sample_3_Basic Encryption and MACing
kenKeyGen(slot, mechanism, NULL, keySize, keyID, PR_TRUE, pwdata); if (!key) { PR_fprintf(PR_STDERR, "Symmetric Key Generation Failed \n"); } return key; } /* * MacInit */ SECStatus MacInit(PK11Context *ctx) { SECStatus rv = PK11_DigestBegin(ctx); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : PK11_DigestBegin
()\n"); } return rv; } /* * MacUpdate */ SECStatus MacUpdate(PK11Context *ctx, unsigned char *msg, unsigned int msgLen) { SECStatus rv = PK11_DigestOp(ctx, msg, msgLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : DigestOp
()\n"); } return rv; } /* * Finalize MACing */ SECStatus MacFinal(PK11Context *ctx, unsigned char *...
...CSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : DigestOp
()\n"); } return rv; } /* * Finalize MACing */ SECStatus MacFinal(PK11Context *ctx, unsigned char *mac, unsigned int *macLen, unsigned int maxLen) { SECStatus rv = PK11_DigestFinal(ctx, mac, macLen, maxLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : PK11_DigestFinal
()\n"); } return SECSuccess; } /* * Compute Mac */ SECStatus ComputeMac(PK11Context *ctxmac, unsigned char *ptext, unsigned int ptextLen, unsigned char *mac, unsigned int *macLen, unsigned int maxLen) { SECStatus rv = MacInit(ctxmac); if (rv != SECSuccess) return rv; rv = MacUpdate(ctxmac, ptext, ptextLen); if (rv != SECSuccess) return rv; ...
... "Could not authenticate to token %s.\n", PK11_GetTokenName(slot)); if (slot) { PK11_FreeSlot(slot); } return NULL; } } key = PK11_FindFixedKey(slot, mechanism, keyBuf, 0); if (!key) { PR_fprintf(PR_STDERR, "PK11_FindFixedKey failed (err %d)\n", PR_GetError
()); PK11_FreeSlot(slot); return NULL; } return key; } /* * Decrypt and Verify MAC */ SECStatus DecryptAndVerifyMac( const char* outFileName, char *encryptedFileName, SECItem *cItem, SECItem *macItem, PK11SymKey* ek, PK11SymKey* mk, SECItem *ivItem, SECItem *padItem) { SECStatus rv; PRFileDesc* inFile; PRFileDesc* outFile; unsign...
...And 3 more matches
EncDecMAC using token object - sample 3
t)); return NULL; } } /* Generate the symmetric key */ key = PK11_TokenKeyGen(slot, mechanism, NULL, keySize, keyID, PR_TRUE, pwdata); if (!key) { PR_fprintf(PR_STDERR, "Symmetric Key Generation Failed \n"); } return key; } /* * MacInit */ SECStatus MacInit(PK11Context *ctx) { SECStatus rv = PK11_DigestBegin(ctx); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : PK11_DigestBegin
()\n"); } return rv; } /* * MacUpdate */ SECStatus MacUpdate(PK11Context *ctx, unsigned char *msg, unsigned int msgLen) { SECStatus rv = PK11_DigestOp(ctx, msg, msgLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : DigestOp
()\n"); } return rv; } /* * Finalize MACing */ SECStatus MacFinal(PK11Context *ctx, unsigned char *mac, unsigned int *macLen, unsigned int maxLen) { SECStat...
...K11_DigestOp(ctx, msg, msgLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : DigestOp
()\n"); } return rv; } /* * Finalize MACing */ SECStatus MacFinal(PK11Context *ctx, unsigned char *mac, unsigned int *macLen, unsigned int maxLen) { SECStatus rv = PK11_DigestFinal(ctx, mac, macLen, maxLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : PK11_DigestFinal
()\n"); } return SECSuccess; } /* * Compute Mac */ SECStatus ComputeMac(PK11Context *ctxmac, unsigned char *ptext, unsigned int ptextLen, unsigned char *mac, unsigned int *macLen, unsigned int maxLen) { SECStatus rv = MacInit(ctxmac); if (rv != SECSuccess) return rv; rv = MacUpdate(ctxmac, ptext, ptextLen); if (rv != SECSuccess) return rv; rv = MacFinal(ctxmac, mac, macLen, maxLen); return rv; } /* ...
...s rv; PK11SymKey *key; if (PK11_NeedLogin(slot)) { rv = PK11_Authenticate(slot, PR_TRUE, pwdata); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Could not authenticate to token %s.\n", PK11_GetTokenName(slot)); if (slot) { PK11_FreeSlot(slot); } return NULL; } } key = PK11_FindFixedKey(slot, mechanism, keyBuf, 0); if (!key) { PR_fprintf(PR_STDERR, "PK11_FindFixedKey failed (err %d)\n", PR_GetError
()); PK11_FreeSlot(slot); return NULL; } return key; } /* * Decrypt and Verify MAC */ SECStatus DecryptAndVerifyMac(const char* outFileName, char *encryptedFileName, SECItem *cItem, SECItem *macItem, PK11SymKey* ek, PK11SymKey* mk, SECItem *ivItem, SECItem *padItem) { SECStatus rv; PRFileDesc* inFile; PRFileDesc* outFile; unsigned char decbuf[64]; unsigned int decbufLen; unsigned char ptext[BLOCKSIZ...
...And 3 more matches
nss tech note5
lse, then data padding is the application's responsibility. You can find a list of cipher mechanisms in security/nss/lib/softoken/pkcs11.c - grep for CKF_EN_DE_. ...
...NSS database is NSS_NoDB_Init(".") Choose a digest mechanism. You can find a list of digest mechanisms in security/nss/lib/softoken/pkcs11.c - grep for CKF_DIGEST. ...
...C mechanism. ...
...And 3 more matches
Rhino serialization
on mode has some significant limitations. Serialization provides a way to save the state of an object and write it out to a file or send it across a network connection. Simple serialization example The Rhino shell has two new top-level functions, serialize and deserialize. They're intended mainly as examples of the use of serialization: $ java org.mozilla.javascript.tools.shell.Main js> function f
() { return 3; } js> serialize(f, "f.ser") js> quit
() $ java org.mozilla.javascript.tools.shell.Main js> f = deserialize("f.ser") function f
() { return 3;} js> f
() 3 js> Here we see a simple case of a function being serialized to a file and then read into a new instance of Rhino and called. Rhino serialization APIs Two new classes, ScriptableOutputStream and ScriptableInputStream, were introduc...
...leOutputStream and ScriptableInputStream, were introduced to handle serialization of Rhino classes. These classes extend ObjectOutputStream and ObjectInputStream respectively. ...
...So why do we need these specialized stream classes instead of simply using ObjectOutputStream and ObjectInputStream? To understand the answer we must know what goes on behind the scenes when Rhino serializes objects. ...
...And 3 more matches
GC Rooting Guide
sed to initialize a JS::Rooted<T> if there is any code that could GC before the end of the containing function; a raw pointer must never be stored on the stack during a GC. One rare but especially tricky case to watch out for is where an RAII destructor could GC in a function that is returning a bare pointer. Consider: JSObject* someFunction(JSContext* cx) { JS::Rooted<JSObject*> obj(cx, foo
()); EventLogger logger(cx); ...code... return obj; } Say that ~EventLogger constructs some sort of object in its destructor, which could trigger a GC. What will happen is that the return statement will pull the bare JSObject* out of the rooted obj variable and either put it in the stack or store it in the return value register. Then ~EventLogger will fire and trigger a GC, invalidatin...
...er a GC, invalidating that unrooted stack/register pointer. This scenario is rare but very difficult to notice manually, and will probably be caught by the static rooting hazard analysis. There are two different approaches to resolving this; use whichever better fits your situation: void someFunction(JSContext* cx, JS::MutableHandleObject obj) { EventLogger(cx); ...code... obj.set(foo
()); } (note that the above should probably check the return value and propagate an error on null), or: JSObject* someFunction(JSContext* cx) { JS::Rooted<JSObject*> obj(cx, foo
()); { // Make a scope to force the destructor to run before obj is unwrapped. EventLogger(cx); ...code... } return obj; } AutoRooters GC thing pointers that appear as part of a stack-all...
... The implementation should trace all the GC things contained in the object by calling JS::TraceEdge. GC things on the heap JS::Heap<T> GC thing pointers on the heap must be wrapped in a JS::Heap<T>. The only exception to this is if they are added as roots with the JS::PersistentRooted class, but don't do this unless it's really necessary. JS::Heap<T> pointers must also continue to be ...
...And 3 more matches
Using the Places keywords API
ference is that keywords are not bound to a specific bookmark, but to a specific URL. Using the keywords API The keywords API is a promise-based API available through the PlacesUtils module: Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils", "resource://gre/modules/PlacesUtils.jsm"); Setting a keyword for an URL The insert
() method accepts a keyword entry object describing the keyword to insert. It has the following properties: keyword: string representing the keyword url: either a URL or spec represeting the URL to associate to postData: optional POST data string. Should be omitted if there's no POST data. PlacesUtils.keywords.insert({ keyword: "my_keyword", url: "http://ww...
...ord: string representing the keyword url: either a URL or spec represeting the URL to associate to postData: optional POST data string. Should be omitted if there's no POST data. ...
... url: "http://www.example.com/" postData: "post+data=1&test=2" }).then(
() => { /* success */ }, e => { /* failure */ }); Note that setting an already existing keyword to a different URL, will silently update the existing keyword to the new URL. Fetching an entry by keyword The fetch
() method acceps a keyword string (or an object having a keywords property) and might resolve to a keyword entry with the following properties: keyword: string representing the keyword url: the URL represeted by the keyword postData: optional POST data string. Not defined if there's no POST data. If no keyword exists, will resolve to null. PlacesUtils.keywords.fetch("my_keyword").then(entry ...
...And 3 more matches
extIPreferenceBranch
mented via XPCOM service for extIApplication: see the instructions on the FUEL (Firefox), STEEL (Thunderbird) and SMILE (SeaMonkey) pages. ...
... void reset
() Attributes Attribute Type Description root readonly attribute AString The name of the branch root. all readonly attribute nsIVariant Array of extIPreference listing all preferences in this branch. events readonly attribute extIEvents The events object for the preferences supports: "change" Methods has
() Check to see if a preference exists. ...
...y attribute nsIVariant Array of extIPreference listing all preferences in this branch. events readonly attribute extIEvents The events object for the preferences supports: "change" Methods has
() Check to see if a preference exists. boolean has(in AString aName) Parameters aName The name of preference Return value true if the preference exists, false if not get
() Gets an object representing a preference extIPreference get(in AString aName) Parameters aName The name of preference Return value a preference object, or null if the preference does not exist getValue
() Gets the value of a preference. Returns a default value if the preference does not exist. nsIVariant getValue(in AString aName, in nsIVariant aDefaultValue) Parameters aName T...
...And 3 more matches
XPCShell Reference
nts) { print(prop + "=" + arguments[prop]); } Entering the following at the command line should produce the following output: $ xpcshell test.js This is a test 0=This 1=is 2=a 3=test XPCShell Extensions Once you execute XPCShell without a script you'll be at the JS> command line. ...
...ions Once you execute XPCShell without a script you'll be at the JS> command line. The following are some useful functions that can be invoked from the command line: clear(object) clear
() removes all properties from an object. For example, if you created anObject with a property named value and then called clear(anObject), the property value would no longer exist. gc(heapDumpFilename) gc
() will invoke garbage collection. It takes an optional argument that can be used to dump the heap to. If specified, it should equate to a valid filename. ...
...It dumps whatever is passed to the screen, putting spaces between arguments and appending a newline at the end. ...
...And 3 more matches
NS_ConvertASCIItoUTF16
@param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...anIndex is the ofs where you want to write the given char @return TRUE if successful Parameters PRUnichar aChar PRUint32 aIndex StripChars void StripChars(const char*) - source These methods are used to remove all occurrences of the characters found in aSet from this string. @param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace
() - source This method strips whitespace throughout the string. ReplaceChar void ReplaceChar(PRUnichar, PRUnichar) - source swaps occurence of 1 string for another Parameters PRUnichar aOldChar PRUnichar aNewChar void ReplaceChar(const char*, PRUnichar) - source Parameters char* aSet PRUnichar aNewChar ReplaceSubstring void ReplaceSubstring(const nsString&, const nsString&) ...
... given unsigned integer to this string Parameters PRUint32 aInteger PRInt32 aRadix void AppendInt(PRInt64, PRInt32) - source Parameters PRInt64 aInteger PRInt32 aRadix AppendFloat void AppendFloat(float) - source Append the given float to this string Parameters float aFloat void AppendFloat(double) - source Parameters double aFloat BeginReading PRUnichar* BeginReading
() const - source reading iterators nsReadingIterator<short unsigned int>& BeginReading(nsReadingIterator<short unsigned int>&) const - source deprecated reading iterators Parameters nsReadingIterator<short unsigned int>& iter PRUnichar*& BeginReading(const PRUnichar*&) const - source Parameters PRUnichar*& iter EndReading PRUnichar* EndReading
() const - source nsReadingIterat...
...And 3 more matches
NS_ConvertUTF16toUTF8
@param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...anIndex is the ofs where you want to write the given char @return TRUE if successful Parameters PRUnichar aChar PRUint32 aIndex StripChars void StripChars(const char*) - source These methods are used to remove all occurrences of the characters found in aSet from this string. @param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace
() - source This method strips whitespace throughout the string. ReplaceChar void ReplaceChar(char, char) - source swaps occurence of 1 string for another Parameters char aOldChar char aNewChar void ReplaceChar(const char*, char) - source Parameters char* aSet char aNewChar ReplaceSubstring void ReplaceSubstring(const nsCString&, const nsCString&) - source Parameters nsCSt...
...d the given unsigned integer to this string Parameters PRUint32 aInteger PRInt32 aRadix void AppendInt(PRInt64, PRInt32) - source Parameters PRInt64 aInteger PRInt32 aRadix AppendFloat void AppendFloat(float) - source Append the given float to this string Parameters float aFloat void AppendFloat(double) - source Parameters double aFloat BeginReading char* BeginReading
() const - source reading iterators nsReadingIterator<char>& BeginReading(nsReadingIterator<char>&) const - source deprecated reading iterators Parameters nsReadingIterator<char>& iter char*& BeginReading(const char*&) const - source Parameters char*& iter EndReading char* EndReading
() const - source nsReadingIterator<char>& EndReading(nsReadingIterator<char>&) const - source ...
...And 3 more matches
NS_ConvertUTF8toUTF16
@param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...anIndex is the ofs where you want to write the given char @return TRUE if successful Parameters PRUnichar aChar PRUint32 aIndex StripChars void StripChars(const char*) - source These methods are used to remove all occurrences of the characters found in aSet from this string. @param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace
() - source This method strips whitespace throughout the string. ReplaceChar void ReplaceChar(PRUnichar, PRUnichar) - source swaps occurence of 1 string for another Parameters PRUnichar aOldChar PRUnichar aNewChar void ReplaceChar(const char*, PRUnichar) - source Parameters char* aSet PRUnichar aNewChar ReplaceSubstring void ReplaceSubstring(const nsString&, const nsString&) ...
... given unsigned integer to this string Parameters PRUint32 aInteger PRInt32 aRadix void AppendInt(PRInt64, PRInt32) - source Parameters PRInt64 aInteger PRInt32 aRadix AppendFloat void AppendFloat(float) - source Append the given float to this string Parameters float aFloat void AppendFloat(double) - source Parameters double aFloat BeginReading PRUnichar* BeginReading
() const - source reading iterators nsReadingIterator<short unsigned int>& BeginReading(nsReadingIterator<short unsigned int>&) const - source deprecated reading iterators Parameters nsReadingIterator<short unsigned int>& iter PRUnichar*& BeginReading(const PRUnichar*&) const - source Parameters PRUnichar*& iter EndReading PRUnichar* EndReading
() const - source nsReadingIterat...
...And 3 more matches
NS_LossyConvertUTF16toASCII
@param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...anIndex is the ofs where you want to write the given char @return TRUE if successful Parameters PRUnichar aChar PRUint32 aIndex StripChars void StripChars(const char*) - source These methods are used to remove all occurrences of the characters found in aSet from this string. @param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace
() - source This method strips whitespace throughout the string. ReplaceChar void ReplaceChar(char, char) - source swaps occurence of 1 string for another Parameters char aOldChar char aNewChar void ReplaceChar(const char*, char) - source Parameters char* aSet char aNewChar ReplaceSubstring void ReplaceSubstring(const nsCString&, const nsCString&) - source Parameters nsCSt...
...d the given unsigned integer to this string Parameters PRUint32 aInteger PRInt32 aRadix void AppendInt(PRInt64, PRInt32) - source Parameters PRInt64 aInteger PRInt32 aRadix AppendFloat void AppendFloat(float) - source Append the given float to this string Parameters float aFloat void AppendFloat(double) - source Parameters double aFloat BeginReading char* BeginReading
() const - source reading iterators nsReadingIterator<char>& BeginReading(nsReadingIterator<char>&) const - source deprecated reading iterators Parameters nsReadingIterator<char>& iter char*& BeginReading(const char*&) const - source Parameters char*& iter EndReading char* EndReading
() const - source nsReadingIterator<char>& EndReading(nsReadingIterator<char>&) const - source ...
...And 3 more matches
nsFixedCString
@param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...anIndex is the ofs where you want to write the given char @return TRUE if successful Parameters PRUnichar aChar PRUint32 aIndex StripChars void StripChars(const char*) - source These methods are used to remove all occurrences of the characters found in aSet from this string. @param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace
() - source This method strips whitespace throughout the string. ReplaceChar void ReplaceChar(char, char) - source swaps occurence of 1 string for another Parameters char aOldChar char aNewChar void ReplaceChar(const char*, char) - source Parameters char* aSet char aNewChar ReplaceSubstring void ReplaceSubstring(const nsCString&, const nsCString&) - source Parameters nsCSt...
...d the given unsigned integer to this string Parameters PRUint32 aInteger PRInt32 aRadix void AppendInt(PRInt64, PRInt32) - source Parameters PRInt64 aInteger PRInt32 aRadix AppendFloat void AppendFloat(float) - source Append the given float to this string Parameters float aFloat void AppendFloat(double) - source Parameters double aFloat BeginReading char* BeginReading
() const - source reading iterators nsReadingIterator<char>& BeginReading(nsReadingIterator<char>&) const - source deprecated reading iterators Parameters nsReadingIterator<char>& iter char*& BeginReading(const char*&) const - source Parameters char*& iter EndReading char* EndReading
() const - source nsReadingIterator<char>& EndReading(nsReadingIterator<char>&) const - source ...
...And 3 more matches
nsFixedString
@param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...anIndex is the ofs where you want to write the given char @return TRUE if successful Parameters PRUnichar aChar PRUint32 aIndex StripChars void StripChars(const char*) - source These methods are used to remove all occurrences of the characters found in aSet from this string. @param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace
() - source This method strips whitespace throughout the string. ReplaceChar void ReplaceChar(PRUnichar, PRUnichar) - source swaps occurence of 1 string for another Parameters PRUnichar aOldChar PRUnichar aNewChar void ReplaceChar(const char*, PRUnichar) - source Parameters char* aSet PRUnichar aNewChar ReplaceSubstring void ReplaceSubstring(const nsString&, const nsString&) ...
... given unsigned integer to this string Parameters PRUint32 aInteger PRInt32 aRadix void AppendInt(PRInt64, PRInt32) - source Parameters PRInt64 aInteger PRInt32 aRadix AppendFloat void AppendFloat(float) - source Append the given float to this string Parameters float aFloat void AppendFloat(double) - source Parameters double aFloat BeginReading PRUnichar* BeginReading
() const - source reading iterators nsReadingIterator<short unsigned int>& BeginReading(nsReadingIterator<short unsigned int>&) const - source deprecated reading iterators Parameters nsReadingIterator<short unsigned int>& iter PRUnichar*& BeginReading(const PRUnichar*&) const - source Parameters PRUnichar*& iter EndReading PRUnichar* EndReading
() const - source nsReadingIterat...
...And 3 more matches
nsPromiseFlatCString
@param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...anIndex is the ofs where you want to write the given char @return TRUE if successful Parameters PRUnichar aChar PRUint32 aIndex StripChars void StripChars(const char*) - source These methods are used to remove all occurrences of the characters found in aSet from this string. @param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace
() - source This method strips whitespace throughout the string. ReplaceChar void ReplaceChar(char, char) - source swaps occurence of 1 string for another Parameters char aOldChar char aNewChar void ReplaceChar(const char*, char) - source Parameters char* aSet char aNewChar ReplaceSubstring void ReplaceSubstring(const nsCString&, const nsCString&) - source Parameters nsCSt...
...d the given unsigned integer to this string Parameters PRUint32 aInteger PRInt32 aRadix void AppendInt(PRInt64, PRInt32) - source Parameters PRInt64 aInteger PRInt32 aRadix AppendFloat void AppendFloat(float) - source Append the given float to this string Parameters float aFloat void AppendFloat(double) - source Parameters double aFloat BeginReading char* BeginReading
() const - source reading iterators nsReadingIterator<char>& BeginReading(nsReadingIterator<char>&) const - source deprecated reading iterators Parameters nsReadingIterator<char>& iter char*& BeginReading(const char*&) const - source Parameters char*& iter EndReading char* EndReading
() const - source nsReadingIterator<char>& EndReading(nsReadingIterator<char>&) const - source ...
...And 3 more matches
nsPromiseFlatString
@param aString is substring to be sought in this @param aIgnoreCase selects case sensitivity @param aOffset tells us where in this string to start searching @param aCount tells us how far from the offse...
...anIndex is the ofs where you want to write the given char @return TRUE if successful Parameters PRUnichar aChar PRUint32 aIndex StripChars void StripChars(const char*) - source These methods are used to remove all occurrences of the characters found in aSet from this string. @param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace
() - source This method strips whitespace throughout the string. ReplaceChar void ReplaceChar(PRUnichar, PRUnichar) - source swaps occurence of 1 string for another Parameters PRUnichar aOldChar PRUnichar aNewChar void ReplaceChar(const char*, PRUnichar) - source Parameters char* aSet PRUnichar aNewChar ReplaceSubstring void ReplaceSubstring(const nsString&, const nsString&) ...
... given unsigned integer to this string Parameters PRUint32 aInteger PRInt32 aRadix void AppendInt(PRInt64, PRInt32) - source Parameters PRInt64 aInteger PRInt32 aRadix AppendFloat void AppendFloat(float) - source Append the given float to this string Parameters float aFloat void AppendFloat(double) - source Parameters double aFloat BeginReading PRUnichar* BeginReading
() const - source reading iterators nsReadingIterator<short unsigned int>& BeginReading(nsReadingIterator<short unsigned int>&) const - source deprecated reading iterators Parameters nsReadingIterator<short unsigned int>& iter PRUnichar*& BeginReading(const PRUnichar*&) const - source Parameters PRUnichar*& iter EndReading PRUnichar* EndReading
() const - source nsReadingIterat...
...And 3 more matches
IAccessibleTableCell
[propget] ...
...[propget] HRESULT columnHeaderCells( [out, size_is(, nColumnHeaderCells,)] IUnknown cellAccessibles, [out] long nColumnHeaderCells ); Parameters cellAccessibles Pointer to an array of references to cell accessibles. The array is allocated by the server. ...
...nknown cellAccessibles, [out] long nColumnHeaderCells ); Parameters cellAccessibles Pointer to an array of references to cell accessibles. The array is allocated by the server. Free it with CoTaskMemFree. nColumnHeaderCells The number of accessibles returned; the size of the returned array. Return value S_FALSE if there is no header, [out] values are null and 0 respectively. S_OK. columnIndex
() Translates this cell accessible into the corresponding column index. [propget] HRESULT columnIndex( [out] long columnIndex ); Parameters columnIndex Returns the 0 based column index of the cell of the specified cell or the index of the first column if the cell spans multiple columns. Return value S_OK. isSelected
() Returns a boolean value indicating whether this cell is selected. [propget] H...
...And 3 more matches
mozIStorageValueArray
unsigned long The number of entries in the array. Constants Constant Value Description VALUE_TYPE_NULL 0 Null data type. VALUE_TYPE_INTEGER 1 INTEGER data type. VALUE_TYPE_FLOAT 2 FLOAT data type. VALUE_TYPE_TEXT 3 TEXT data type. VALUE_TYPE_BLOB 4 BLOB data type. Methods getTypeOfIndex
() Returns the type of the value at the given column index. long getTypeOfIndex( in unsigned long aIndex ); Parameters aIndex The zero-based numerical index for the column to get the data from. Return value One of the constants mozIStorageValueArray.VALUE_TYPE_NULL, mozIStorageValueArray.VALUE_TYPE_INTEGER, mozIStorageValueArray.VALUE_TYPE_FLOAT, mozIStorageValueArray.VALUE_TYPE_...
... unsigned long aIndex ); Parameters aIndex The zero-based numerical index for the column to get the data from. Return value One of the constants mozIStorageValueArray.VALUE_TYPE_NULL, mozIStorageValueArray.VALUE_TYPE_INTEGER, mozIStorageValueArray.VALUE_TYPE_FLOAT, mozIStorageValueArray.VALUE_TYPE_TEXT, or mozIStorageValueArray.VALUE_TYPE_BLOB describing the type aIndex is. getInt32
() Obtains a Int32 from the specified index. long getInt32( in unsigned long aIndex ); Parameters aIndex The zero-based numerical index for the column to get the data from. Return value The int32 for the specified entry. getInt64
() Obtains a int64 from the specified index. long long getInt64( in unsigned long aIndex ); Parameters aIndex The zero-based numerical index fo...
...rameters aIndex The zero-based numerical index for the column to get the data from. Return value The int32 for the specified entry. getInt64
() Obtains a int64 from the specified index. long long getInt64( in unsigned long aIndex ); Parameters aIndex The zero-based numerical index for the column to get the data from. Return value The int64 for the specified entry. getDouble
() Obtains a double from the specified index. double getDouble( in unsigned long aIndex ); Parameters aIndex The zero-based numerical index for the column to get the data from. Return value The double for the specified entry. getUTF8String
() Obtains a UTF8String from the specified index. Note: C++ callers should be aware that a string value for a NULL column has IsVoid set to dist...
...And 3 more matches
mozIVisitInfoCallback
void handleError( in nsresult aResultCode, in mozIPlaceInfo aPlaceInfo ); Parameters aResultCode nsresult indicating the reason...
....0 Inherits from: nsISupports Last changed in Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) Method overview void handleError(in nsresult aResultCode, in mozIPlaceInfo aPlaceInfo); void handleResult(in mozIPlaceInfo aPlaceInfo); void onComplete(in nsresult aResultCode, in mozIPlaceInfo aPlaceInfo);Obsolete since Gecko 8.0 Methods handleError
() Called when a mozIPlaceInfo couldn't be processed. void handleError( in nsresult aResultCode, in mozIPlaceInfo aPlaceInfo ); Parameters aResultCode nsresult indicating the reason why the change failed. aPlaceInfo The information that was unable to be processed. handleResult
() Called for each visit added, title change, or GUID change when passed to mozIAsyncHistory.updatePla...
...lled when a mozIPlaceInfo couldn't be processed. void handleError( in nsresult aResultCode, in mozIPlaceInfo aPlaceInfo ); Parameters aResultCode nsresult indicating the reason why the change failed. aPlaceInfo The information that was unable to be processed. handleResult
() Called for each visit added, title change, or GUID change when passed to mozIAsyncHistory.updatePlaces
(). ...
...And 3 more matches
nsIBinaryOutputStream
void w...
... void writeFloat(in float aFloat); void writeStringZ(in string aString); void writeUtf8Z(in wstring aString); void writeWStringZ(in wstring aString); Methods setOutputStream
() Sets the stream to which output is directed. void setOutputStream( in nsIOutputStream aOutputStream ); Parameters aOutputStream Instance of the nsIOutputStream object to which output should be directed. write8
() Writes an 8-bit integer to the stream. void write8( in PRUint8 aByte ); Parameters aByte The byte to write to the stream. write16
() Writes a 16-bit integer to the stream. void write16( in PRUint16 a16 ); Parameters a16 The 16-bit integer to write to the stream. write32
() Writes a 32-bit integer to the stream. void write32( in PRUint32 a32 ); Parameters a32 The 32-bit integer to writ...
...to the stream. void write8( in PRUint8 aByte ); Parameters aByte The byte to write to the stream. write16
() Writes a 16-bit integer to the stream. void write16( in PRUint16 a16 ); Parameters a16 The 16-bit integer to write to the stream. write32
() Writes a 32-bit integer to the stream. void write32( in PRUint32 a32 ); Parameters a32 The 32-bit integer to write to the stream. write64
() Writes a 64-bit integer to the stream. void write64( in PRUint64 a64 ); Parameters a64 The 64-bit integer to write to the stream. writeBoolean
() Writes a boolean value (as a byte) to the stream. ...
...And 3 more matches
nsICacheSession
g with evicting cache entries and checking for cache devices instantiation according to the session storage policies. Inherits from: nsISupports Last changed in Gecko 14 (Firefox 14 / Thunderbird 14 / SeaMonkey 2.11) Method overview void asyncOpenCacheEntry(in ACString key, in nsCacheAccessMode accessRequested, in nsICacheListener listener, [optional] in boolean noWait); void evictEntries
(); PRBool isStorageEnabled
(); nsICacheEntryDescriptor openCacheEntry(in ACString key, in nsCacheAccessMode accessRequested, in boolean blockingMode); void doomEntry(in ACString key, in nsICacheListener listener); Attributes Attribute Type Description doomEntriesIfExpired PRBool Expired entries will be doomed or evicted if this attribute is set to true. If false, expired entries will ...
...key, in nsICacheListener listener); Attributes Attribute Type Description doomEntriesIfExpired PRBool Expired entries will be doomed or evicted if this attribute is set to true. If false, expired entries will be returned (useful for offline mode and clients, such as HTTP, that can update the valid lifetime of cached content). This attribute defaults to true. Methods asyncOpenCacheEntry
() This method gives an asynchronous cache access. Does not block the calling thread. Instead, the listener will be notified when the descriptor is available. void asyncOpenCacheEntry( in ACString key, in nsCacheAccessMode accessRequested, in nsICacheListener listener, [optional] in boolean noWait ); Parameters key The key for cache entry. accessRequested The requested access. listener The...
...en the descriptor is available. void asyncOpenCacheEntry( in ACString key, in nsCacheAccessMode accessRequested, in nsICacheListener listener, [optional] in boolean noWait ); Parameters key The key for cache entry. accessRequested The requested access. listener The cache listener to be notified. noWait Do not wait for the cache entry when it is in use and waits for validation. ...
...And 3 more matches
nsICollection
xpcom/ds/nsICollection.idlScriptable This interface represents a list of nsISupports items. It provides basic operations on those items like: getting, setting, appending, removing, and so on. Inherits from: nsISerializable Last changed in Gecko 1.7 Method overview void AppendElement(in nsISupports item); void Clear
(); PRUint32 Count
(); nsIEnumerator Enumerate
(); nsISupports GetElementAt(in PRUint32 index); void QueryElementAt(in PRUint32 index, in nsIIDRef uuid, [iid_is(uuid),retval] out nsQIResult result); void RemoveElement(in nsISupports item); void SetElementAt(in PRUint32 index, in nsISupports item); Methods AppendElement
() Appends a new item to the collection. void AppendElement( in nsISuppo...
...ElementAt(in PRUint32 index, in nsIIDRef uuid, [iid_is(uuid),retval] out nsQIResult result); void RemoveElement(in nsISupports item); void SetElementAt(in PRUint32 index, in nsISupports item); Methods AppendElement
() Appends a new item to the collection. void AppendElement( in nsISupports item ) Parameters item nsISupports item to be appended to the list. Clear
() Removes all items from the collection. void Clear
(); Parameters None. Count
() Returns the number of items in the collection. PRUint32 Count
(); Parameters None. ...
...nsISupports GetElementAt( in PRUint32 index ); Parameters index The index position of the item to be returned. ...
...And 3 more matches
nsICommandLine
a different working directory. Read only. Constants State constants Constant Value Description STATE_INITIAL_LAUNCH 0 The first launch of the application instance. STATE_REMOTE_AUTO 1 A remote command line automatically redirected to this instance. STATE_REMOTE_EXPLICIT 2 A remote command line explicitly redirected to this instance using xremote/windde/appleevents. ...
...On Windows, flags of the form /flag are normalized to -flag. /flag:param are normalized to -flag param. On Unix/Linux and Mac OS X, flags of the form --flag are normalized to -flag, and flags of the form --flag=param are normalized to the form -flag param. ...
...getArgument( in long aIndex ); Parameters aIndex The argument to retrieve. This index is 0-based, and does not include the application name. Return value The value of the specified argument. This is the full text of that argument, so if the argument is a flag, the returned value is "-flag [<flagvalue>]". Exceptions thrown NS_ERROR_INVALID_ARG The specified index is out of bounds. handleFlag
() Finds the specified flag, removing it from the array of flags. Reports whether or not the specified flag was found. This is useful for Boolean flags; that is, flags that don't accept a parameter. You can determine if the flag was provided and remove it from the list of flags waiting to be processed in one operation. boolean handleFlag( in AString aFlag, in boolean aCaseSensitive ); Parameter...
...And 3 more matches
nsIDNSService
ls" strategy is used to reduce lengthy timeouts when attempting backup connections during attempts to connect from clients that have broken IPv6 connectivity. This is done by disabling IPv6 on backup connections. ...
...broken IPv6 connectivity. This is done by disabling IPv6 on backup connections. Method overview nsICancelable asyncResolve(in AUTF8String aHostName, in unsigned long aFlags, in nsIDNSListener aListener, in nsIEventTarget aListenerTarget); void init
(); Obsolete since Gecko 1.8 nsIDNSRecord resolve(in AUTF8String aHostName, in unsigned long aFlags); void shutdown
(); Obsolete since Gecko 1.8 Attributes Attribute Type Description myHostName AUTF8String Read only. Constants Resolve flag constants Various flags that may be ORed together to form the aFlags parameter passed to asyncResolve
() and resolve
(). Constant Value Description RESOLVE_BYPASS_CACHE (1 << 0) This flag suppresses the inter...
... RESOLVE_PRIORITY_LOW (1 << 3) The query is given lower priority. If used with medium, medium takes precedence. RESOLVE_SPECULATE (1 << 4) Indicates request is speculative. Speculative requests return errors if prefetching is disabled by configuration. RESOLVE_DISABLE_IPV6 (1 << 5) If this flag is set, only IPv4 addresses will be returned by asyncResolve
() and resolve
(). Methods asyncResolve
() Begins off an asynchronous host lookup. A specified nsIDNSListener is invoked when the resolution process is completed. nsICancelable asyncResolve( in AUTF8String aHostName, in unsigned long aFlags, in nsIDNSListener aListener, in nsIEventTarget aListenerTarget ); Parameters aHostName The host name or IP-address-literal to resolve. ...
...And 3 more matches
nsIDOMNode
dom/interfaces/core/nsIDOMNode.idlScriptable This interface is the primary datatype for the entire Document Object Model. It represents a single node in the document tree. Inherits from: nsISupports Last changed in Gecko 0.9.6 Method overview nsIDOMNode appendChild(in nsIDOMNode newChild) nsIDOMNode cloneNode(in boolean deep); boolean hasAttributes
(); boolean hasChildNodes
(); nsIDOMNode insertBefore(in nsIDOMNode newChild, in nsIDOMNode refChild) boolean isSupported(in DOMString feature, in DOMString version); void normalize
(); nsIDOMNode removeChild(in nsIDOMNode oldChild) nsIDOMNode replaceChild(in nsIDOMNode newChild, in nsIDOMNode oldChild) Attributes Attribute Type Description attributes nsIDOMNamedNodeMap Read only. childNodes nsIDOMNodeList...
...refix DOMString previousSibling nsIDOMNode Read only. ...
... ELEMENT_NODE 1 ATTRIBUTE_NODE 2 TEXT_NODE 3 CDATA_SECTION_NODE 4 ENTITY_REFERENCE_NODE 5 ENTITY_NODE 6 PROCESSING_INSTRUCTION_NODE 7 COMMENT_NODE 8 DOCUMENT_NODE 9 DOCUMENT_TYPE_NODE 10 DOCUMENT_FRAGMENT_NODE 11 NOTATION_NODE 12 Methods appendChild
() nsIDOMNode appendChild( in nsIDOMNode newChild ); Parameters newChild Return value cloneNode
() nsIDOMNode cloneNode( in boolean deep ); Parameters deep Return value hasAttributes
() boolean hasAttributes
(); Parameters None. Return value hasChildNodes
() boolean hasChildNodes
(); Parameters None. Return value insertBefore
() nsIDOMNode insertBefore( in nsIDOMNode newChild, in nsIDOMNode refChild ); Parameters newChild refChild Return value isSupported
() boolean isSupported(...
...And 3 more matches
nsIDOMStorage
lue pairs, which may be retrieved, modified and removed as needed. A key may only exist once within a storage object, and only one value may be associated with a particular key. Keys are stored in a particular order with the condition that this order not change by merely changing the value associated with a key, but the order may change when a key is added or removed. ...
...DOMString getItem( in DOMString key ); Parameters key The key for which data should be returned. ...
...lear
(); DOMString getItem(in DOMString key); DOMString key(in unsigned long index); void removeItem(in DOMString key); void setItem(in DOMString key, in DOMString data); Attributes Attribute Type Description length unsigned long The number of keys stored in the session store. Read only. Methods clear
() Clear the content of this storage bound to a domain or an origin. void clear
(); Parameters None. getItem
() Returns from session storage the data corresponding to the specified key. DOMString getItem( in DOMString key ); Parameters key The key for which data should be returned. Return value An nsIDOMStorageItem object describing the data corresponding to the specified key, or null if no data exists for the given key. ...
...And 3 more matches
nsIDOMWindow
a subclass of nsIDOMWindow that adds some new features to this interface. In Gecko 7.0 nsIDOMWindow2 has been merged into this interface. In Gecko 8.0 nsIDOMStorageWindow and nsIDOMWindowInternal have been merged into this interface. ...
...Read only. Note: Prior to Gecko 7.0 this attribute was part of nsIDOMWindow2. ...
...ntent boundaries. This attribute is "replaceable" in JavaScript. Read only. windowRoot nsIDOMEventTarget The window root for this window. This is useful for connecting event listeners to this window as well as every other window nested in that window root. Read only. Native code only! Note: Prior to Gecko 7.0 this attribute was part of nsIDOMWindow2. Methods getComputedStyle
() See dom-window-getcomputedstyle for details. nsIDOMCSSStyleDeclaration getComputedStyle( in nsIDOMElement elt, in DOMString pseudoElt Optional ); Parameters elt pseudoElt Optional Return value getSelection
() Returns the nsISelection object indicating what if any content is currently selected in the window. nsISelection getSelection
(); Parameters None. Return value Th...
...And 3 more matches
nsIHttpChannelInternal
true to notify the channel that it is open on behalf of a download. documentURI nsIURI An HTTP channel can own a reference to the document URI. forceAllowThirdPartyCookie boolean Force relevant cookies to be sent with this load even if normally they would not be. localAddress AUTF8String The local IP address to which the channel is bound, in the same format produced by PR_NetAddrToString
(). This may be either an IPv4 or IPv6 address. Note: If Network Address Translation (NAT) is in effect, this may not be the same address the remote host thinks it is talking to. This may throw an NS_ERROR_NOT_AVAILABLE exception if accessed when the channel's endpoints haven't been determined yet, or any time the nsIHttpActivityObserver.isActive attribute is false. See bug 534698 and bug 526207. Re...
... endpoints haven't been determined yet, or any time the nsIHttpActivityObserver.isActive attribute is false. See bug 534698 and bug 526207. Read only. proxyInfo nsIProxyInfo Get the proxy info in use by the channel. Read only. Obsolete since Gecko 1.9 remoteAddress AUTF8String The IP address of the remote host to which this channel is bound, in the same format produced by PR_NetAddrToString
(). This may throw an NS_ERROR_NOT_AVAILABLE exception if accessed when the channel's endpoints haven't been determined yet, or any time the nsIHttpActivityObserver.isActive attribute is false. See bug 534698 and bug 526207. Read only. remotePort PRInt32 The remote port number to which the channel is bound. This may throw an NS_ERROR_NOT_AVAILABLE exception if accessed when the channel's endpoin...
...attribute is false. See bug 534698 and bug 526207. Read only. remotePort PRInt32 The remote port number to which the channel is bound. This may throw an NS_ERROR_NOT_AVAILABLE exception if accessed when the channel's endpoints haven't been determined yet, or any time the nsIHttpActivityObserver.isActive attribute is false. See bug 534698 and bug 526207. Read only. Methods getRequestVersion
() Gets the request's major and minor version numbers. void getRequestVersion( out unsigned long major, out unsigned long minor ); Parameters major On return, contains the request's major version number. minor On return, contains the request's minor version number. getResponseVersion
() Gets the response's major and minor version numbers. void getResponseVersion( out unsigned long major, o...
...And 3 more matches
nsIHttpServer
An example : https://github.com/laurentj/slimerjs/blob/master/src/modules/webserver.jsm var EXPORTED_SYMBOLS = ["create"]; Components.utils.import("resource://gre/modules/Services.jsm"); function create
() { var server = Components.classes["@mozilla.org/server/jshttp;1"] .createInstance(Components.interfaces.nsIHttpServer); return { get objectName
() { return "WebServer"; }, /** * @param integer|string port port or "host:port" * @param object opt optional options. (not supported) * @param function callback optional callback */ listen: function(port, opt, callback) { if (arguments.length == 2 && "function" == typeof opt) { ...
... * * @para...
... * * @param port * the port upon which li...
...And 3 more matches
nsIJumpListBuilder
widget/public/nsIJumpListBuilder.idlScriptable Please add a summary to this article. 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Jump lists are built and then applied. Modifying an applied jump list is not permitted. Callers should begin the creation of a new jump list using initListBuild
(), add sub lists using addListToBuild
(), then commit the jump list using commitListBuild
(). Lists are built in real-time during the sequence of build calls, make sure to check for errors on each individual step. The default number of allowed items in a jump list is ten. Users can change the number through system preferences. User may also pin items to jump lists, which take up additional slots. App...
... lists, which take up additional slots. Applications do not have control over the number of items allowed in jump lists; excess items added are dropped by the system. Item insertion priority is defined as first to last added. Users may remove items from jump lists after they are committed. The system tracks removed items between commits. A list of these items is returned by a call to initListBuild
(). nsIJumpListBuilder does not filter entries added that have been removed since the last commit. To prevent repeatedly adding entires users have removed, applications are encouraged to track removed items internally. Each list is made up of an array of nsIWinJumpListItems representing items such as shortcuts, links, and separators. See nsIJumpListItem for information on adding additional jump list...
...dded that have been removed since the last commit. To prevent repeatedly adding entires users have removed, applications are encouraged to track removed items internally. Each list is made up of an array of nsIWinJumpListItems representing items such as shortcuts, links, and separators. See nsIJumpListItem for information on adding additional jump list types. Method overview void abortListBuild
(); boolean addListToBuild(in short aCatType, in nsIArray items Optional, in AString catName Optional); boolean commitListBuild
(); boolean deleteActiveList
(); boolean initListBuild(in nsIMutableArray removedItems); Attributes Attribute Type Description available short Indicates whether jump list taskbar features are supported by the current host. Read only. isListCommitted boolean ...
...And 3 more matches
nsIObserver
xpcom/ds/nsIObserver.idlScriptable This interface is implemented by an object that wishes to observe notifications. These notifications are often, though not always, broadcast via the nsIObserverService. Inherits from: nsISupports Last changed in Gecko 0.9.6 Method overview void observe(in nsISupports aSubject, in string aTopic, in wstring aData); Methods observe
() This method will be called when there is a notification for the topic that the observer has been registered for. If you expect multiple topics/subjects, the implementor is responsible for filtering. You should not modify, add, remove, or enumerate notifications in the implementation of this method. void observe( in nsISupports aSubject, in string aTopic, in wstring aData ); Parameters...
...upport these operations correctly within Observe. Example The following code is an implementation of nsIObserver that is registered to receive notifications for the "myTopicID" topic. See Observer Notifications for a list of built-in topics possible. Observing preferences works slightly differently. See Code snippets:Preferences - Using preference observers for an example. ...
...ons correctly within Observe. Example The following code is an implementation of nsIObserver that is registered to receive notifications for the "myTopicID" topic. See Observer Notifications for a list of built-in topics possible. Observing preferences works slightly differently. See Code snippets:Preferences - Using preference observers for an example. ...
...And 3 more matches
nsIProcess
x 4 / Thunderbird 3.3 / SeaMonkey 2.1) Implemented by: @mozilla.org/process/util;1. ...
... name of the process. Read only. Gecko 1.9.1 note This attribute is no longer implemented as of Gecko 1.9.1, and is removed entirely in Gecko 1.9.2. processSignature unsigned long The process signature. Read only. Gecko 1.9.1 note This attribute is no longer implemented as of Gecko 1.9.1, and is removed entirely in Gecko 1.9.2. Methods init
() Initializes the nsIProcess with the specified executable file. Once initialized, you can start the process executing by calling run
(). Note: This function does not work with application bundles on Mac OS X, see bug 307463 for details. void init( in nsIFile executable ); Parameters executable The nsIFile executable file to be represented by the nsIProcess object. initWithPid(...
... Obsolete since Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Initializes the nsIProcess to represent an existing process, given that process's ID. Gecko 1.9.1 note This method is no longer implemented as of Gecko 1.9.1, and is removed entirely in Gecko 1.9.2. void initWithPid( in unsigned long pid ); Parameters pid The process ID to begin to represent. kill
() Immediately terminates the process represented by the nsIProcess object. This only works if the process was run without blocking enabled. Gecko 1.9.1 note Prior to Gecko 1.9.1 (Firefox 3.5), this method did not work on Windows or Mac OS X. Now it does. void kill
(); Parameters None. run
() Starts executing the process. Gecko 1.9.1 note Prior to Gecko 1.9.1 (Firefox 3.5), this me...
...And 3 more matches
nsISHistory
Read only. index long The index of the current document in session history. Read only. maxLength long Used to Get/Set the maximum number ...
...ing the value -1 is returned. Read only. SHistoryEnumerator nsISimpleEnumerator Called to obtain a enumerator for all the documents stored in session history. The enumerator object thus returned by this method can be traversed using nsISimpleEnumerator. To access individual history entries of the enumerator, perform the following steps: Call GetSHistoryEnumerator
() to obtain handle the nsISimpleEnumerator object. Use nsISimpleEnumerator.GetNext
() on the object returned by step #1 to obtain handle to the next object in the list. The object returned by this step is of type nsISupports. Perform a QueryInterface on the object returned by step #2 to nsISHEntry. Use nsISHEntry to access properties of each history entry. Read only. Me...
...Listeners are notified when pages are loaded or purged from history. Note: A listener object must implement nsISHistoryListener and nsSupportsWeakReference. ...
...And 3 more matches
nsIScriptError
tError = Components.classes["@mozilla.org/scripterror;1"] .createInstance(Components.interfaces.nsIScriptError); Note: The nsIScriptError2 interface was merged into this interface in Gecko 12.0. Prior to that release, if you wanted to associate an outer window with a script error, you had to use nsIScriptError2 instead. That subclass offered the nsIScriptError.initWithWindowID
() method for that purpose; that method is now available in this interface, however. Method overview void init(in wstring message, in wstring sourceName, in wstring sourceLine, in PRUint32 lineNumber, in PRUint32 columnNumber, in PRUint32 flags, in string category); void initWithWindowID(in wstring message, in wstring sourceName, in wstring sourceLine, in PRUint32 lineNumber, in...
...Read only. columnNumber PRUint32 The column number where the error occurred. This is used to draw the arrow pointing to the problem character. Read only. errorMessage AString The error mes...
...e number information. Note: nsIConsoleMessage.message will return the error formatted with file/line information. Read only. flags PRUint32 Flags; see Flag constants for a list. Read only. innerWindowID unsigned long long The inner window ID with which the error is associated. This is zero if the error was initialized by calling nsIScriptError.init
() instead of initWithWindowID
(). Read only. lineNumber PRUint32 The number of the line where the error occurred. Read only. outerWindowID unsigned long long The window ID with which the error is associated. This is zero if the error was initialized by calling nsIScriptError.init
() instead of initWithWindowID
(). Read only. sourceLine AString The line fr...
...And 3 more matches
nsIServerSocket
It will asynchronously listen for and accept client conn...
...It will asynchronously listen for and accept client connections. The listener will be notified once for each client connection that is accepted. The liste...
... void initWithAddress([const] in PRNetAddrPtr aAddr, in long aBackLog);Native code only! void close
(); void asyncListen(in nsIServerSocketListener aListener); PRNetAddr getAddress
();Native code only! Attributes Attribute Type Description port long Returns the port of this server socket. Read only. Methods asyncListen
() This method puts the server socket in the listening state. It will asynchronously listen for and accept client connections. The listener will be notified once for each client connection that is accepted. The listener's onSocketAccepted
() method will be called on the same thread that called asyncListen
() (the calling thread must have an nsIEventTarget). The listener will be passed a reference to...
...And 3 more matches
nsIServiceManager
Unlike createInstance, this will always return the same object each time it is called with the same arguments. void getService( in nsCIDRef aClass, in nsIIDRef aIID, [iid_is(aIID),retval] out nsQIResult result ); Parameters aClass The ClassID of the service that is being requested. aIID ...
...id getService( in nsCIDRef aClass, in nsIIDRef aIID, [iid_is(aIID),retval] out nsQIResult result ); Parameters aClass The ClassID of the service that is being requested. aIID The interface type to be returned. result The resulting interface pointer. Exceptions thrown NS_ERROR_FACTORY_NOT_REGISTERED Indicates that the specified class is not registered. getServiceByContractID
() This method returns a reference to a particular XPCOM service given the ContractID of the service. void getServiceByContractID( in string aContractID, in nsIIDRef aIID, [iid_is(aIID),retval] out nsQIResult result ); Parameters aContractID The ContractID of the service that is being requested. aIID The interface type to be returned. result The resulting interface pointer. Excep...
...tID( in string aContractID, in nsIIDRef aIID, [iid_is(aIID),retval] out nsQIResult result ); Parameters aContractID The ContractID of the service that is being requested. aIID The interface type to be returned. result The resulting interface pointer. Exceptions thrown NS_ERROR_FACTORY_NOT_REGISTERED Indicates that the specified class is not registered. isServiceInstantiated
() This method tests whether or not a XPCOM service, identified by ClassID, has been instantiated. boolean isServiceInstantiated( in nsCIDRef aClass, in nsIIDRef aIID ); Parameters aClass The ClassID of the service that is being tested. aIID The interface type to be tested. Return value true if the service has already been created. Exceptions thrown NS_ERROR_SERVICE_NOT_AVAILABL...
...And 3 more matches
nsISocketTransportService
Obsolete since Gecko 1.8 Metho...
...Obsolete since Gecko 1.8 Methods Native code only! attachSocket Adds a new socket to the list of controlled sockets. This will fail with the error code NS_ERR...
... boolean controls whether or not the socket transport service should poke the autodialer on connection failure. Obsolete since Gecko 1.8 Methods Native code only! attachSocket Adds a new socket to the list of controlled sockets. This will fail with the error code NS_ERROR_NOT_AVAILABLE if the maximum number of sockets is already reached. ...
...And 3 more matches
nsITaskbarPreviewController
. Depending on whether the controller is connected to an nsITaskbarTabPreview or nsITaskbarWindowPreview, only certain methods and attributes need to be implemented. Method overview boolean drawPreview(in nsIDOMCanvasRenderingContext2D ctx); boolean drawThumbnail(in nsIDOMCanvasRenderingContext2D ctx, in unsigned long width, in unsigned long height); boolean onActivate
(); void onClick(in nsITaskbarPreviewButton button); void onClose
(); Attributes Attribute Type Description height unsigned long The height in pixels of the preview image. This value may change at any time. See drawPreview
() for more information. Read only. thumbnailAspectRatio float The thumbnail's aspect ratio. This doesn't need...
...Read only. ...
...See drawPreview
() for more information. Read only. thumbnailAspectRatio float The thumbnail's aspect ratio. This doesn't need to match the preview's aspect ratio, and is allowed to be changed at any time. See drawThumbnail
() for more information. Read only. width unsigned long The width in pixels of the preview image. This value may change at any time. See drawPreview
() for more information. Read only. Note: Although these attributes are read only, that indicates that the previews controlled by an nsITaskbarPreviewController cannot alter these values. The controller and its supporting code, however, may change this values at any time. Methods drawPreview
() Invoked by nsITaskbarPreview when it needs to render the preview. The specified context is attach...
...And 3 more matches
nsIURLParser
a null terminated string, in which case the length argument should be -1. Out parameters of the methods are all optional (that is the caller may pass-in a null value if the corresponding results are not needed). Signed out parameters may hold a value of -1 if the corresponding result is not part of the string being parsed. The parsing routines attempt to be as forgiving as possible. parseAuthority
() Breaks the authority string up into its 4 components: username, password, hostname, and hostport. auth = <username>:<password>@<hostname>:<port> void parseAuthority( in string authority, in long authorityLen, out unsigned long usernamePos, out long usernameLen, out unsigned long passwordPos, out long passwordLen, out unsigned long hostnamePos, out long hostnameLen, out long port...
...port> void parseAuthority( in string authority, in long authorityLen, out unsigned long usernamePos, out long usernameLen, out unsigned long passwordPos, out long passwordLen, out unsigned long hostnamePos, out long hostnameLen, out long port ); Parameters authority authorityLen usernamePos usernameLen passwordPos passwordLen hostnamePos hostnameLen port parseFileName
() filename = <basename>.<extension> void parseFileName( in string filename, in long filenameLen, out unsigned long basenamePos, out long basenameLen, out unsigned long extensionPos, out long extensionLen ); Parameters filename filenameLen basenamePos basenameLen extensionPos extensionLen parseFilePath
() Breaks the file path string up into: the directory portion, file base name,...
...path = <filepath>;<param>?<query>#<ref> void parsePath( in string path, in long pathLen, out unsigned long filepathPos, out long filepathLen, out unsigned long paramPos, // Removed in Gecko 9.0 out long paramLen, // Removed in Gecko 9.0 out unsigned long queryP...
...And 3 more matches
nsIWebBrowserPersist
6.0 / SeaMonkey 2.33) Implemented by: @mozilla.org/embedding/browser/nsWebBrowser;1 and @mozilla.org/embedding/browser/nsWebBrowserPersist;1. ...
...lder products that don't support ? and friends. ENCODE_FLAGS_ENCODE_LATIN1_ENTITIES 16384 Encode Latin1 entities. This includes the basic set and accented letters between 128 and 255. ENCODE_FLAGS_ENCODE_HTML_ENTITIES 32768 Encode HTML4 entities. This includes the basic set, accented letters, Greek letters and certain special markup symbols. Methods cancelSave
() Cancels the current operation. The caller is responsible for cleaning up partially written files or directories. This has the same effect as calling cancel with an argument of NS_BINDING_ABORTED. void cancelSave
(); Parameters None. saveChannel
() Save a channel to a file. It must not be opened yet. void saveChannel( in nsIChannel aChannel, in nsISupports aFile ); Parameters aChann...
...ncel with an argument of NS_BINDING_ABORTED. void cancelSave
(); Parameters None. saveChannel
() Save a channel to a file. It must not be opened yet. void saveChannel( in nsIChannel aChannel, in nsISupports aFile ); Parameters aChannel The nsIChannel to save to a file. aFile Target local file. This may be a nsILocalFile object or an nsIURI object with a file scheme. saveDocument
() Save the specified DOM document to file and optionally all linked files (for example images, CSS, JS & subframes). Do not call this method until the document has finished loading! void saveDocument( in nsIDOMDocument aDocument, in nsISupports aFile, in nsISupports aDataPath, in string aOutputContentType, in unsigned long aEncodingFlags, in unsigned long aWrapColumn ); Parameters ...
...And 3 more matches
nsIWebProgress
ociated with this nsIWebProgress instance. Read only. Exceptions thrown NS_ERROR_FAILURE Indicates that there is no associated DOM window. isLoadingDocument PRBool Indicates whether or not a document is currently being loaded in the context of this nsIWebProgress instance. Read only. ...
... currently being loaded in the context of this nsIWebProgress instance. Read only. Constants The following flags may be combined to form the aNotifyMask parameter for the addProgressListener
() method. They limit the set of events that are delivered to an nsIWebProgressListener instance. These flags indicate the state transistions to observe, corresponding to nsIWebProgressListener.onStateChange
(). Constant Value Description NOTIFY_STATE_REQUEST 0x00000001 Only receive the nsIWebProgressListener.onStateChange
() event if the aStateFlags parameter includes nsIWebProgressListener::STATE_IS_REQUEST. NOTIFY_STATE_DOCUMENT 0x00000002 Only receive the nsIWebProgressListener.onStateChange
() event if the aStateFlags parameter includes nsIWebProgressListener::STATE_IS_DOCUMENT. NOTIFY_STATE...
...ceive the nsIWebProgressListener.onStateChange
() event if the aStateFlags parameter includes nsIWebProgressListener::STATE_IS_REQUEST. NOTIFY_STATE_DOCUMENT 0x00000002 Only receive the nsIWebProgressListener.onStateChange
() event if the aStateFlags parameter includes nsIWebProgressListener::STATE_IS_DOCUMENT. NOTIFY_STATE_NETWORK 0x00000004 Only receive the nsIWebProgressListener.onStateChange
() event if the aStateFlags parameter includes nsIWebProgressListener::STATE_IS_NETWORK. NOTIFY_STATE_WINDOW 0x00000008 Only receive the nsIWebProgressListener.onStateChange
() event if the aStateFlags parameter includes nsIWebProgressListener::STATE_IS_WINDOW. NOTIFY_STATE_ALL 0x0000000f Receive all nsIWebProgressListener.onStateChange
() events. These flags indicate the other events to observ...
...And 3 more matches
nsIWinTaskbar
in the application; they can vary in size, shape, and location. They don't even have to represent actual GUI elements on the window. Unlike window previews, tab previews require most of the functionality of the nsITaskbarPreviewController interface be implemented. Warning: This API has undergone changes that are not yet documented. Among these is the addition of the method getOverlayIconController
(). This method is currently known to crash if used under certain conditions. See bug 744992 for details and to track progress on a fix. Implemented by: @mozilla.org/windows-taskbar;1. To create an instance, use: var winTaskbar = Components.classes["@mozilla.org/windows-taskbar;1"] .getService(Components.interfaces.nsIWinTaskbar); Method overview nsIJumpListBuilder createJumpLis...
...ethod is currently known to crash if used under certain conditions. See bug 744992 for details and to track progress on a fix. Implemented by: @mozilla.org/windows-taskbar;1. ...
... attribute is configured using application.ini settings, and is of the format "vendor.application.version". For example, if the Vendor is configured to "Foobar Systems", the application's Name is "Squashweb", and the application's Version is 1.0, the defaultGroupId attribute would be "Foobar Systems.Squashweb.1.0". See XUL Application Packaging for additional details. ...
...And 3 more matches
nsIXULTemplateResult
ally, the result and its id will be able to uniquely identify a node in the source data, such as an RDF or XML node. In other contexts, such as a database query, a result would represent a particular record. A result is expected to only be created by a query processor. Each result also contains a set of variable bindings. ...
...d will be able to uniquely identify a node in the source data, such as an RDF or XML node. In other contexts, such as a database query, a result would represent a particular record. A result is expected to only be created by a query processor. Each result also contains a set of variable bindings. The value for a particular variable may be retrieved using the getBindingFor
() and getBindingObjectFor
() methods. Method overview AString getBindingFor(in nsIAtom aVar); nsISupports getBindingObjectFor(in nsIAtom aVar); void hasBeenRemoved
(); void ruleMatched(in nsISupports aQuery, in nsIDOMNode aRuleNode); Attributes Attribute Type Description id AString ID of the result. T...
...ly. resource nsIRDFResource Resource for the result, which may be null. If set, the resource uri must be the same as the ID property. Read only. type AString The type of the object. The predefined value 'separator' may be used for separators. Other values may be used for application specific purposes. Read only. Methods getBindingFor
() Get the string representation of the value of a variable for this result. This string will be used in the action body from a template as the replacement text. For instance, if the text ?name appears in an attribute within the action body, it will be replaced with the result of this method. The question mark is considered part of the variable name, thus aVar should be ?name and not simply name. AS...
...And 3 more matches
Setting HTTP request headers
above code was changed to reflect that in a FireFox Add-On one can not directly access Components.interfaces und Components.classes anymore but must use the require line introduced to the sample code above. So where you see Ci and Cc in this page there used to be Components.interfaces and Components.classes. Please also note that the code itself usually is wrapped inside a exports.main = function
() { ... } block. Note that the number of parameter that the observe method takes is important. It takes 3 parameters (as we've shown in the example code above). For the "http-on-modify-request" topic, the first parameter (named subject in the code above) will be the nsIHttpChannel. However, it is passed to us as an nsISupports. So we need to change the nsISupports into a nsIHttpChannel which is wha...
...e was good for learning, in an actual real-world application, you'd probably want to code it more like the following. ...
...rver = { observe: function(subject, topic, data) { if (topic == "http-on-modify-request") { var httpChannel = subject.QueryInterface(Ci.nsIHttpChannel); httpChannel.setRequestHeader("X-Hello", "World", false); } }, get observerService
() { return Cc["@mozilla.org/observer-service;1"] .getService(Ci.nsIObserverService); }, register: function
() { this.observerService.addObserver(this, "http-on-modify-request", false); }, unregister: function
() { this.observerService.removeObserver(this, "http-on-modify-request"); } }; This object has a convenience register
() and unregister
() methods, so in order to activate it you just need to call: httpRequestObserver.register
(); You should also remember to unregister the observer ...
...And 3 more matches
Reference Manual
nterface." It would be annoying if nsCOMPtr forced you to QueryInterface to the XPCOM-correct nsISupports within an object in places where you don't care to know the exact type. NULL-dereference Safeguards An nsCOMPtr will also assert at runtime if you try to dereference it when it is void, e.g., nsCOMPtr<nsIFoo> foo; // Note: default initialized to |0| foo->DoSomething
(); // NS_PRECONDITION: "You can't dereference a NULL nsCOMPtr with operator->
()" A similar precondition intervenes on behalf of operator*. Reference-Counting Safeguards All of the operations that extract the underlying raw pointer out of an nsCOMPtr use a C trick to implement another safety feature. The pointer returned cannot be AddRefed, Released, or deleted. ...
...Casting Never use old-style C/C++ casts on an nsCOMPtr. ...
... A similar precondition intervenes on behalf of operator*. Reference-Counting Safeguards All of the operations that extract the underlying raw pointer out of an nsCOMPtr use a C trick to implement another safety feature. The pointer returned cannot be AddRefed, Released, or deleted. nsCOMPtr<nsIFoo> foo = ...; foo->AddRef
(); // Error: |AddRef| is private delete foo.get
(); // Error: |operator delete| is private NS_RELEASE(foo); // Error: |Release| is private Of course, the most important safety feature provided by nsCOMPtr is that it AddRefs and Releases automatically at the appropriate times. Casting Never use old-style C/C++ casts on an nsCOMPtr. An old-style cast is guaranteed to compile, even if it can't do the right thing. Old-style casts ...
...And 3 more matches
Adding items to the Folder Pane
cessary data for the Folder Pane's display. This data is returned in the form of an array of folder-tree-items. Listening for Folder Pane rebuilds Every time the Folder Pane rebuilds, it fires a "mapRebuild" event, which is the ideal opportunity for extensions to step in and modify the display data. ...
...ideal opportunity for extensions to step in and modify the display data. The following code snippet listens for that event: let gNumbersExt = { load: function gne_load
() { window.removeEventListener("load", gNumbersExt.load, false); let tree = document.getElementById("folderTree"); tree.addEventListener("mapRebuild", gNumbersExt._insert, false); }, _insert: function gne__insert
() { // This function is called when a rebuild occurs } }; window.addEventListener("load", gNumbersExt.load, true); The structure of folder-tree-items The Folder Pane stores its current display data in a property called _rowMap. This property is an array of folder-tree-items. Each item in this array satisfies the following interface: id (attribute) a unique string for this object. Must ...
... command (function) this function will be called when the item is double-clicked For our example extension, two different types of folder-tree-items will be defined. ...
...And 3 more matches
Creating a Custom Column
w, props): optionally modify the props array getImageSrc(row, col): return a string (or null) getCellText(row, col): return a string representing the actual text to display in the column From nsIMsgCustomColumnHandler: getSortStringForRow(hdr): return the string value that the column will be sorted by getSortLongForRow(hdr): return the long value that the column will be sorted by isString
(): return true / false Warning! Do not get confused between GetCellText
() and GetSortString/LongForRow
()! Though they sound similar you may not want to return the same value from both. GetCellText
() is the text that is displayed to the user while GetSort*ForRow
() is what is used internally when sorting by your column A Simple Implementation Objects in Javascript are just "advanced" variables, s...
...nsIMsgCustomColumnHandler interface looks like: var columnHandler = { getCellText: function(row, col) { //get the message's header so that we can extract the reply to field var hdr = gDBView.getMsgHdrAt(row); return hdr.getStringProperty("replyTo"); }, getSortStringForRow: function(hdr) {return hdr.getStringProperty("replyTo");}, isString: function
() {return true;}, getCellProperties: function(row, col, props){}, getRowProperties: function(row, props){}, getImageSrc: function(row, col) {return null;}, getSortLongForRow: function(hdr) {return 0;} } Basically, all we are doing here is making sure that both the text that is displayed to the user (getCellText
()) and the string we sort according to (when the user deci...
...ndler object. Our implementation will need to call something similar to: gDBView.addColumnHandler("colReplyTo", columnHandler); Setting the Custom Column Handler We've added a special event that gets fired whenever a view is created. When that event fires, you should set up the custom column handler on the new view. ...
...And 3 more matches
Access Thunderbird Window Areas
To access particular parts of the Thunderbird window you can use these helper methods. An alternative to these methods is to directly access the element by it's ID as in the Detect When a Folder Opens example. ...
... To access particular parts of the Thunderbird window you can use these helper methods. An alternative to these methods is to directly access the element by it's ID as in the Detect When a Folder Opens example. ...
... To access particular parts of the Thunderbird window you can use these helper methods. An alternative to these methods is to directly access the element by it's ID as in the Detect When a Folder Opens example. ...
...And 3 more matches
Using the Multiple Accounts API
d are used to construct the preference names, such as "mail.account.account1.server". This the way accounts know which server and which identities they contain. Creating new accounts It is possible to create and modify accounts through the account manager API. The account manager is responsible for the creation of all accounts, incoming servers, and identities. You should not use CreateInstance
() to create any of the relevant objects because the account manager needs to keep track of all of these objects as they are created. To create accounts using the API, you should do the following: Create a fresh identity with createIdentity
(); Assign values to the various identity properties as necessary. Create a fresh incoming server with createIncomingServer
(). You will need to pass it th...
...ith createIdentity
(); Assign values to the various identity properties as necessary. Create a fresh incoming server with createIncomingServer
(). You will need to pass it the server type as a string, from the list above. Assign values to the various server properties as necessary. The most important properties here are the userName and the hostname. Create a fresh account with createAccount
(); Assign the server to the account with the incomingServer attribute. Assign the identity to the account with the AddIdentity
() method. Some sample code: (where accountManager is the account manager. ...
... server properties as necessary. The most important properties here are the userName and the hostname. Create a fresh account with createAccount
(); Assign the server to the account with the incomingServer attribute. Assign the identity to the account with the AddIdentity
() method. Some sample code: (where accountManager is the account manager. var identity = accountManager.createIdentity
(); identity.email="fred@myisp.com"; var server = accountManager.createIncomingServer("pop3"); server.userName = "fred"; server.hostname = "pop.myisp.com"; var account = accountManager.createAccount
(); account.incomingServer = server; account.AddIdentity(identity); That's it! Now you have a working account, identity, and server. It is possible, through some tricks with server and identi...
...And 3 more matches
Edit Shape Paths in CSS - Firefox Developer Tools
and other boxes used by CSS Shapes see our guide to Shapes from box values. Editing Basic Shapes The options given to you by the tool will differ depending on the type of basic shape that you are editing. Options can be accessed by activating the Shape Path Editor with a regular click on the icon, and you can use the context menu (Ctrl/Cmd + click) to access additional functionality. ...
... guide to Shapes from box values. Editing Basic Shapes The options given to you by the tool will differ depending on the type of basic shape that you are editing. Options can be accessed by activating the Shape Path Editor with a regular click on the icon, and you can use the context menu (Ctrl/Cmd + click) to access additional functionality. circle
() If the value of shape-outside is circle
(), you are creating a circle basic shape. Clicking on the shapes icon next to the value of circle
() will highlight the shape, and also give you the option to resize the circle or move its center. If you move or resize the circle past the margin box, the edges become clipped by it. In the Rules Panel you can see the values for circle
() change as you edit the shape. You can then copy these values ...
... to the value of circle
() will highlight the shape, and also give you the option to resize the circle or move its center. If you move or resize the circle past the margin box, the edges become clipped by it. In the Rules Panel you can see the values for circle
() change as you edit the shape. You can then copy these values back into your stylesheet to create the new, tweaked shape path. ellipse
() If the value of shape-outside is ellipse
() then you are using the ellipse basic shape. The ellipse
() value works in much the same way as circle
() in the Shape Path Editor. An ellipse is a squashed circle and therefore has the option to resize horizontally and vertically when you click on the shapes icon. ...
...And 3 more matches
Sorting algorithms comparison - Firefox Developer Tools
This article describes a simple example program that we use in two of the Performance guides: the guide to the Call Tree and the guide to the Flame Chart. This program compares the performance of three different sorting algorithms: bubble sort selection sort quicksort It consists of the following functions: sortAll
() Top-level function. Iteratively (200 iterations) generates a randomized array and calls sort
(). ...
...hat we use in two of the Performance guides: the guide to the Call Tree and the guide to the Flame Chart. This program compares the performance of three different sorting algorithms: bubble sort selection sort quicksort It consists of the following functions: sortAll
() Top-level function. Iteratively (200 iterations) generates a randomized array and calls sort
(). sort
() Calls each of bubbleSort
(), selectionSort
(), quickSort
() in turn and logs the result. ...
... program compares the performance of three different sorting algorithms: bubble sort selection sort quicksort It consists of the following functions: sortAll
() Top-level function. Iteratively (200 iterations) generates a randomized array and calls sort
(). sort
() Calls each of bubbleSort
(), selectionSort
(), quickSort
() in turn and logs the result. bubbleSort
() Implements a bubble sort, returning the sorted array. selectionSort
() Implements a selection sort, returning the sorted array. quickSort
() Implements quicksort, returning the sorted array. ...
...And 3 more matches
AbortController - Web APIs
The AbortController interface represents a controller object that allows you to abort one or more Web requests as and when desired. You can create a new AbortController object using the AbortController.AbortController
() constructor. Communicating with a DOM request is done using an AbortSignal object. Constructor AbortController
() Creates a new AbortController object instance. Properties AbortController.signal Read only Returns a AbortSignal object instance, which can be used to communicate with/abort a DOM request. Methods AbortController.abort
() Aborts a DOM request before it has completed. This is able to abort fetch requests, consumption of any response Body, and streams. Examples In the following snippet, we aim to download a video using the Fetch API. ...
...a AbortSignal object instance, which can be used to communicate with/abort a DOM request. Methods AbortController.abort
() Aborts a DOM request before it has completed. This is able to abort fetch requests, consumption of any response Body, and streams. Examples In the following snippet, we aim to download a video using the Fetch API. We first create a controller using the AbortController
() constructor, then grab a reference to its associated AbortSignal object using the AbortController.signal property. When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). ...
...ng the AbortController
() constructor, then grab a reference to its associated AbortSignal object using the AbortController.signal property. When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). This associates the signal and controller with the fetch request and allows us to abort it by calling AbortController.abort
(), as seen below in the second event listener. ...
...And 3 more matches
AbortSignal - Web APIs
a DOM request (such as a Fetch) and abort it if required via an AbortController object. Properties The AbortSignal interface also inherits properties from its parent interface, EventTarget. AbortSignal.aborted Read only A Boolean that indicates whether the request(s) the signal is communicating with is/are aborted (true) or not (false). Events Listen to this event using addEventListener
() or by assigning an event listener to the oneventname property of this interface. abort Invoked when the DOM request(s) the signal is communicating with is/are aborted. Also available via the onabort property. Methods The AbortSignal interface inherits methods from its parent interface, EventTarget. Examples In the following snippet, we aim to download a video using the Fetch API. We fi...
...name property of this interface. abort Invoked when the DOM request(s) the signal is communicating with is/are aborted. Also available via the onabort property. Methods The AbortSignal interface inherits methods from its parent interface, EventTarget. Examples In the following snippet, we aim to download a video using the Fetch API. ...
...ng the AbortController
() constructor, then grab a reference to its associated AbortSignal object using the AbortController.signal property. When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). This associates the signal and controller with the fetch request and allows us to abort it by calling AbortController.abort
(), as seen below in the second event listener. ...
...And 3 more matches
AnalyserNode.fftSize - Web APIs
ge 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). ...
...rNode, 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
(); ... ...
... (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)
(); var analyser = audioCtx.createAnalyser
(); ... ...
...And 3 more matches
AudioBuffer - Web APIs
Once put into an AudioBuffer, the audio can then be played by being passed into an AudioBufferSourceNode. Objects of these types are designed to hold small audio snippets, typically less than 45 s. For longer sounds, objects implementing the MediaElementAudioSourceNode are more suitable. ...
...ger sounds, objects implementing the MediaElementAudioSourceNode are more suitable. The buffer contains data in the following format: non-interleaved IEEE754 32-bit linear PCM with a nominal range between -1 and +1, that is, 32bits floating point buffer, with each samples between -1.0 and 1.0. If the AudioBuffer has multiple channels, they are stored in separate buffer. Constructor AudioBuffer
() Creates and returns a new AudioBuffer object instance. Properties AudioBuffer.sampleRate Read only Returns a float representing the sample rate, in samples per second, of the PCM data stored in the buffer. AudioBuffer.length Read only Returns an integer representing the length, in sample-frames, of the PCM data stored in the buffer. AudioBuffer.duration Read only Returns a double re...
...ting the length, in sample-frames, of the PCM data stored in the buffer. AudioBuffer.duration Read only Returns a double representing the duration, in seconds, of the PCM data stored in the buffer. AudioBuffer.numberOfChannels Read only Returns an integer representing the number of discrete audio channels described by the PCM data stored in the buffer. Methods AudioBuffer.getChannelData
() Returns a Float32Array containing the PCM data associated with the channel, defined by the channel parameter (with 0 representing the first channel). AudioBuffer.copyFromChannel
() Copies the samples from the specified channel of the AudioBuffer to the destination array. AudioBuffer.copyToChannel
() Copies the samples to the specified channel of the AudioBuffer, from the source array. Exampl...
...And 3 more matches
AudioBufferSourceNode.loop - Web APIs
et must be replayed when the end of the AudioBuffer is reached. The loop property's default value is false. Syntax var loopingEnabled = AudioBufferSourceNode.loop; AudioBufferSourceNode.loop = true | false; Value A Boolean which is true if looping is enabled; otherwise, the value is false. When looping is enabled, the sound begins playing at the time specified as the start point when start
() is called. When the time specified by the loopEnd property is reached, playback continues at the time specified by loopStart Example In this example, the AudioContext.decodeAudioData function is used to decode an audio track and put it into an AudioBufferSourceNode. Buttons are provided to play and stop the audio playback, and a slider control is used to change the playbackRate property value o...
...rt Example In this example, the AudioContext.decodeAudioData function is used to decode an audio track and put it into an AudioBufferSourceNode. Buttons are provided to play and stop the audio playback, and a slider control is used to change the playbackRate property value on the fly. When the audio is played, it loops. ...
...ext.decodeAudioData function is used to decode an audio track and put it into an AudioBufferSourceNode. Buttons are provided to play and stop the audio playback, and a slider control is used to change the playbackRate property value on the fly. When the audio is played, it loops. ...
...And 3 more matches
AudioBufferSourceNode.loopStart - Web APIs
's default value is 0. Syntax AudioBufferSourceNode.loopStart = startOffsetInSeconds; startOffsetInSeconds = AudioBufferSourceNode.loopStart; Value A floating-point number indicating the offset, in seconds, into the audio buffer at which each loop should begin during playback. This value is only used when the loop parameter is true. Example In this example, the AudioContext.decodeAudioData
() function is used to decode an audio track and put it into an AudioBufferSourceNode. Buttons are provided to play and stop the audio playback, and slider controls are used to change the playbackRate, loopStart, and loopEnd properties on the fly. When the audio is played to the end, it loops, but you can control how long the loops last by altering loopStart and loopEnd. For example, if you set the...
...art, and loopEnd properties on the fly. When the audio is played to the end, it loops, but you can control how long the loops last by altering loopStart and loopEnd. For example, if you set their values to 20 and 25, respectively, the audio will start to loop between 20 and 25 seconds in to the track. For a full working example, see this code running live, or view the source. ...
...en the audio is played to the end, it loops, but you can control how long the loops last by altering loopStart and loopEnd. For example, if you set their values to 20 and 25, respectively, the audio will start to loop between 20 and 25 seconds in to the track. For a full working example, see this code running live, or view the source. ...
...And 3 more matches
AudioContext - Web APIs
Properties Also inherits properties from its parent interface, BaseAudioContext. AudioContext.baseLatency Read only Returns the number of seconds of processing latency incurred by the AudioContext passing the audio from the AudioDestinationNode to the audio subsystem. AudioContext.outputLatency Read only Returns an estimation of the o...
...ntext.baseLatency Read only Returns the number of seconds of processing latency incurred by the AudioContext passing the audio from the AudioDestinationNode to the audio subsystem. AudioContext.outputLatency Read only Returns an estimation of the output latency of the current audio context. Methods Also inherits methods from its parent interface, BaseAudioContext. ...
...g the audio from the AudioDestinationNode to the audio subsystem. AudioContext.outputLatency Read only Returns an estimation of the output latency of the current audio context. Methods Also inherits methods from its parent interface, BaseAudioContext. AudioContext.close
() Closes the audio context, releasing any system audio resources that it uses. AudioContext.createMediaElementSource
() Creates a MediaElementAudioSourceNode associated with an HTMLMediaElement. This can be used to play and manipulate audio from <video> or <audio> elements. AudioContext.createMediaStreamSource
() Creates a MediaStreamAudioSourceNode associated with a MediaStream representing an audio stream which may come from the local computer microphone or other sources. AudioContext.createMediaStreamDestina...
...And 3 more matches
AudioListener.dopplerFactor - Web APIs
The deprecated dopplerFactor property of the AudioListener interface is a double value representing the amount of pitch shift to use when rendering a doppler effect. The dopplerFactor property's default value is 1, which is a sensible default for most situations. Syntax var audioCtx = new AudioContext
(); var myListener = audioCtx.listener; myListener.dopplerFactor = 1; Value A double indicating the doppler effect's pitch shift value. The value is 1 by default. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, and then update the position of one or both ...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 3 more matches
AudioListener.forwardX - Web APIs
The forwardX read-only property of the AudioListener interface is an AudioParam representing the x value of the direction vector defining the forward direction the listener is pointing in. Note: The parameter is a-rate when used with a PannerNode whose panningModel is set to equalpower, or k-rate otherwise. Syntax var audioCtx = new AudioContext
(); var myListener = audioCtx.listener; myListener.forwardX.value = 0; Value An AudioParam. Its default value is 0, and it can range between positive and negative infinity. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy ...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 3 more matches
AudioListener.forwardY - Web APIs
The forwardY read-only property of the AudioListener interface is an AudioParam representing the y value of the direction vector defining the forward direction the listener is pointing in. Note: The parameter is a-rate when used with a PannerNode whose panningModel is set to equalpower, or k-rate otherwise. Syntax var audioCtx = new AudioContext
(); var myListener = audioCtx.listener; myListener.forwardY.value = 0; Value An AudioParam. Its default value is 0, and it can range between positive and negative infinity. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy ...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 3 more matches
AudioListener.forwardZ - Web APIs
The forwardZ read-only property of the AudioListener interface is an AudioParam representing the z value of the direction vector defining the forward direction the listener is pointing in. Note: The parameter is a-rate when used with a PannerNode whose panningModel is set to equalpower, or k-rate otherwise. Syntax var audioCtx = new AudioContext
(); var myListener = audioCtx.listener; myListener.forwardZ.value = 0; Value An AudioParam. Its default value is -1, and it can range between positive and negative infinity. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 3 more matches
AudioListener.positionX - Web APIs
The positionX read-only property of the AudioListener interface is an AudioParam representing the x position of the listener in 3D cartesian space. Note: The parameter is a-rate when used with a PannerNode whose PannerNode is set to equalpower, or k-rate otherwise. Syntax var audioCtx = new AudioContext
(); var myListener = audioCtx.listener; myListener.positionX.value = 1; Value An AudioParam. Its default value is 0, and it can range between positive and negative infinity. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, and then update the position of...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 3 more matches
AudioListener.positionY - Web APIs
The positionY read-only property of the AudioListener interface is an AudioParam representing the y position of the listener in 3D cartesian space. Note: The parameter is a-rate when used with a PannerNode whose PannerNode is set to equalpower, or k-rate otherwise. Syntax var audioCtx = new AudioContext
(); var myListener = audioCtx.listener; myListener.positionY.value = 1; Value An AudioParam. Its default value is 0, and it can range between positive and negative infinity. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, and then update the position of...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 3 more matches
AudioListener.positionZ - Web APIs
The positionZ read-only property of the AudioListener interface is an AudioParam representing the z position of the listener in 3D cartesian space. Note: The parameter is a-rate when used with a PannerNode whose PannerNode is set to equalpower, or k-rate otherwise. Syntax var audioCtx = new AudioContext
(); var myListener = audioCtx.listener; myListener.positionZ.value = 1; Value An AudioParam. Its default value is 0, and it can range between positive and negative infinity. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, and then update the position of...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 3 more matches
AudioListener.speedOfSound - Web APIs
alue representing the speed of sound, in meters per second. The speedOfSound property's default value is 343.3 m/s and is used to calculate the doppler shift appropriate for the speed the panner is travelling at (as defined by PannerNode.setVelocity.) Note: Bear in mind that no propagation delay is automatically applied to a sound far from the listener. Syntax var audioCtx = new AudioContext
(); var myListener = audioCtx.listener; myListener.speedOfSound = 343.3; Value A double. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, and then update the positi...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 3 more matches
AudioListener.upX - Web APIs
The upX read-only property of the AudioListener interface is an AudioParam representing the x value of the direction vector defining the up direction the listener is pointing in. Note: The parameter is a-rate when used with a PannerNode whose PannerNode is set to equalpower, or k-rate otherwise. Syntax var audioCtx = new AudioContext
(); var myListener = audioCtx.listener; myListener.upX.value = 0; Value An AudioParam. Its default value is 0, and it can range between positive and negative infinity. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, and th...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 3 more matches
AudioListener.upY - Web APIs
The upY read-only property of the AudioListener interface is an AudioParam representing the y value of the direction vector defining the up direction the listener is pointing in. Note: The parameter is a-rate when used with a PannerNode whose PannerNode is set to equalpower, or k-rate otherwise. Syntax var audioCtx = new AudioContext
(); var myListener = audioCtx.listener; myListener.upY.value = 0; Value An AudioParam. Its default value is 1, and it can range between positive and negative infinity. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, and th...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 3 more matches
AudioListener.upZ - Web APIs
The upZ read-only property of the AudioListener interface is an AudioParam representing the z value of the direction vector defining the up direction the listener is pointing in. Note: The parameter is a-rate when used with a PannerNode whose PannerNode is set to equalpower, or k-rate otherwise. Syntax var audioCtx = new AudioContext
(); var myListener = audioCtx.listener; myListener.upZ.value = 0; Value An AudioParam. Its default value is 0, and it can range between positive and negative infinity. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, and th...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 3 more matches
AudioProcessingEvent - Web APIs
le to cancel the event? playbackTime Read only 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 sc...
...ut 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 following example shows basic usage of a ScriptProcessorNode to take a track loaded via AudioContext.decodeAudioData
(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the AudioDestinationNode. For each channel and each sample frame, the scriptNode.onaudioprocess function takes the associated audioProcessingEvent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before s...
...se, before setting that result to be the output sample in each case. ...
...And 3 more matches
AudioWorkletProcessor - Web APIs
dioWorkletProcessor 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. The constructor of the deriving class is getting called with an options object, so you can perform a custom initialization procedures -- see constructor page for details. AudioWorkletProcessor
() Creates a new instance of an AudioWorkletProcessor object. Properties port Read only Returns a MessagePort used for bidirectional communication between the processor and the AudioWorkletNode which it belongs to. The other end is available under the port property of the node. Methods The AudioWorkletProcessor interface does not define any methods of its own. However, you must provide a ...
...es a new instance of an AudioWorkletProcessor object. Properties port Read only Returns a MessagePort used for bidirectional communication between the processor and the AudioWorkletNode which it belongs to. The other end is available under the port property of the node. Methods The AudioWorkletProcessor interface does not define any methods of its own. However, you must provide a process
() method, which is called in order to process the audio stream. Events The AudioWorkletProcessor interface doesn't respond to any events. Usage notes Deriving classes To define custom audio processing code you have to derive a class from the AudioWorkletProcessor interface. Although not defined on the interface, the deriving class must have the process method. This method gets called for each ...
...perty as a static getter on the processor. The array of AudioParamDescriptor-based objects returned is used internally to create the AudioParams during the instantiation of the AudioWorkletNode. The resulting AudioParams reside in the parameters property of the node and can be automated using standard methods such as linearRampToValueAtTime. ...
...And 3 more matches
Body.body - Web APIs
The body read-only property of the Body mixin is a simple getter used to expose a ReadableStream of the body contents. Syntax var stream = response.body; Value A ReadableStream. ...
...create a reader using ReadableStream.getReader
(), then enqueue that stream's chunks into a second, custom readable stream -- effectively creating an identical copy of the image. ...
... chunks into a second, custom readable stream -- effectively creating an identical copy of the image. ...
...And 3 more matches
CanvasRenderingContext2D.lineCap - Web APIs
The CanvasRenderingContext2D.lineCap property of the Canvas 2D API determines the shape used to draw the end points of lines. Note: Lines can be drawn with the stroke
(), strokeRect
(), and strokeText
() methods. Syntax ctx.lineCap = "butt" || "round" || "square"; Options "butt" The ends of lines are squared off at the endpoints. Default value. "round" The ends of lines are rounded. "square" The ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness. Examples Changing the shape of line caps This example rounds the end caps of a straight line. ...
...s of lines are rounded. "square" The ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness. Examples Changing the shape of line caps This example rounds the end caps of a straight line. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath
(); ctx.moveTo(20, 20); ctx.lineWidth = 15; ctx.lineCap = 'round'; ctx.lineTo(100, 100); ctx.stroke
(); Result Comparison of line caps In this example three lines are drawn, each with a different value for the lineCap property. Two guides to see the exact differences between the three are added. Each of these lines starts and ends exactly on these guides. The line on the left uses the default ...
...alf the width of the line. The line on the right uses the "square" option. This adds a box with an equal width and half the height of the line thickness. ...
...And 3 more matches
Drawing text - Web APIs
nvas rendering context provides two methods to render text: fillText(text, x, y [, maxWidth]) Fills a given text at the given (x,y) position. Optionally with a maximum width to draw. strokeText(text, x, y [, maxWidth]) Strokes a given text at the given (x,y) position. Optionally with a maximum width to draw. A fillText example The text is filled using the current fillStyle. ...
...text, x, y [, maxWidth]) Strokes a given text at the given (x,y) position. Optionally with a maximum width to draw. A fillText example The text is filled using the current fillStyle. function draw
() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.font = '48px serif'; ctx.fillText('Hello world', 10, 50); } <canvas id="canvas" width="300" height="100"></canvas> draw
(); A strokeText example The text is filled using the current strokeStyle. ...
...maximum width to draw. A fillText example The text is filled using the current fillStyle. function draw
() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.font = '48px serif'; ctx.fillText('Hello world', 10, 50); } <canvas id="canvas" width="300" height="100"></canvas> draw
(); A strokeText example The text is filled using the current strokeStyle. function draw
() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.font = '48px serif'; ctx.strokeText('Hello world', 10, 50); } <canvas id="canvas" width="300" height="100"></canvas> draw
(); Styling text In the examples above we are already making use of the font property to make the text a bit larger than the default size. There are some more properties which let you adjust the w...
...And 3 more matches
ChannelSplitterNode - Web APIs
rates the different channels of an audio source into a set of mono outputs. This is useful for accessing each channel separately, e.g. for performing channel mixing where gain must be separately controlled on each channel. If your ChannelSplitterNode always has one single input, the amount of outputs is defined by a parameter on its constructor and the call to AudioContext.createChannelSplitter
(). In the case that no value is given, it will default to 6. If there are fewer channels in the input than there are outputs, supernumerary outputs are silent. Number of inputs 1 Number of outputs variable; default to 6. Channel count mode "explicit" Older implementations, as per earlier versions of the spec use "max". Channel count Fixed to the numb...
...r of outputs variable; default to 6. Channel count mode "explicit" Older implementations, as per earlier versions of the spec use "max". Channel count Fixed to the number of outputs. Older implementations, as per earlier versions of the spec use 2 (not used in the default count mode). Channel interpretation "discrete" Constructor ChannelSplitterNode
() Creates a new ChannelSplitterNode object instance. Properties No specific property; inherits properties from its parent, AudioNode. Methods No specific method; inherits methods from its parent, AudioNode. Example The following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. To use them, you need to use...
...ample The following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. To use them, you need to use the second and third parameters of the AudioNode.connect(AudioNode) method, which allow you to specify the index of the channel to connect from and the index of the channel to connect to. ...
...And 3 more matches
Constraint validation API - Web APIs
validationMessage A read-only property that returns an empty string if the element is not a candidate for constraint validation, or if the element's value is valid. If the element's value is not valid, it returns a localized validation message. ...
...age is set using setCustomValidity
(), this will be shown. willValidate A read-only boolean property that returns true if the element is a candidate for constraint validation; and false otherwise. Elements with the HTMLObjectElement interface are never candidates for constraint validation. Others may be barred from constraint validation depending on specific conditions. Methods checkValidity
() Checks the element's value against its constraints. If the value is invalid, it fires an invalid event at the element and returns false; otherwise it returns true. ...
...lse otherwise. Elements with the HTMLObjectElement interface are never candidates for constraint validation. Others may be barred from constraint validation depending on specific conditions. Methods checkValidity
() Checks the element's value against its constraints. If the value is invalid, it fires an invalid event at the element and returns false; otherwise it returns true. reportValidity
() HTMLFormElement method Checks the element's value against its constraints and also reports the validity status; if the value is invalid, it fires an invalid event at the element, returns false, and then reports the validity status to the user in whatever way the user agent has available. Otherwise, it returns true. setCustomValidity(message) Sets a custom error message string to be shown to th...
...And 3 more matches
ConvolverNode - Web APIs
ConvolverNode always has exactly one input and one output. Note: For more information on the theory behind Linear Convolution, see the Convolution article on Wikipedia. Number of inputs 1 Number of outputs 1 Channel count mode "clamped-max" Channel count 1, 2, or 4 Channel interpretation "speakers" Constructor ConvolverNode
() Creates a new ConvolverNode object instance. Properties Inherits properties from its parent, AudioNode. ConvolverNode.buffer A mono, stereo, or 4-channel AudioBuffer containing the (possibly multichannel) impulse response used by the ConvolverNode to create the reverb effect. ConvolverNode.normalize A boolean that controls whether the impulse response from the buffer will be scaled by a...
...zation when the buffer attribute is set, or not. Methods No specific method; inherits methods from its parent, AudioNode. ConvolverNode Example The following example shows basic usage of an AudioContext to create a convolver node. Note: You will need to find an impulse response to complete the example below. See this Codepen for an applied example. ...
... is set, or not. Methods No specific method; inherits methods from its parent, AudioNode. ConvolverNode Example The following example shows basic usage of an AudioContext to create a convolver node. Note: You will need to find an impulse response to complete the example below. See this Codepen for an applied example. ...
...And 3 more matches
DOMParser - Web APIs
ng a DOM tree into XML or HTML source--using the XMLSerializer interface. In the case of an HTML document, you can also replace portions of the DOM with new DOM trees built from HTML by setting the value of the Element.innerHTML and outerHTML properties. These properties can also be read to fetch HTML fragments corresponding to the corresponding DOM subtree. Syntax let domparser = new DOMParser
() Methods DOMParser.parseFromString
() Syntax let doc = domparser.parseFromString(string, mimeType) Return Either Document or XMLDocument depending on the mimeType argument. Parameters This method has 2 parameters (both required): string The DOMString to be parsed. It must contain either HTML, xml, xhtml+xml, or svg document. mimeType A DOMString. This string determines a class of th...
...following: mimeType doc.constructor text/html Document text/xml XMLDocument application/xml XMLDocument application/xhtml+xml XMLDocument image/svg+xml XMLDocument Examples Parsing XML Once you have created a parser object, you can parse XML from a string using the parseFromString
() method: let parser = new DOMParser
() let doc = parser.parseFromString(stringContainingXMLSource, "application/xml") Error handling Note that if the parsing process fails, the DOMParser does not throw an exception, but instead returns an error document: <parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml"> (error description) <sourcetext>(a snippet of the source XML)<...
....0 / SeaMonkey 2.7) or an HTML document (Firefox 12.0 / Thunderbird 12.0 / SeaMonkey 2.9). There are three different results possible, selected by the MIME type given. ...
...And 3 more matches
DelayNode.delayTime - Web APIs
Value An AudioParam. ...
... Value An AudioParam. ...
...op -- see create-delay (you can also view the source code). If you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time. ...
...And 3 more matches
DirectoryReaderSync - Web APIs
as on a standard track and it proves not a good idea. Do not use it anymore. About this document This document was last updated on March 2, 2012 and follows the W3C Specifications (Working Draft) drafted on April 19, 2011. This specification is pretty much abandoned, having failed to reach any substantial traction. Basic concepts Before you call the only method in this interface, readEntries
(), create the DirectoryEntrySync object. But DirectoryEntrySync (as well as FileEntrySync) is not a data type that you can pass between a calling app and Web Worker thread. It's not a big deal, because you don't really need to have the main app and the worker thread see the same JavaScript object; you just need them to access the same files. You can do that by passing a list of filesystem: URLs--w...
...ing app and Web Worker thread. It's not a big deal, because you don't really need to have the main app and the worker thread see the same JavaScript object; you just need them to access the same files. You can do that by passing a list of filesystem: URLs--which are just strings--instead of a list of entries. You can also use the filesystem: URL to look up the entry with resolveLocalFileSystemURL
(). That gets you back to a DirectoryEntrySync (as well as FileEntrySync) object. Example In the following code snippet from HTML5Rocks, we create Web Workers and pass data from it to the main app. // Taking care of the browser-specific prefixes. window.resolveLocalFileSystemURL = window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL; /...
...}); The following is Worker.js code that gets the contents of the directory. // Taking care of the browser-specific prefixes. self.requestFileSystemSync = self.webkitRequestFileSystemSync || self.requestFileSystemSync; // Global for holding the list of entry file system URLs. ...
...And 3 more matches
Locating DOM elements using selectors - Web APIs
e Element nodes from the DOM by matching against a set of selectors. This is much faster than past techniques, wherein it was necessary to, for example, use a loop in JavaScript code to locate the specific items you needed to find. ...
...to, for example, use a loop in JavaScript code to locate the specific items you needed to find. The NodeSelector interface This specification adds two new methods to any objects implementing the Document, DocumentFragment, or Element interfaces: querySelector
() Returns the first matching Element node within the node's subtree. If no matching node is found, null is returned. querySelectorAll
() Returns a NodeList containing all matching Element nodes within the node's subtree, or an empty NodeList if no matches are found. Note: The NodeList returned by querySelectorAll
() is not live, which means that changes in the DOM are not reflected in the collection. This is different from other DOM querying methods that return live node lists. You may find examples and details by reading the d...
... Selectors The selector methods accept one or more comma-separated selectors to determine what element or elements should be returned. ...
...And 3 more matches
FetchEvent - Web APIs
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. ...
...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. ...
...bled. FetchEvent.replacesClientId Read only The id of the client that is being replaced during a page navigation. FetchEvent.resultingClientId Read only The id of the client that replaces the previous client during a page navigation. FetchEvent.request Read only The Request the browser intends to make. Methods Inherits methods from its parent, ExtendableEvent. FetchEvent.respondWith
() Prevent the browser's default fetch handling, and provide (a promise for) a response yourself. ExtendableEvent.waitUntil
() Extends the lifetime of the event. Used to notify the browser of tasks that extend beyond the returning of a response, such as streaming and caching. Examples This fetch event uses the browser default for non-GET requests. For GET requests it tries to return a match...
...And 3 more matches
Fetch API - Web APIs
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 optionall...
...urns a Promise that resolves to the Response to that request, whether it is successful or not. You can also optionally pass in an init options object as the second argument (see Request). Once a Response is retrieved, there are a number of methods available to define what the body content is and how it should be handled (see Body). ...
...that resolves to the Response to that request, whether it is successful or not. You can also optionally pass in an init options object as the second argument (see Request). Once a Response is retrieved, there are a number of methods available to define what the body content is and how it should be handled (see Body). ...
...And 3 more matches
FileSystemDirectoryEntry - Web APIs
If you want to create subdirectories, create each child directory in sequence. ...
...try.fullPath === '/Documents' }, onError); } // Opening a file system with temporary storage window.requestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, onFs, onError); Properties This interface has no properties of its own, but inherits properties from its parent interface, FileSystemEntry. Methods This interface inherits methods from its parent interface, FileSystemEntry. ...
...ileSystem(TEMPORARY, 1024*1024 /*1MB*/, onFs, onError); Properties This interface has no properties of its own, but inherits properties from its parent interface, FileSystemEntry. Methods This interface inherits methods from its parent interface, FileSystemEntry. createReader
() Creates a FileSystemDirectoryReader object which can be used to read the entries in this directory. ...
...And 3 more matches
FileSystemEntry - Web APIs
interface serves as a base class for the FileSystemFileEntry and FileSystemDirectoryEntry interfaces, which provide features specific to file system entries representing files and directories, respectively. The FileSystemEntry interface includes methods that you would expect for manipulating files and directories, but it also includes a convenient method for obtaining the URL of the entry: toURL
(). It also introduces a new URL scheme: filesystem:. You can use the filesystem: scheme on Google Chrome to see all the files and folders that are stored in the origin of your app. Just use filesystem: scheme for the root directory of the origin of the app. For example, if your app is in http://www.html5rocks.com, open filesystem:http://www.html5rocks.com/temporary/ in a tab. Chrome shows a read-o...
...ee all the files and folders that are stored in the origin of your app. Just use filesystem: scheme for the root directory of the origin of the app. For example, if your app is in http://www.html5rocks.com, open filesystem:http://www.html5rocks.com/temporary/ in a tab. Chrome shows a read-only list of all the files and folders stored the origin of your app. Example To see an example of how toURL
() works, see the method description. The snippet below shows you how you can remove a file by name. // Taking care of the browser-specific prefixes. window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; ... // Opening a file system with temporary storage window.requestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, function(fs) { fs.root.getFile('log.txt', {}, functi...
...t below shows you how you can remove a file by name. // Taking care of the browser-specific prefixes. window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; ... // Opening a file system with temporary storage window.requestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, function(fs) { fs.root.getFile('log.txt', {}, function(fileEntry) { fileEntry.remove(function
() { console.log('File removed.'); }, onError); }, onError); }, onError); Properties This interface provides the following properties. filesystem Read only A FileSystem object representing the file system in which the entry is located. fullPath Read only A USVString object which provides the full, absolute path from the file system's root to the entry; it can also be thought ...
...And 3 more matches
FileSystemFileEntry - Web APIs
The FileSystemFileEntry interface of the File System API represents a file in a file system. It offers properties describing the file's attributes, as well as the file
() method, which creates a File object that can be used to read the file. Properties Inherits the properties of its parent interface, FileSystemEntry, but has no properties unique to this interface. Methods file
() Creates a new File object which can be used to read the file. Obsolete methods createWriter
() Creates a new FileWriter object which allows writing to the file represented by the file system entry. Basic concepts To write content to file, create a FileWriter object by calling createWriter
(). To read a file, obtain a File object representing its contents by calling file
(). Example The foll...
... function onInitFs(fs) { fs.root.getFile('log.txt', {create: true}, function(fileEntry) { // Create a FileWriter object for our FileSystemFileEntry (log.txt). ...
...function onInitFs(fs) { fs.root.getFile('log.txt', {create: true}, function(fileEntry) { // Create a FileWriter object for our FileSystemFileEntry (log.txt). ...
...And 3 more matches
Using the Frame Timing API - Web APIs
t was specified when the observer was created. Creating an observer To observe "frame" performance entry types, the application first creates a PerformanceObserver object with a specific frame observer callback. In the following example, two observers for the "frame" performance entry type are created and the first observer constructor uses inline function syntax. ...
... the performance observer var observe_frame = new PerformanceObserver(function(list) { // Log the frame entries var perfEntries = list.getEntriesByType("frame"); for (var i=0; i < perfEntries.length; i++) { console.log("OBS #1: [" + i + "] = " + perfEntries[i].name); } }); // Only observe 'frame' events observe_frame.observe({entryTypes: ['frame']}); } function init
() { create_frame_observer
(); var obs = new PerformanceObserver(frame_observer_2); obs.observe({entryTypes: ['frame']}); } function frame_observer_2(list) { // Log the frame entries var perfEntries = list.getEntriesByType("frame"); for (var i=0; i < perfEntries.length; i++) { console.log("OBS #2: [" + i + "] = " + perfEntries[i].name); } } <body onload="init(event)"> When the ...
...Type("frame"); for (var i=0; i < perfEntries.length; i++) { console.log("OBS #2: [" + i + "] = " + perfEntries[i].name); } } <body onload="init(event)"> When the browser adds a new "frame" entry to the performance timeline, both of the observer callbacks will be invoked. Registering for notifications After an observer is created, the next step is to use the PerformanceObserver.observe
() method to specify the set of performance events to observe. In the following example, the observer only registers for "frame" performance entry notifications. var observe_frame = new PerformanceObserver(function(list) { // Process the frame ... }); // Only observe 'frame' events observe_frame.observe({entryTypes: ['frame']}); In the following example, the observer registers to be notifi...
...And 3 more matches
Fullscreen API - Web APIs
no interfaces of its own. Instead, it augments several other interfaces to add the methods, properties, and event handlers needed to provide full-screen functionality. These are listed in the following sections. Methods The Fullscreen API adds methods to the Document and Element interfaces to allow turning off and on full-screen mode. ...
... API adds methods to the Document and Element interfaces to allow turning off and on full-screen mode. Methods on the Document interface Document.exitFullscreen
() Requests that the user agent switch from full-screen mode back to windowed mode. Returns a Promise which is resolved once full-screen mode has been completely shut off. Methods on the Element interface Element.requestFullscreen
() Asks the user agent to place the specified element (and, by extension, its descendants) into full-screen mode, removing all of the browser's UI elements as well as all other applications from the screen. Returns a Promise which is resolved once full-screen mode has been activated. Properties The Document interface provides properties that can be used to determine if full-screen mode is suppor...
...ess of changing between full-screen and windowed modes. fullscreenchange Sent to a Document or Element when it transitions into or out of full-screen mode. fullscreenerror Sent to a Document or Element if an error occurs while attempting to switch it into or out of full-screen mode. Dictionaries FullscreenOptions Provides optional settings you can specify when calling requestFullscreen
(). Controlling access The availability of full-screen mode can be controlled using Feature Policy. The full-screen mode feature is identified by the string "fullscreen", with a default allow-list value of "self", meaning that full-screen mode is permitted in top-level document contexts, as well as to nested browsing contexts loaded from the same origin as the top-most document. See Using Featur...
...And 3 more matches
GlobalEventHandlers.onload - Web APIs
The onload property of the GlobalEventHandlers mixin is an EventHandler that processes load events on a Window, XMLHttpRequest, <img> element, etc. The load event fires when a given resource has loaded. Syntax target.onload = functionRef; Value functionRef is the handler function to be called when the window's load event fires. ...
... The onload property of the GlobalEventHandlers mixin is an EventHandler that processes load events on a Window, XMLHttpRequest, <img> element, etc. The load event fires when a given resource has loaded. Syntax target.onload = functionRef; Value functionRef is the handler function to be called when the window's load event fires. ...
... onload property of the GlobalEventHandlers mixin is an EventHandler that processes load events on a Window, XMLHttpRequest, <img> element, etc. The load event fires when a given resource has loaded. Syntax target.onload = functionRef; Value functionRef is the handler function to be called when the window's load event fires. ...
...And 3 more matches
HTMLDialogElement.open - Web APIs
ing the state of the open HTML attribute. true means it is set, and therefore the dialog is shown. false means it not set, and therefore the dialog is not shown. The property is now read only -- it is possible to set the value to programmatically show or hide the dialog. Examples The following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showModal
() method. From there you can click the Cancel button to close the dialog (via the HTMLDialogElement.close
() method), or submit the form via the submit button. <!-- Simple pop-up dialog box, containing a form --> <dialog id="favDialog"> <form method="dialog"> <section> <p><label for="favAnimal">Favorite animal:</label> <select id="favAnimal" name="favAnimal"> ...
...ption>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function
() { var updateButton = document.getElementById('updateDetails'); var cancelButton = document.getElementById('cancel'); var dialog = document.getElementById('favDialog'); dialog.returnValue = 'favAnimal'; function openCheck(dialog) { if(dialog.open) { console.log('Dialog open'); } else { console.log('Dialog closed'); } ...
... Specifications Spec...
...And 3 more matches
HTMLElement: animationcancel event - Web APIs
ords, any time it stops running without sending an animationend event. This might happen when the animation-name is changed such that the animation is removed, or when the animating node is hidden using CSS. Therefore, either directly or because any of its containing nodes are hidden. An event handler for this event can be added by setting the onanimationcancel property, or using addEventListener
(). Bubbles Yes Cancelable No Interface AnimationEvent Event handler property onanimationcancel Examples This code gets an element that's currently being animated and adds a listener to the animationcancel event. It then sets the element's display property to none, which will trigger the animationcancel event. const animated = document.queryS...
...ace AnimationEvent Event handler property onanimationcancel Examples This code gets an element that's currently being animated and adds a listener to the animationcancel event. It then sets the element's display property to none, which will trigger the animationcancel event. ...
...istener to the animationcancel event. It then sets the element's display property to none, which will trigger the animationcancel event. ...
...And 3 more matches
IDBDatabase - Web APIs
connected database. IDBDatabase.version Read only A 64-bit integer that contains the version of the connected database. When a database is first created, this attribute is an empty string. IDBDatabase.objectStoreNames Read only A DOMStringList that contains a list of the names of the object stores currently in the connected database. ...
...abase. When a database is first created, this attribute is an empty string. IDBDatabase.objectStoreNames Read only A DOMStringList that contains a list of the names of the object stores currently in the connected database. Methods Inherits from: EventTarget IDBDatabase.close
() Returns immediately and closes the connection to a database in a separate thread. IDBDatabase.createMutableFile
() Creates a file handle, allowing files to be stored inside an IndexedDB database. ...
... A DOMStringList that contains a list of the names of the object stores currently in the connected database. Methods Inherits from: EventTarget IDBDatabase.close
() Returns immediately and closes the connection to a database in a separate thread. IDBDatabase.createMutableFile
() Creates a file handle, allowing files to be stored inside an IndexedDB database. IDBDatabase.createObjectStore
() Creates and returns a new object store or index. IDBDatabase.deleteObjectStore
() Destroys the object store with the given name in the connected database, along with any indexes that reference it. IDBDatabase.transaction
() Immediately returns a transaction object (IDBTransaction) containing the IDBTransaction.objectStore method, which you can use to access your object store. Runs in a separat...
...And 3 more matches
IDBRequest.onerror - Web APIs
est fails. ...
...What will be inside of t...
...What will be inside of this event? }; Specifications Specification Status Comment In...
...And 3 more matches
MediaPositionState.position - Web APIs
This information is then, in turn, used by the user agent to provide a user interface which displays media playback information to the viewer. For example, a browser might use this information along with the position property and the navigator.mediaSession.playbackState, as well as the session's metadata to provide an integrated common user interface showing the currently playing media as well as standard pause, play, forward, reverse, and other controls. ...
...d other controls. Syntax let positionState = { position: timeInSeconds }; let duration = positionState.duration; Value A floating-point value indicating the current playback position within the media currently being performed, in seconds. This value should always be zero or more. ...
...Value A floating-point value indicating the current playback position within the media currently being performed, in seconds. This value should always be zero or more. Example In this example, a player for a non-standard media file format, written in JavaScript, uses setInterval
() to establish a callback which fires once per second to refresh the position information by calling setPositionState
(). ...
...And 3 more matches
MediaSource - Web APIs
Properties MediaSource.sourceBuffers Read only Returns a SourceBufferList object containing the list of SourceBuffer objects associated with this MediaSource. MediaSource.activeSourceBuffers Read only Returns a SourceBufferList object containing a subset of the SourceBuffer objects contained within Media...
...st of objects providing the selected video track, enabled audio tracks, and shown/hidden text tracks. MediaSource.readyState Read only Returns an enum representing the state of the current MediaSource, whether it is not currently attached to a media element (closed), attached and ready to receive SourceBuffer objects (open), or attached but the stream has been ended via MediaSource.endOfStream
() (ended.) MediaSource.duration Gets and sets the duration of the current media being presented. Event handlers MediaSource.onsourceclose The event handler for the sourceclose event. MediaSource.onsourceended The event handler for the sourceended event. MediaSource.onsourceopen The event handler for the sourceopen event. Methods Inherits methods from its parent interface, EventTarget...
... Gets and sets the duration of the current media being presented. Event handlers MediaSource.onsourceclose The event handler for the sourceclose event. MediaSource.onsourceended The event handler for the sourceended event. MediaSource.onsourceopen The event handler for the sourceopen event. Methods Inherits methods from its parent interface, EventTarget. MediaSource.addSourceBuffer
() Creates a new SourceBuffer of the given MIME type and adds it to the MediaSource.sourceBuffers list. MediaSource.clearLiveSeekableRange
() Clears a seekable range previously set with a call to setLiveSeekableRange
(). MediaSource.endOfStream
() Signals the end of the stream. MediaSource.removeSourceBuffer
() Removes the given SourceBuffer from the MediaSource.sourceBuffers list. MediaSource.s...
...And 3 more matches
MediaStream - Web APIs
The MediaStream interface represents a stream of media content. A stream consists of several tracks such as video or audio tracks. Each track is specified as an instance of MediaStreamTrack.You can obtain a MediaStream object either by using the constructor or by calling MediaDevices.getUserMedia
(). Some user agents subclass this interface to provide more precise information or functionality, like in CanvasCaptureMediaStream. Constructor MediaStream
() Creates and returns a new MediaStream object. You can create an empty stream, a stream which is based upon an existing stream, or a stream that contains a specified list of tracks (specified as an array of MediaStreamTrack objects). Properties This interface inherits properties from its parent, EventTarget. MediaStream.active Read ...
...eam.onaddtrack An EventHandler containing the action to perform when an addtrack event is fired when a new MediaStreamTrack object is added. MediaStream.onremovetrack An EventHandler containing the action to perform when a removetrack event is fired when a MediaStreamTrack object is removed from it. Methods This interface inherits methods from its parent, EventTarget. ...
...etrack An EventHandler containing the action to perform when a removetrack event is fired when a MediaStreamTrack object is removed from it. Methods This interface inherits methods from its parent, EventTarget. MediaStream.addTrack
() Stores a copy of the MediaStreamTrack given as argument. If the track has already been added to the MediaStream object, nothing happens. MediaStream.clone
() Returns a clone of the MediaStream object. The clone will, however, have a unique value for id. ...
...And 3 more matches
Using the Media Capabilities API - Web APIs
edia given a specified set of encoding parameters. These parameters may include the codecs, resolutions, bit rates, frame rates, and other such details. With the Media Capabilities API, you can determine not just if the browser can support a given format, but whether or not it can do so efficiently and smoothly. In short, this API replaces--and improves upon--the MediaSource method isTypeSupported
() or the HTMLMediaElement method canPlayType
(). More and more finely-detailed information about the display's properties, so that informed decisions can be made when choosing the best format to play on the user's device. For example, you can use the API to ensure that you don't try to play High Dynamic Range (HDR) content on a Standard Dynamic Range (SDR) screen. Support for getting real-time fee...
... API is available. You can, therefore, test for the presence of the API like so: if ("mediaCapabilities" in navigator) { // mediaCapabilities is available } else { // mediaCapabilities IS NOT available } Taking video as an example, to obtain information about video decoding abilities, you create a video decoding configuration which you pass as a parameter to MediaCapabilities.decodingInfo
() method. This returns a promise that fulfills with information about the media capabilities as to whether the video can be decoded, and whether decoding will be smooth and power efficient. You can also test audio decoding as well as video and audio encoding. Creating a video decoding configuration The MediaCapabilities.decodingInfo
() method takes as a parameter a media decoding configuration. Th...
...e type of media being tested -- either record (for recording media, i.e. a MediaRecorder object) or transmission (for media transmitted over electronic means like RTCPeerConnection) -- plus either an audio or video configuration as described above. Querying the browser about decoding abilities Now that we've created a video decoding configuration we can pass it as a paramater of the decodingInfo
() method to determine if a video matching this configuration would be decodable and if the playback would be smooth and power efficient. var promise = navigator.mediaCapabilities.decodingInfo(videoConfiguration); The decodingInfo
() and encodingInfo
() methods both return promises. Once the promises state is fulfilled, you can access the MediaCapabilitiesInfo interface's supported, smooth, and powe...
...And 3 more matches
NavigationPreloadManager - Web APIs
The NavigationPreloadManager interface of the the Service Worker API provides methods for managing the preloading of resources with a service worker. Methods NavigationPreloadManager.enable
() Enables navigation preloading and returns a Promise that resolves. NavigationPreloadManager.disable
() Disables navigation preloading and returns a Promise that resolves. NavigationPreloadManager.setHeaderValue
() Sets the value of the Service-Worker-Navigation-Preload header and returns an empty Promise. NavigationPreloadManager.getState
() Returns a Promise that resolves to an object with properties indicating whether preload is enabled and the contents of the Service-Worker-Navigation-Preload. Examples Feature Detecting and Enabling Navigation Preloading addEventListener('activate', eve...
...e-Worker-Navigation-Preload header and returns an empty Promise. NavigationPreloadManager.getState
() Returns a Promise that resolves to an object with properties indicating whether preload is enabled and the contents of the Service-Worker-Navigation-Preload. Examples Feature Detecting and Enabling Navigation Preloading addEventListener('activate', event => { event.waitUntil(async function
() { if (self.registration.navigationPreload) { // Enable navigation preloads! ...
...ject with properties indicating whether preload is enabled and the contents of the Service-Worker-Navigation-Preload. ...
...And 3 more matches
Using Navigation Timing - Web APIs
ide timing information as perceived by the user rather than data that has no correlation to what the user experiences. Collecting timing information Using the API is as simple as obtaining the Performance object using window.performance and looking up what you need within the object returned. ...
... perceived by the user rather than data that has no correlation to what the user experiences. Collecting timing information Using the API is as simple as obtaining the Performance object using window.performance and looking up what you need within the object returned. ...
... by the user rather than data that has no correlation to what the user experiences. Collecting timing information Using the API is as simple as obtaining the Performance object using window.performance and looking up what you need within the object returned. ...
...And 3 more matches
Notification - Web APIs
Note: This feature is available in Web Workers. The Notification interface of the Notifications API is used to configure and display desktop notifications to the user. These notifications' appearance and specific functionality vary across platforms but generally they provide a way to asynchronously provide information to the user. Constructor Notification
() Creates a new instance of the Notification object. Properties Static properties These properties are available only on the Notification object itself. Notification.permission Read only A string representing the current permission to display notifications. Possible values are: denied -- The user refuses to have notifications displayed. granted -- The user accepts having notifications displayed. default -- Th...
... triggered when the user closes the notification. Notification.onerror A handler for the error event. It is triggered each time the notification encounters an error. Notification.onshow A handler for the show event. It is triggered when the notification is displayed. Methods Static methods These methods are available only on the Notification object itself. ...
...ds Static methods These methods are available only on the Notification object itself. Notification.requestPermission
() Requests permission from the user to display notifications. Instance methods These properties are available only on an instance of the Notification object or through its prototype. The Notification object also inherits from the EventTarget interface. Notification.close
() Programmatically closes a notification instance. ...
...And 3 more matches
PannerNode.distanceModel - Web APIs
n induced by the distance according to: refDistance / (refDistance + rolloffFactor * (Math.max(distance, refDistance) - refDistance)) exponential: An exponential distance model calculating the gain induced by the distance according to: pow((Math.max(distance, refDistance) / refDistance, -rolloffFactor). inverse is the default value of distanceModel. Syntax var audioCtx = new AudioContext
(); var panner = audioCtx.createPanner
(); panner.distanceModel = 'inverse'; Value A enum -- see DistanceModelType. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, a...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 3 more matches
PannerNode.maxDistance - Web APIs
The maxDistance property of the PannerNode interface is a double value representing the maximum distance between the audio source and the listener, after which the volume is not reduced any further. This value is used only by the linear distance model. The maxDistance property's default value is 10000. Syntax var audioCtx = new AudioContext
(); var panner = audioCtx.createPanner
(); panner.maxDistance = 10000; Value A double. The default is 10000, and non-positive values are not allowed. Exceptions RangeError The property has been given a value that is outside the accepted range. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the pos...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 3 more matches
PannerNode.panningModel - Web APIs
lgorithm to use to position the audio in 3D space. The possible values are: equalpower: Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value. HRTF: Renders a stereo output of higher quality than equalpower -- it uses a convolution with measured impulse responses from human subjects. Syntax var audioCtx = new AudioContext
(); var panner = audioCtx.createPanner
(); panner.panningModel = 'HRTF'; Value A enum -- see PanningModelType. Example In the following example, you can see an example of how the createPanner
() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, and th...
...er (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight
(), moveLeft
(), etc., which set new values for the panner position via the PositionPanner
() function. To see a complete implementation, check out our panner-node example (view the source code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection ...
...ce code) -- this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. ...
...And 3 more matches
PaymentAddress - Web APIs
te properties The following properties are obsolete and should no longer be used, but may still be present in some browser versions. PaymentAddress.languageCode Read only A DOMString indicating the language code of the address. This identifies the language in which the address is given, and is intended to aid in localization of the display of the address. ...
...Code Read only A DOMString indicating the language code of the address. This identifies the language in which the address is given, and is intended to aid in localization of the display of the address. Methods PaymentAddress.toJSON
() A standard serializer that returns a JSON representation of the PaymentAddress object's properties. Examples In the following example, the PaymentRequest
() constructor is used to create a new payment request, which takes three objects as parameters -- one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options. The first of these three (supportedInstruments in the example below) contains a dat...
..."success" : "failure"; ...
...And 3 more matches
PerformanceEntry.duration - Web APIs
metric, the browser may choose to return a duration of 0. Note: if the performance entry has an entryType of "resource" (i.e. the entry is a PerformanceResourceTiming object), this property returns the difference between the PerformanceEntry.responseEnd and PerformanceEntry.startTime timestamps. Example The following example shows the use of the duration property. ...
... the difference between the PerformanceEntry.responseEnd and PerformanceEntry.startTime timestamps. Example The following example shows the use of the duration property. function run_PerformanceEntry
() { log("PerformanceEntry support ..."); if (performance.mark === undefined) { log("... ...
...mple The following example shows the use of the duration property. function run_PerformanceEntry
() { log("PerformanceEntry support ..."); if (performance.mark === undefined) { log("... ...
...And 3 more matches
PerformanceEntry - Web APIs
Performance entries are also created in indirect ways such as loading a resource (such as an image). ...
...g representing the type of performance metric such as, for example, "mark". See property page for valid values. PerformanceEntry.startTime Read only A DOMHighResTimeStamp representing the starting time for the performance metric. PerformanceEntry.duration Read only A DOMHighResTimeStamp representing the time value of the duration of the performance event. ...
...ation Read only A DOMHighResTimeStamp representing the time value of the duration of the performance event. Methods PerformanceEntry.toJSON
() Returns a JSON representation of the PerformanceEntry object. Example The following example checks all PerformanceEntry properties to see if the browser supports them and if so, write their values to the console. ...
...And 3 more matches
Performance Timeline - Web APIs
an overview of the standard's interfaces. For more details about the interfaces, see the reference pages and Using Performance Timeline. Performance extensions The Performance Timeline API extends the Performance interface with three methods that provide different mechanisms to get a set of performance records (metrics), depending on the specified filter criteria. The methods are: getEntries
() Returns all recorded performance entries or, optionally, the entries based on the specified name, performance type and/or the initiatorType (such as an HTML element). getEntriesByName
() Returns the recorded performance entries based on the specified name and optionally the performance type. getEntriesByType
() Returns the recorded performance entries based on the specified performance type. ...
... The type of performance metric (for example, "mark"). startTime A high resolution timestamp representing the starting time for the performance entry. duration A high resolution timestamp representing the time value of the duration of the performance event. (Some performance entry types have no concept of duration and this value is set to '0' for such types.) This interface includes a toJSON
() method that returns the serialization of the PerformanceEntry object. The serialization is specific to the performance entry's type. Performance observers The performance observer interfaces allow an application to register an observer for specific performance event types, and when one of those event types is recorded, the application is notified of the event via the observer's callback func...
...rded, the application is notified of the event via the observer's callback function that was specified when the observer was created. When the observer (callback) is invoked, the callback's parameters include a performance observer entry list that contains only observed performance entries. ...
...And 3 more matches
PublicKeyCredential - Web APIs
holds the globally unique identifier for this PublicKeyCredential. This identifier can be used to look up credentials for future calls to CredentialsContainer.get. PublicKeyCredential.response Read only Secure context An instance of an AuthenticatorResponse object. ...
...future calls to CredentialsContainer.get. PublicKeyCredential.response Read only Secure context An instance of an AuthenticatorResponse object. It is either of type AuthenticatorAttestationResponse if the PublicKeyCredential was the results of a navigator.credentials.create
() call, or of type AuthenticatorAssertionResponse if the PublicKeyCredential was the result of a navigator.credentials.get
() call. ...
...onse Read only Secure context An instance of an AuthenticatorResponse object. It is either of type AuthenticatorAttestationResponse if the PublicKeyCredential was the results of a navigator.credentials.create
() call, or of type AuthenticatorAssertionResponse if the PublicKeyCredential was the result of a navigator.credentials.get
() call. Methods PublicKeyCredential.getClientExtensionResults
()Secure context If any extensions were requested, this method will return the results of processing those extensions. PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable
()Secure context A static method returning a Promise which resolves to true if an authenticator bound to the platform is capable of verifying the user. With the current state of implementation, this method only reso...
...And 3 more matches
RTCIceTransport - Web APIs
e used to determine whether the ICE agent has made an initial connection using a viable candidate pair ("connected"), made its final selection of candidate pairs ("completed"), or in an error state ("failed"), among other states. See the RTCIceTransportState enumerated type for a complete list of states. Methods Also includes methods from EventTarget, the parent interface. ...
...Also includes methods from EventTarget, the parent interface. getLocalCandidates
() Returns an array of RTCIceCandidate objects, each describing one of the ICE candidates that have been gathered so far for the local device. These are the same candidates which have already been sent to the remote peer by sending an icecandidate event to the RTCPeerConnection for transmission. getLocalParameters
() Returns a RTCIceParameters object describing the ICE parameters established by a call to the RTCPeerConnection.setLocalDescription
() method. Returns null if parameters have not yet been received. ...
...evice. These are the same candidates which have already been sent to the remote peer by sending an icecandidate event to the RTCPeerConnection for transmission. getLocalParameters
() Returns a RTCIceParameters object describing the ICE parameters established by a call to the RTCPeerConnection.setLocalDescription
() method. Returns null if parameters have not yet been received. getRemoteCandidates
() Returns an array of RTCIceCandidate objects, one for each of the remote device's ICE candidates that have been received by the local end of the RTCPeerConnection and delivered to ICE by calling addIceCandidate
(). getRemoteParameters
() Returns a RTCIceParameters object containing the ICE parameters for the remote device, as set by a call to RTCPeerConnection.setRemoteDescription
(). If setRemote...
...And 3 more matches
ReadableStreamDefaultController - Web APIs
internal queue. Default controllers are for streams that are not byte streams. Constructor None. ReadableStreamDefaultController instances are created automatically during ReadableStream construction. Properties ReadableStreamDefaultController.desiredSize Read only Returns the desired size required to fill the stream's internal queue. Methods ReadableStreamDefaultController.close
() Closes the associated stream. ReadableStreamDefaultController.enqueue
() Enqueues a given chunk in the associated stream. ReadableStreamDefaultController.error
() Causes any future interactions with the associated stream to error. Examples In the following simple example, a custom ReadableStream is created using a constructor (see our Simple random stream example for the full code). The sta...
...Closes the associated stream. ReadableStreamDefaultController.enqueue
() Enqueues a given chunk in the associated stream. ReadableStreamDefaultController.error
() Causes any future interactions with the associated stream to error. Examples In the following simple example, a custom ReadableStream is created using a constructor (see our Simple random stream example for the full code). The start
() function generates a random string of text every second and enqueues it into the stream. A cancel
() function is also provided to stop the generation if ReadableStream.cancel
() is called for any reason. Note that a ReadableStreamDefaultController object is provided as the parameter of the start
() and pull
() functions. When a button is pressed, the generation is stopped, the stream is closed usin...
...text every second and enqueues it into the stream. A cancel
() function is also provided to stop the generation if ReadableStream.cancel
() is called for any reason. Note that a ReadableStreamDefaultController object is provided as the parameter of the start
() and pull
() functions. When a button is pressed, the generation is stopped, the stream is closed using ReadableStreamDefaultController.close
(), and another function is run, which reads the data back out of the stream. ...
...And 3 more matches
Request.cache - Web APIs
{ /* consume the response */ }); // Naive stale-while-revalidate client-level implementation. // Prefer a cached albeit stale response; but update if it's too old. // AbortController and signal to allow better memory cleaning. ...
...hange the value let controller = new AbortController
(); fetch("some.json", {cache: "only-if-cached", mode: "same-origin", signal: controller.signal}) .catch(e => e instanceof TypeError && e.message === "Failed to fetch" ? ({status: 504}) : // Workaround for chrome; which simply fails with a typeerror Promise.reject(e)) .then(res => { if (res.status === 504) { controller.abort
() controller = new AbortController
(); return fetch("some.json", {cache: "force-cache", mode: "same-origin", signal: controller.signal}) } const date = res.headers.get("date"), dt = date ? ...
...tatus: 504}) : // Workaround for chrome; which simply fails with a typeerror Promise.reject(e)) .then(res => { if (res.status === 504) { controller.abort
() controller = new AbortController
(); return fetch("some.json", {cache: "force-cache", mode: "same-origin", signal: controller.signal}) } const date = res.headers.get("date"), dt = date ? ...
...And 3 more matches
SVGMatrix - Web APIs
senting the a component of the matrix. SVGMatrix.b A float representing the b component of the matrix. SVGMatrix.c A float representing the c component of the matrix. SVGMatrix.d A float representing the d component of the matrix. SVGMatrix.e A float representing the e component of the matrix. SVGMatrix.f A float representing the f component of the matrix. ...
...nt of the matrix. SVGMatrix.d A float representing the d component of the matrix. SVGMatrix.e A float representing the e component of the matrix. SVGMatrix.f A float representing the f component of the matrix. Methods SVGMatrix.multiply
() Performs matrix multiplication. This matrix is post-multiplied by another matrix, returning the resulting new matrix as SVGMatrix. SVGMatrix.inverse
() Returns the inverse matrix as SVGMatrix. ...
...ent of the matrix. SVGMatrix.e A float representing the e component of the matrix. SVGMatrix.f A float representing the f component of the matrix. Methods SVGMatrix.multiply
() Performs matrix multiplication. This matrix is post-multiplied by another matrix, returning the resulting new matrix as SVGMatrix. SVGMatrix.inverse
() Returns the inverse matrix as SVGMatrix. SVGMatrix.translate
() Post-multiplies a translation transformation on the current matrix and returns the resulting matrix as SVGMatrix. ...
...And 3 more matches
SVGTransformList - Web APIs
t defines a list of SVGTransform objects. An SVGTransformList object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
... length unsigned long The number of items in the list. Meth...
...fItems readonly unsigned long length Normative document SVG 1.1 (2nd Edition) Properties Name Type Description numberOfItems unsigned long The number of items in the list. length unsigned long The number of items in the list. Methods Name & Arguments Return Description clear
() void Clears all existing current items from the list, with the result being an empty list. Exceptions: a DOMException with code NO_MODIFICATION_ALLOWED_ERR is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in SVGTransform newItem) SVGTransform Clears all existing current items fro...
...And 3 more matches
SpeechGrammarList - Web APIs
The SpeechGrammarList interface of the Web Speech API represents a list of SpeechGrammar objects containing words or patterns of words that we want the recognition service to recognize. Grammar is defined using JSpeech Grammar Format (JSGF.) Other formats may also be supported in the future. Constructor SpeechGrammarList.SpeechGrammarList
() Creates a new SpeechGrammarList object. ...
...nition service to recognize. Grammar is defined using JSpeech Grammar Format (JSGF.) Other formats may also be supported in the future. Constructor SpeechGrammarList.SpeechGrammarList
() Creates a new SpeechGrammarList object. Properties SpeechGrammarList.length Read only Returns the number of SpeechGrammar objects contained in the SpeechGrammarList. Methods SpeechGrammarList.item
() Standard getter -- allows individual SpeechGrammar objects to be retrieved from the SpeechGrammarList using array syntax. SpeechGrammarList.addFromURI
() Takes a grammar present at a specific URI and adds it to the SpeechGrammarList as a new SpeechGrammar object. SpeechGrammarList.addFromString
() Takes a grammar present in a specific DOMString within the code base (e.g. stored in a variable) ...
...d adds it to the SpeechGrammarList as a new SpeechGrammar object. SpeechGrammarList.addFromString
() Takes a grammar present in a specific DOMString within the code base (e.g. stored in a variable) and adds it to the SpeechGrammarList as a new SpeechGrammar object. Examples In our simple Speech color changer example, we create a new SpeechRecognition object instance using the SpeechRecognition
() constructor, create a new SpeechGrammarList, add our grammar string to it using the SpeechGrammarList.addFromString method, and set it to be the grammar that will be recognised by the SpeechRecognition instance using the SpeechRecognition.grammars property. var grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crims...
...And 3 more matches
Storage Access API - Web APIs
sers who wish to continue to interact with embedded content are forced to greatly relax their blocking policy for resources loaded from all embedded origins and possibly across all websites. The Storage Access API is intended to solve this problem; embedded cross-origin content can request unrestricted access to its first-party storage on a site-by-site basis via the Document.requestStorageAccess
() method, and check whether it already has access via the Document.hasStorageAccess
() method. In addition, sandboxed <iframe>s cannot be granted storage access by default for security reasons. The API therefore also adds the allow-storage-access-by-user-activation sandbox token. The embedding website needs to add this to allow storage access requests to be successful, along with allow-scripts and ...
...(in Firefox, "recently" is "within 30 days"). The browser may decide to involve the user in the decision of whether to grant an incoming storage access request. Specifics regarding the lifetime of a storage grant and the circumstances under which the browser may decide to inform the user are currently being worked through and will be announced once ready. User prompts When requestStorageAccess
() is called by an embedded, cross-origin document, the user agent may choose to involve the user in the decision of whether to grant storage access to the requesting origin. Prompting heuristics currently vary across the two implementers of the Storage Access API -- Safari shows prompts for all embedded tracking content that has not previously received storage access, while Firefox only prompts use...
... storage access to the requesting origin. Prompting heuristics currently vary across the two implementers of the Storage Access API -- Safari shows prompts for all embedded tracking content that has not previously received storage access, while Firefox only prompts users after a tracking origin has requested storage access on more than a threshold number of sites. See Document.requestStorageAccess
() for more details. Safari implementation differences Although the API surface is the same, websites using the Storage Access API should expect differences in the level and extent of storage access they receive between Firefox and Safari. This is caused by differences in the storage access policies implemented in the two browsers. Design properties unique to Firefox are summarized here: If the...
...And 3 more matches
Streams API concepts - Web APIs
a conventional stream for reading underlying byte sources (otherwise known as BYOB, or "bring your own buffer") sources. These allow streams to be read straight into a buffer supplied by the developer, minimizing the copying required. ...
...ableStream
() constructor page). Important: Byte streams 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. This may change over time. You can make use of ready-made readable streams via mechanisms like a Response.body from a fetch request, or roll your own streams using the ReadableStream
() constructor. Teeing Even though only a single reader can read a stream at once, it is possible to split a stream into two identical copies, which can then be read by two separate readers. This is called teeing. ...
... readable streams via mechanisms like a Response.body from a fetch request, or roll your own streams using the ReadableStream
() constructor. Teeing Even though only a single reader can read a stream at once, it is possible to split a stream into two identical copies, which can then be read by two separate readers. This is called teeing. In JavaScript, this is achieved via the ReadableStream.tee
() method -- it outputs an array containing two identical copies of the original readable stream, which can then be read independently by two separate readers. You might do this for example in a ServiceWorker if you want to fetch a response from the server and stream it to the browser, but also stream it to the ServiceWorker cache. Since a response body cannot be consumed more than once, and a stre...
...And 3 more matches
StylePropertyMapReadOnly - Web APIs
The StylePropertyMapReadOnly interface of the the CSS Typed Object Model API provides a read-only representation of a CSS declaration block that is an alternative to CSSStyleDeclaration. Retrieve an instance of this interface using Element.computedStyleMap
(). Properties StylePropertyMapReadOnly.size Returns an unsinged long integer containing the size of the StylePropertyMapReadOnly object. Methods StylePropertyMapReadOnly.entries
() Returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). StylePropertyMapReadOnly.forEach
() Executes a provided function once for each element of StylePropertyMapReadOnly. St...
...MapReadOnly.entries
() Returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). StylePropertyMapReadOnly.forEach
() Executes a provided function once for each element of StylePropertyMapReadOnly. StylePropertyMapReadOnly.get
() Returns the value of the specified property. StylePropertyMapReadOnly.getAll
() Returns an array of CSSStyleValue objects containing the values for the provided property. StylePropertyMapReadOnly.has
() Indicates whether the specified property is in the StylePropertyMapReadOnly object. ...
...e for each element of StylePropertyMapReadOnly. StylePropertyMapReadOnly.get
() Returns the value of the specified property. StylePropertyMapReadOnly.getAll
() Returns an array of CSSStyleValue objects containing the values for the provided property. StylePropertyMapReadOnly.has
() Indicates whether the specified property is in the StylePropertyMapReadOnly object. StylePropertyMapReadOnly.keys
() Returns a new Array Iterator containing the keys for each item in StylePropertyMapReadOnly. StylePropertyMapReadOnly.values
() Returns a new Array Iterator containing the values for each index in the StylePropertyMapReadOnly object. Examples We have to have an element to observe: <p> This is a paragraph with some text. We can add some CSS, or not. The style map will include all the de...
...And 3 more matches
TreeWalker - Web APIs
Properties This interface doesn't inherit any property. TreeWalker.root Read only Returns a Node representing the root node as specified when the TreeWalker was created. TreeWalker.whatToShow Read only Returns an unsigned long being a bitmask made of constants describing the types of Node that must be presented. Non-matching nodes are skipped, but their children may be included, if relevant. ...
... the same time. TreeWalker.currentNode Is the Node on which the TreeWalker is currently pointing at. Methods This interface doesn't inherit any method. Note: in the context of a TreeWalker, a node is visible if it exists in the logical view determined by the whatToShow and filter parameter arguments. ...
...e node is visible on the screen is irrelevant.) TreeWalker.parentNode
() Moves the current Node to the first visible ancestor node in the document order, and returns the found node. It also moves the current node to this one. If no such node exists, or if it is before that the root node defined at the object construction, returns null and the current node is not changed. TreeWalker.firstChild
() Moves the current Node to the first visible child of the current node, and returns the found child. It also moves the current node to this child. If no such child exists, returns null and the current node is not changed. TreeWalker.lastChild
() Moves the current Node to the last visible child of the current node, and returns the found child. It also moves the current node to this child. If no s...
...And 3 more matches
UserDataHandler - Web APIs
Obsolete since Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Summary When associating user data with a key on a node, Node.setUserData
() can also accept, in its third argument, a handler which will be called when the object is cloned, imported, deleted, renamed, or adopted. Per the specification, exceptions should not be thrown in a UserDataHandler. In both document.importNode
() and Node.cloneNode
(), although user data is not copied over, the handler will be called. Properties None. Methods handle (operation, key, data, src, dst) (no return value) This method is a callback which will be called if a node i...
...ted, renamed and as well, if deleted or adopted. operation (unsigned short) is an operation type integer (see below). key (DOMString) is the user key. data (DOMUserData) is the user data. src (Node) is the source node (null if being deleted). dst (Node) is the destination node (if any, or null). ...
...peration (unsigned short) is an operation type integer (see below). key (DOMString) is the user key. data (DOMUserData) is the user data. src (Node) is the source node (null if being deleted). dst (Node) is the destination node (if any, or null). ...
...And 3 more matches
WakeLockSentinel - Web APIs
This can happen if the document becomes inactive or looses visibility, if the device is low on power or the user turns on a power save mode. ...
...This can happen if the document becomes inactive or looses visibility, if the device is low on power or the user turns on a power save mode. ...
... lock type will cause the underlying platform wake lock to be released. Properties This interface provides the following properties. type Read only Returns a String representation of the currently acquired WakeLockSentinel type. Return values are: 'screen': A screen wake lock. Prevents devices from dimming or locking the screen. Event handlers onrelease Fired when the release
() method is called or the wake lock is released by the user agent. Methods release
() Releases the WakeLockSentinel, returning a Promise that is resolved once the sentinel has been successfully released. Examples In this example we create an asynchronous function which requests a WakeLockSentinel. Once acquired we listen for the onrelease event which can be used to give appropriate UI feedb...
...And 3 more matches
WebGLTransformFeedback - Web APIs
f the WebGL 2 API and enables transform feedback, which is the process of capturing primitives generated by vertex processing. It allows to preserve the post-transform rendering state of an object and resubmit this data multiple times. ...
...which is the process of capturing primitives generated by vertex processing. It allows to preserve the post-transform rendering state of an object and resubmit this data multiple times. ...
...enerated by vertex processing. It allows to preserve the post-transform rendering state of an object and resubmit this data multiple times. ...
...And 3 more matches
Creating 3D objects using WebGL - Web APIs
Consider: each face requires four vertices to define it, but each vertex is shared by three faces. ...
... Consider: each face requires four vertices to define it, but each vertex is shared by three faces. ...
...rtex in three different colors, one for each face. 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>. Define the positions of the cube's vertices First, let's build the cube's vertex position buffer by updating the code in initBuffers
(). This is pretty much the same as it was for the square plane, but somewhat longer since there are 24 vertices (4 per side): const positions = [ // Front face -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, // Back face -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, // Top face -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0,...
...And 3 more matches
Window.speechSynthesis - Web APIs
y point into using Web Speech API speech synthesis functionality. Syntax var synth = window.speechSynthesis; Value A SpeechSynthesis object. Examples In our basic Speech synthesiser demo, we first grab a reference to the SpeechSynthesis controller using window.speechSynthesis. ...
...eech synthesiser demo, we first grab a reference to the SpeechSynthesis controller using window.speechSynthesis. After defining some necessary variables, we retrieve a list of the voices available using SpeechSynthesis.getVoices
() and populate a select menu with them so the user can choose what voice they want. Inside the inputForm.onsubmit handler, we stop the form submitting with preventDefault
(), create a new SpeechSynthesisUtterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the SpeechSynthesis.speak
() method. var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.
...taining the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the SpeechSynthesis.speak
() method. ...
...And 3 more matches
WindowEventHandlers.onhashchange - Web APIs
The WindowEventHandlers.onhashchange property of the WindowEventHandlers mixin is the EventHandler for processing hashchange events. The hashchange event fires when a window's hash changes (see Window.location and HTMLHyperlinkElementUtils.hash). Syntax Using an event handler: window.onhashchange = funcRef; Using an HTML event handler: <body onhashchange="funcRef
();"> Using an event listener: To add an event listener, use addEventListener
(): window.addEventListener("hashchange", funcRef, false); Parameters funcRef A reference to a function. Examples Using an event handler This example uses an event handler (window.onhashchange) to check the new hash value whenever it changes. If it equals #cool-feature, the script logs a message to the console. function locationHashCha...
... To add an event listener, use addEventListener
(): window.addEventListener("hashchange", funcRef, false); Parameters funcRef A reference to a function. Examples Using an event handler This example uses an event handler (window.onhashchange) to check the new hash value whenever it changes. If it equals #cool-feature, the script logs a message to the console. function locationHashChanged
() { if (location.hash === '#cool-feature') { console.log("You're visiting a cool feature!"); } } window.onhashchange = locationHashChanged; Using an event listener This example uses an event listener to log a notification whenever the hash has changed. ...
...r it changes. If it equals #cool-feature, the script logs a message to the console. function locationHashChanged
() { if (location.hash === '#cool-feature') { console.log("You're visiting a cool feature!"); } } window.onhashchange = locationHashChanged; Using an event listener This example uses an event listener to log a notification whenever the hash has changed. function hashHandler
() { console.log('The hash has changed!'); } window.addEventListener('hashchange', hashHandler, false); Overriding the hash This function sets a new hash dynamically, setting it randomly to one of two values. ...
...And 3 more matches
WindowOrWorkerGlobalScope - Web APIs
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. 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...
...GlobalScope.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. Methods These methods are defined on the WindowOrWorkerGlobalScope mixin, and implemented by Window and WorkerGlobalScope. ...
...(true) or not (false). WindowOrWorkerGlobalScope.origin Read only Returns the origin of the global scope, serialized as a string. Methods These methods are defined on the WindowOrWorkerGlobalScope mixin, and implemented by Window and WorkerGlobalScope. WindowOrWorkerGlobalScope.atob
() Decodes a string of data which has been encoded using base-64 encoding. WindowOrWorkerGlobalScope.btoa
() Creates a base-64 encoded ASCII string from a string of binary data. ...
...And 3 more matches
WorkerGlobalScope.self - Web APIs
re dealing with, as indicated above). ...
...orker, you will get a worker global scope of the same type as that worker object written to the console -- something like the following: DedicatedWorkerGlobalScope { undefined: undefined, Infinity: Infinity, Math: MathConstructor, NaN: NaN, Intl: Object...} Infinity: Infinity Array: function Array
() { [native code] } arguments: null caller: null isArray: function isArray
() { [native code] } length: 1 name: "Array" observe: function observe
() { [native code] } prototype: Array[0] unobserve: function unobserve
() { [native code] } __proto__: function Empty
() {} <function scope> ArrayBuffer: function ArrayBuffer
() { [native code] } Blob: function Blob
() { [native code] } Boolean: function Boolean
() { [native code] }...
...etc. ...
...And 3 more matches
XDomainRequest - Web APIs
lementation of HTTP access control (CORS) that worked in Internet Explorer 8 and 9. It was removed in Internet Explorer 10 in favor of using XMLHttpRequest with proper CORS; if you are targeting Internet Explorer 10 or later, or wish to support any other browser, you need to use standard HTTP access control. This interface can send both GET and POST requests. ...
...cess control. This interface can send both GET and POST requests. Syntax var xdr = new XDomainRequest
(); Returns a new XDomainRequest object, which can then be used to make and manage these requests. Properties XDomainRequest.timeout Gets or sets the amount of time until a request times out. XDomainRequest.responseText Gets the response body as a string. Methods XDomainRequest.open
() Opens the request, specifing the method (GET/POST) and URL. XDomainRequest.send
() Sends the request. POST data is specified in this method. XDomainRequest.abort
() Aborts the request. Event handlers XDomainRequest.onprogress A handler for when the request has made progress between the send method call and the onload event. XDomainRequest.ontimeout A handler for when the request times ...
...A handler for when the request has made progress between the send method call and the onload event. XDomainRequest.ontimeout A handler for when the request times out. XDomainRequest.onerror A handler for when a request has errored. XDomainRequest.onload A handler for when the full response has been received from the server. ...
...And 3 more matches
XMLSerializer - Web APIs
The XMLSerializer interface provides the serializeToString
() method to construct an XML string representing a DOM tree. Methods serializeToString
() Returns the serialized subtree of a string. serializeToStream
() The subtree rooted by the specified element is serialized to a byte stream using the character set specified. Examples Serializing XML into a string The first, basic, example just serializes an entire document into a string containing XML. var s = new XMLSerializer
(); var d = document; var str = s.serializeToString(d); saveXML(str); This involves creating a new XMLSerializer object, then passing the Document to be serialized into serializeToString
(), which returns the XML equivalent of the document. Inserting nodes into a DOM based on XML This example uses the ...
...document into a string containing XML. var s = new XMLSerializer
(); var d = document; var str = s.serializeToString(d); saveXML(str); This involves creating a new XMLSerializer object, then passing the Document to be serialized into serializeToString
(), which returns the XML equivalent of the document. Inserting nodes into a DOM based on XML This example uses the Element.insertAdjacentHTML
() method to insert a new DOM Node into the body of the Document, based on XML created by serializing an Element object. ...
... then passing the Document to be serialized into serializeToString
(), which returns the XML equivalent of the document. Inserting nodes into a DOM based on XML This example uses the Element.insertAdjacentHTML
() method to insert a new DOM Node into the body of the Document, based on XML created by serializing an Element object. ...
...And 3 more matches
XRSession - Web APIs
With XRSession methods, you can poll the viewer's position and orientation (the XRViewerPose), gather information about the user's environment, and present imagery to the user. XRSession supports both inline and immersive virtual and augmented reality modes. ...
...augmented reality modes. Properties In addition to the properties listed below, XRSession inherits properties from its parent interface, EventTarget. environmentBlendMode Read only Returns this session's blend mode which denotes how much of the real-world environment is visible through the XR device and how the device will blend the device imagery with it. Note: environmentBlendMode
() is part of the WebXR Augmented Reality Module, which has not been completed. inputSources Read only Returns a list of this session's XRInputSources, each representing an input device used to control the camera and/or scene. renderState Read only An XRRenderState object which contains options affecting how the imagery is rendered. This includes things such as the near and far clipping ...
...e Read only A DOMString whose value is one of those found in the XRVisibilityState enumerated type, indicating whether or not the session's imagery is visible to the user, and if so, if it's being visible but not currently the target for user events. Methods XRSession provides the following methods in addition to those inherited from its parent interface, EventTarget. ...
...And 3 more matches
-webkit-tap-highlight-color - CSS: Cascading Style Sheets
their tap is being successfully recognized, and indicates which element they're tapping on. -webkit-tap-highlight-color: red; -webkit-tap-highlight-color: transparent; /* for removing the highlight */ Syntax Values A <color value>. ...
...s being successfully recognized, and indicates which element they're tapping on. -webkit-tap-highlight-color: red; -webkit-tap-highlight-color: transparent; /* for removing the highlight */ Syntax Values A <color value>. ...
...ccessfully recognized, and indicates which element they're tapping on. -webkit-tap-highlight-color: red; -webkit-tap-highlight-color: transparent; /* for removing the highlight */ Syntax Values A <color value>. ...
...And 3 more matches
-webkit-text-fill-color - CSS: Cascading Style Sheets
: rgb(100, 200, 0); /* Global values */ -webkit-text-fill-color: inherit; -webkit-text-fill-color: initial; -webkit-text-fill-color: unset; Syntax Values <color> The foreground fill color of the element's text content. ...
...200, 0); /* Global values */ -webkit-text-fill-color: inherit; -webkit-text-fill-color: initial; -webkit-text-fill-color: unset; Syntax Values <color> The foreground fill color of the element's text content. ...
.../* Global values */ -webkit-text-fill-color: inherit; -webkit-text-fill-color: initial; -webkit-text-fill-color: unset; Syntax Values <color> The foreground fill color of the element's text content. ...
...And 3 more matches
-webkit-text-stroke-color - CSS: Cascading Style Sheets
-webkit-text-stroke-color: rgb(200, 100, 0); /* Global values */ -webkit-text-stroke-color: inherit; -webkit-text-stroke-color: initial; -webkit-text-stroke-color: unset; Syntax Values <color> The color of the stroke. ...
...xt-stroke-color: rgb(200, 100, 0); /* Global values */ -webkit-text-stroke-color: inherit; -webkit-text-stroke-color: initial; -webkit-text-stroke-color: unset; Syntax Values <color> The color of the stroke. ...
...color: rgb(200, 100, 0); /* Global values */ -webkit-text-stroke-color: inherit; -webkit-text-stroke-color: initial; -webkit-text-stroke-color: unset; Syntax Values <color> The color of the stroke. ...
...And 3 more matches
-webkit-text-stroke - CSS: Cascading Style Sheets
) | rgba( <number>{3} [ / <alpha-value> ]? ) | rgba( <per...
...) | rgba( <number>{3} [ / <alpha-value> ]? ) | rgba( <percentage>#{3...
...) | rgba( <number>{3} [ / <alpha-value> ]? ) | rgba( <percentage>#{3} , <alpha...
...And 3 more matches
CSS Animations tips and tricks - CSS: Cascading Style Sheets
re things you might want to do that aren't obvious, or clever ways to do things that you might not come up with right away. This article is a collection of tips and tricks we've found that may make your work easier, including how to run a stopped animation again. Run an animation again The CSS Animations specification doesn't offer a way to run an animation again. There's no magic resetAnimation
() method on elements, and you can't even just set the element's animation-play-state to "running" again. Instead, you have to use clever tricks to get a stopped animation to replay. Here's one way to do it that we feel is stable and reliable enough to suggest to you. HTML content First, let's define the HTML for a <div> we wish to animate and a button that will play (or replay) the animation. <...
...imation details are included in the "changing" class, which says that the @keyframes named "colorchange" should be used over the course of two seconds to animate the box. Note that because of this, the box doesn't start with any animation effects in place, so it won't be animating. JavaScript content Next we'll look at the JavaScript that does the work. ...
...named "colorchange" should be used over the course of two seconds to animate the box. Note that because of this, the box doesn't start with any animation effects in place, so it won't be animating. JavaScript content Next we'll look at the JavaScript that does the work. The meat of this technique is in the play
() function, which is called when the user clicks on the "Run" button. ...
...And 3 more matches
CSS values and units - CSS: Cascading Style Sheets
s A <url> type uses functional notation, which accepts a <string> that is a URL. This may be an absolute URL or a relative URL. For example, if you wanted to include a background image, you might use either of the following. .box { background-image: url("images/my-background.png"); } .box { background-image: url("https://www.exammple.com/images/my-background.png"); } The parameter for url
() can be either quoted or unquoted. If unquoted, it is parsed as a <url-token>, which has extra requirements including the escaping of certain characters. See <url> for more information. Numeric data types <integer> <number> <dimension> <percentage> Integers An integer is one or more decimal digits, 0 through 9, such as 1024 or -55. An integer may be preceded by a + or - symbol, with no ...
...of image that can be used in CSS, and is defined in the CSS Image Values and Replaced Content Module. Position The <position> type defines 2D positioning of an object inside a positioning area, for example a background image inside a container. This type is interpreted as a background-position and therefore specified in the CSS Backgrounds and Borders specification. Functional notation calc
() min
() max
() clamp
() toggle
() attr
() Functional notation is a type of value that can represent more complex types or invoke special processing by CSS. The syntax starts with the name of the function immediately followed by a left parenthesis ( followed by the argument(s) to the notation followed by a right parenthesis ). Functions can take multiple arguments, which are formatted similarly t...
...cessing by CSS. The syntax starts with the name of the function immediately followed by a left parenthesis ( followed by the argument(s) to the notation followed by a right parenthesis ). Functions can take multiple arguments, which are formatted similarly to a CSS property value. White space is allowed, but optional inside the parentheses. (But see notes regarding whitespace within pages for min
(), max
() and clamp
() functions.) Some legacy functional notations such as rgba
() use commas, but generally commas are only used to separate items in a list. If a comma is used to separate arguments, white space is optional before and after the comma. Specifications Specification Status Comment CSS Values and Units Module Level 4 Editor's Draft Adds the vi, vb, i...
...And 3 more matches
background-color - CSS: Cascading Style Sheets
, or 24px or larger. WebAIM: Color Contrast Checker MDN Understanding WCAG, Guideline 1.4 explanations Understanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0 Formal definition Initial valuetransparentApplies toall elements. ...
...r larger. WebAIM: Color Contrast Checker MDN Understanding WCAG, Guideline 1.4 explanations Understanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0 Formal definition Initial valuetransparentApplies toall elements. ...
... WebAIM: Color Contrast Checker MDN Understanding WCAG, Guideline 1.4 explanations Understanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0 Formal definition Initial valuetransparentApplies toall elements. ...
...And 3 more matches
border-block-end - CSS: Cascading Style Sheets
) | rgba( <number>{3} [ / <alpha-value> ]? ) | rgba( <per...
...) | rgba( <number>{3} [ / <alpha-value> ]? ) | rgba( <percentage>#{3...
...) | rgba( <number>{3} [ / <alpha-value> ]? ) | rgba( <percentage>#{3} , <alpha...
...And 3 more matches
border-block-start - CSS: Cascading Style Sheets
) | rgba( <number>{3} [ / <alpha-value> ]? ) | rgba( <per...
...) | rgba( <number>{3} [ / <alpha-value> ]? ) | rgba( <percentage>#{3...
...) | rgba( <number>{3} [ / <alpha-value> ]? ) | rgba( <percentage>#{3} , <alpha...
...And 3 more matches
border-block - CSS: Cascading Style Sheets
) | rgba( <number>{3} [ / <alpha-value> ]? ) | rgba( <per...
...) | rgba( <number>{3} [ / <alpha-value> ]? ) | rgba( <percentage>#{3...
...) | rgba( <number>{3} [ / <alpha-value> ]? ) | rgba( <percentage>#{3} , <alpha...
...And 3 more matches
column-rule-color - CSS: Cascading Style Sheets
*/ column-rule-color: inherit; column-rule-color: initial; column-rule-color: unset; The column-rule-color property is specified as a single <color> value. Values <color> The color of the rule that separates columns. ...
...ule-color: inherit; column-rule-color: initial; column-rule-color: unset; The column-rule-color property is specified as a single <color> value. Values <color> The color of the rule that separates columns. ...
... inherit; column-rule-color: initial; column-rule-color: unset; The column-rule-color property is specified as a single <color> value. Values <color> The color of the rule that separates columns. ...
...And 3 more matches
offset-path - CSS: Cascading Style Sheets
offset-path: circle(50% at 25% 25%); offset-path: inset(50% 50% 50% 50%); offset-path: polygon(30% 0%, 70% 0%, 100% 50%, 30% 100%, 0% 70%, 0% 30%); offset-path: path('M 0,200 Q 200,200 260,80 Q 290,20 400,0 Q 300,100 400,200'); /* Geometry Boxes */ offset-path: margin-box; offset-path: stroke-box; /* Global values */ offset-path: inherit; offset-path: initial; offset-path: unset; Values ray
() Taking up to three values, defines a path that is a line segment starting from the position of the box and proceeds in the direction defined by the specified angle similar to the CSS gradient angle where 0deg is up, with positive angles increasing in the clockwise direction, with the size value being similar to the CSS radial gradient size values from closest-side to farthest-corner, and the key...
...ee values, defines a path that is a line segment starting from the position of the box and proceeds in the direction defined by the specified angle similar to the CSS gradient angle where 0deg is up, with positive angles increasing in the clockwise direction, with the size value being similar to the CSS radial gradient size values from closest-side to farthest-corner, and the keyterm contain. url
() References the ID of an SVG shape -- circle, ellipse, line, path, polygon, polyline, or rect -- using the shape's geometry as the path. <basic-shape> Specifies a CSS shape including circle
(), ellipse
(), inset
(), polygon
(), or path
(). path
() A path string defined with SVG coordinate syntax. none Specifies no motion path at all. Description This property defines a path an anima...
...and an initial direction which specifies the rotation of the object to the initial position. Early versions of the spec called this property motion-path. It was changed to offset-path because the property describes static positions, not motion. ...
...And 3 more matches
scrollbar-color - CSS: Cascading Style Sheets
ensure the specified colors have enough contrast between them. For keyword values, UAs should ensure the colors they use have enough contrast. See Techniques for WCAG 2.0: G183: Using a contrast ratio of 3:1. ...
... specified colors have enough contrast between them. For keyword values, UAs should ensure the colors they use have enough contrast. See Techniques for WCAG 2.0: G183: Using a contrast ratio of 3:1. ...
... colors have enough contrast between them. For keyword values, UAs should ensure the colors they use have enough contrast. See Techniques for WCAG 2.0: G183: Using a contrast ratio of 3:1. ...
...And 3 more matches
text-decoration-color - CSS: Cascading Style Sheets
te a link has focus. WebAIM: Color Contrast Checker MDN Understanding WCAG, Guideline 1.4 explanations Understanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0 Formal definition Initial valuecurrentcolorApplies toall elements. ...
...as focus. WebAIM: Color Contrast Checker MDN Understanding WCAG, Guideline 1.4 explanations Understanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0 Formal definition Initial valuecurrentcolorApplies toall elements. ...
... WebAIM: Color Contrast Checker MDN Understanding WCAG, Guideline 1.4 explanations Understanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0 Formal definition Initial valuecurrentcolorApplies toall elements. ...
...And 3 more matches
text-emphasis-color - CSS: Cascading Style Sheets
Global values */ text-emphasis-color: inherit; text-emphasis-color: initial; text-emphasis-color: unset; Syntax Values <color> Defines the color of the emphasis marks. If no color is present, it defaults to currentcolor. ...
...es */ text-emphasis-color: inherit; text-emphasis-color: initial; text-emphasis-color: unset; Syntax Values <color> Defines the color of the emphasis marks. If no color is present, it defaults to currentcolor. ...
...-emphasis-color: inherit; text-emphasis-color: initial; text-emphasis-color: unset; Syntax Values <color> Defines the color of the emphasis marks. If no color is present, it defaults to currentcolor. ...
...And 3 more matches
text-shadow - CSS: Cascading Style Sheets
the bigger the blur; the shadow becomes wider and lighter. If not specified, it defaults to 0. Formal definition Initial valuenoneApplies toall elements. ...
... the blur; the shadow becomes wider and lighter. If not specified, it defaults to 0. Formal definition Initial valuenoneApplies toall elements. ...
... the shadow becomes wider and lighter. If not specified, it defaults to 0. Formal definition Initial valuenoneApplies toall elements. ...
...And 3 more matches
Printing - Developer guides
r) send beforeprint and afterprint events to let content determine when printing may have occurred. You can use this to adjust the user interface presented during printing (such as by displaying or hiding user interface elements during the print process). Note: You can also use window.onbeforeprint and window.onafterprint to assign handlers for these events, but using EventTarget.addEventListener
() is preferred. Examples Here are some common examples. Open and automatically close a popup window when finished If you want to be able to automatically close a popup window (for example, the printer-friendly version of a document) after the user prints its contents, you can use code like this: <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" ...
...ished If you want to be able to automatically close a popup window (for example, the printer-friendly version of a document) after the user prints its contents, you can use code like this: <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>JavaScript Window Close Example </title> <script type="text/javascript"> function popuponclick
() { my_window = window.open('', 'mywindow', 'status=1,width=350,height=150'); my_window.document.write('<html><head><title>Print Me</title></head>'); my_window.document.write('<body onafterprint="self.close
()">'); my_window.document.write('<p>When you print this window, it will close afterward.</p>'); my_window.document.write('</body></html>'); } </script> </head> ...
...ow.document.write('<p>When you print this window, it will close afterward.</p>'); my_window.document.write('</body></html>'); } </script> </head> <body> <p>To try out the <code>afterprint</code> event, click the link below to open the window to print. You can also try changing the code to use <code>beforeprint</code> to see the difference.</p> <p><a href="javascript: popuponclick
()">Open Popup Window</a></p> </body> </html> View Live Examples Print an external page without opening it If you want to be able to print an external page without opening it, you can utilize a hidden <iframe> (see: HTMLIFrameElement), automatically removing it after the user prints its contents. The following is a possible example which will print a file named externalPage.html: <!doctype html...
...And 3 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
gin sharing standard can enable cross-site HTTP requests for: Invocations of the XMLHttpRequest or Fetch APIs, as discussed above. Web Fonts (for cross-domain font usage in @font-face within CSS), so that servers can deploy TrueType fonts that can only be cross-site loaded and used by web sites that are permitted to do so. WebGL textures. Images/video frames drawn to a canvas using drawImage
(). CSS Shapes from images. This article is a general discussion of Cross-Origin Resource Sharing and includes a discussion of the necessary HTTP headers. Functional overview The Cross-Origin Resource Sharing standard works by adding new HTTP headers that let servers describe which origins are permitted to read that information from a web browser. Additionally, for HTTP request methods that can...
...ple CORS Switch to a blacklist model for restricted Accept headers in simple CORS requests No other browsers implement these extra restrictions, because they're not part of the spec. For example, suppose web content at https://foo.example wishes to invoke content on domain https://bar.other. ...
...xtra restrictions, because they're not part of the spec. For example, suppose web content at https://foo.example wishes to invoke content on domain https://bar.other. ...
...And 3 more matches
The legacy Iterator protocol - JavaScript
terator protocol was a SpiderMonkey-specific feature, which is removed in Firefox 58+. For future-facing usages, consider using for..of loops and the iterator protocol. The deprecated Firefox-only iterator protocol Firefox, prior to version 26 implemented another iterator protocol that is similar to the standard ES2015 Iterator protocol. An object is an legacy iterator when it implements a next
() method with the following semantics, and throws StopIteration at the end of iteration. Property Value next A zero arguments function that returns an value. Difference between legacy and ES2015 iterator protocols The value was returned directly as a return value of calls to next, instead of the value property of a placeholder object Iteration termination was exp...
... an value. Difference between legacy and ES2015 iterator protocols The value was returned directly as a return value of calls to next, instead of the value property of a placeholder object Iteration termination was expressed by throwing a StopIteration object. ...
...xt, instead of the value property of a placeholder object Iteration termination was expressed by throwing a StopIteration object. ...
...And 3 more matches
TypeError: cyclic object value - JavaScript
The JavaScript exception "cyclic object value" occurs when object references were found in JSON. JSON.stringify
() doesn't try to solve them and fails accordingly. Message TypeError: cyclic object value (Firefox) TypeError: Converting circular structure to JSON (Chrome and Opera) TypeError: Circular reference in value argument not supported (Edge) Error type TypeError What went wrong? ...
...ringify
() doesn't try to solve them and fails accordingly. Message TypeError: cyclic object value (Firefox) TypeError: Converting circular structure to JSON (Chrome and Opera) TypeError: Circular reference in value argument not supported (Edge) Error type TypeError What went wrong? The JSON format per se doesn't support object references (although an IETF draft exists), hence JSON.stringify
() doesn't try to solve them and fails accordingly. Examples Circular references In a circular structure like the following var circularReference = {otherData: 123}; circularReference.myself = circularReference; JSON.stringify
() will fail JSON.stringify(circularReference); // TypeError: cyclic object value To serialize circular references you can use a library that supports them (e.g. cycle...
...r: cyclic object value To serialize circular references you can use a library that supports them (e.g. cycle.js) or implement a solution by yourself, which will require finding and replacing (or removing) the cyclic references by serializable values. ...
...And 3 more matches
TypeError: setting getter-only property "x" - JavaScript
operty for which only a getter is specified. While this will be silently ignored in non-strict mode, it will throw a TypeError in strict mode. Examples Property with no setter The example below shows how to set a getter for a property. It doesn't specify a setter, so a TypeError will be thrown upon trying to set the temperature property to 30. ...
...d. While this will be silently ignored in non-strict mode, it will throw a TypeError in strict mode. Examples Property with no setter The example below shows how to set a getter for a property. It doesn't specify a setter, so a TypeError will be thrown upon trying to set the temperature property to 30. For more details see also the Object.defineProperty
() page. ...
...mode. Examples Property with no setter The example below shows how to set a getter for a property. It doesn't specify a setter, so a TypeError will be thrown upon trying to set the temperature property to 30. For more details see also the Object.defineProperty
() page. ...
...And 3 more matches
RangeError: precision is out of range - JavaScript
The JavaScript exception "precision is out of range" occurs when a number that's outside of the range of 0 and 20 (or 21) was passed into toFixed or toPrecision. ...
...recision is out of range" occurs when a number that's outside of the range of 0 and 20 (or 21) was passed into toFixed or toPrecision. ...
...f 0 and 20 (or 21) was passed into toFixed or toPrecision. Message RangeError: The number of fractional digits is out of range (Edge) RangeError: The precision is out of range (Edge) RangeError: precision {0} out of range (Firefox) RangeError: toExponential
() argument must be between 0 and 20 (Chrome) RangeError: toFixed
() digits argument must be between 0 and 20 (Chrome) RangeError: toPrecision
() argument must be between 1 and 21 (Chrome) Error type RangeError What went wrong? There was an out of range precision argument in one of these methods: Number.prototype.toExponential
() Number.prototype.toFixed
() Number.prototype.toPrecision
() The allowed range for these methods is usually between 0 and 20 (or 21). However, the ECMAScript specification allows to extend this range. ...
...And 3 more matches
TypeError: 'x' is not iterable - JavaScript
function* generate(a, b) { yield a; yield b; } for (let x of generate) // TypeErr...
... function* generate(a, b) { yield a; yield b; } for (let x of generate) // TypeError: generate is not iterable console.log(x); When they are not called, the Function object correspon...
...untry, capital); Another option for this use case might be to use a Map: var map = new Map; map.set('France', 'Paris'); map.set('England', 'London'); // Iterate over the property names: for (let country of map.keys
()) { let capital = map[country]; console.log(country, capital); } for (let capital of map.values
()) console.log(capital); for (const [country, capital] of map.entries
()) console.log(country, capital); Iterating over a generator Generators are functions you call to produce an iterable object. function* generate(a, b) { yield a; yield b; } for (let x of generate) // TypeError: generate is not iterable console.log(x); When they are not called, the Function object corresponding to the generator is callable, but not iterable. Calling a generator pr...
...And 3 more matches
Error - JavaScript
ow for standard built-in error types. Description Runtime errors result in new Error objects being created and thrown. Error types Besides the generic Error constructor, there are seven other core error constructors in JavaScript. For client-side exceptions, see Exception handling statements. EvalError Creates an instance representing an error that occurs regarding the global function eval
(). InternalError Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion". RangeError Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range. ReferenceError Creates an instance representing an error that occurs when de-referencing an invalid refe...
...tside of its valid range. ReferenceError Creates an instance representing an error that occurs when de-referencing an invalid reference. SyntaxError Creates an instance representing a syntax error. TypeError Creates an instance representing an error that occurs when a variable or parameter is not of a valid type. URIError Creates an instance representing an error that occurs when encodeURI
() or decodeURI
() are passed invalid parameters. Constructor Error
() Creates a new Error object. Static methods Error.captureStackTrace
() A non-standard V8 function that creates the stack property on an Error instance. Instance properties Error.prototype.message Error message. Error.prototype.name Error name. Error.prototype.description A non-standard Microsoft property for the...
...path to the file that raised this error. Error.prototype.lineNumber A non-standard Mozilla property for the line number in the file that raised this error. Error.prototype.columnNumber A non-standard Mozilla property for the column number in the line that raised this error. Error.prototype.stack A non-standard Mozilla property for a stack trace. Instance methods Error.prototype.toString
() Returns a string representing the specified object. Overrides the Object.prototype.toString
() method. Examples Throwing a generic error Usually you create an Error object with the intention of raising it using the throw keyword. You can handle the error using the try...catch construct: try { throw new Error('Whoops!') } catch (e) { console.error(e.name + ': ' + e.message) } Handling a...
...And 3 more matches
Intl.Collator - JavaScript
The Intl.Collator objects enable language sensitive string comparison. 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. Constructor Intl.Collator
() Creates a new Collator object. ...
...tor objects enable language sensitive string comparison. 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. Constructor Intl.Collator
() Creates a new Collator object. ...
...or object. Static methods Intl.Collator.supportedLocalesOf
() Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. Instance methods Intl.Collator.prototype.compare Getter function that compares two strings according to the sort order of this Intl.Collator object. Intl.Collator.prototype.resolvedOptions
() Returns a new object with properties reflecting the locale and collation options computed during initialization of the object. ...
...And 3 more matches
Number - JavaScript
The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values, but there are some limits to what it can store. ...
...n When used as a function, Number(value) converts a string or other value to the Number type. If the value can't be converted, it returns NaN. Literal syntax 123 // one-hundred twenty-three 123.0 // same 123 === 123.0 // true Function syntax Number('123') // returns the number 123 Number('123') === 123 // true Number("unicorn") // NaN Number(undefined) // NaN Constructor Number
() Creates a new Number value. Static properties Number.EPSILON The smallest interval between two representable numbers. Number.MAX_SAFE_INTEGER The maximum safe integer in JavaScript (253 - 1). Number.MAX_VALUE The largest positive representable number. Number.MIN_SAFE_INTEGER The minimum safe integer in JavaScript (-(253 - 1)). Number.MIN_VALUE The smallest positive representable nu...
..., the positive number closest to zero (without actually being zero). Number.NaN Special "Not a Number" value. Number.NEGATIVE_INFINITY Special value representing negative infinity. Returned on overflow. Number.POSITIVE_INFINITY Special value representing infinity. Returned on overflow. Number.prototype Allows the addition of properties to the Number object. Static methods Number.isNaN
() Determine whether the passed value is NaN. Number.isFinite
() Determine whether the passed value is a finite number. Number.isInteger
() Determine whether the passed value is an integer. Number.isSafeInteger
() Determine whether the passed value is a safe integer (number between -(253 - 1) and 253 - 1). Number.parseFloat(string) This is the same as the global parseFloat
() function. Number.
...And 3 more matches
RegExp - JavaScript
For example, the following are equivalent: let re = /\w+/ let re = new RegExp('\\w+') Perl-like RegExp properties Note that several of the RegExp properties have both long and short (Perl-like) names. Both names always refer to the same value. (Perl is the programming language from which JavaScript modeled its regular expressions.). See also deprecated RegExp properties. Constructor RegExp
() Creates a new RegExp object. Static properties get RegExp[@@species] The constructor function that is used to create derived objects. RegExp.lastIndex The index at which to start the next match. Instance properties RegExp.prototype.flags A string that contains the flags of the RegExp object. RegExp.prototype.dotAll Whether . matches newlines or not. RegExp.prototype.global Whet...
...totype.ignoreCase Whether to ignore case while attempting a match in a string. RegExp.prototype.multiline Whether or not to search in strings across multiple lines. RegExp.prototype.source The text of the pattern. RegExp.prototype.sticky Whether or not the search is sticky. RegExp.prototype.unicode Whether or not Unicode features are enabled. ...
...totype.multiline Whether or not to search in strings across multiple lines. RegExp.prototype.source The text of the pattern. RegExp.prototype.sticky Whether or not the search is sticky. RegExp.prototype.unicode Whether or not Unicode features are enabled. Instance methods RegExp.prototype.compile
() (Re-)compiles a regular expression during execution of a script. RegExp.prototype.exec
() Executes a search for a match in its string parameter. ...
...And 3 more matches
WebAssembly.Module - JavaScript
A WebAssembly.Module object contains stateless WebAssembly code that has already been compiled by the browser -- this can be efficiently shared with Workers, and instantiated multiple times. Constructor WebAssembly.Module
() Creates a new Module object. Static properties WebAssembly.Module.customSections
() Given a Module and string, returns a copy of the contents of all custom sections in the module with the given string name. WebAssembly.Module.exports
() Given a Module, returns an array containing descriptions of all the declared exports. WebAssembly.Module.imports
() Given a Module, returns an array containing descriptions of all the declared imports. Examples Sending a compiled module to a worker The following example (see our index-compile.html demo on GitHub, and view...
... an array containing descriptions of all the declared exports. WebAssembly.Module.imports
() Given a Module, returns an array containing descriptions of all the declared imports. Examples Sending a compiled module to a worker The following example (see our index-compile.html demo on GitHub, and view it live also) compiles the loaded simple.wasm byte code using the WebAssembly.compileStreaming
() method and then sends the resulting Module instance to a worker using postMessage
(). var worker = new Worker("wasm_worker.js"); WebAssembly.compileStreaming(fetch('simple.wasm')) .then(mod => worker.postMessage(mod) ); In the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. When the module i...
...Message
(). var worker = new Worker("wasm_worker.js"); WebAssembly.compileStreaming(fetch('simple.wasm')) .then(mod => worker.postMessage(mod) ); In the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. When the module is received, we create an instance from it using the WebAssembly.instantiate
() method and invoke an exported function from inside it. ...
...And 3 more matches
WebAssembly.Table - JavaScript
The WebAssembly.Table
() object is a JavaScript wrapper object -- an array-like structure representing a WebAssembly Table, which stores function references. A table created by JavaScript or in WebAssembly code will be accessible and mutable from both JavaScript and WebAssembly. Note: Tables can currently only store function references, but this will likely be expanded in the future. Constructor WebAssembly.Table
() Creates a new Table object. Instance properties Table.prototype.length Returns the length of the table, i.e. the number of elements. Instance methods Table.prototype.get
() Accessor function -- gets the element stored at a given index. Table.prototype.grow
() Increases the size of the Table instance by a specified number of elements. ...
...tructor WebAssembly.Table
() Creates a new Table object. Instance properties Table.prototype.length Returns the length of the table, i.e. the number of elements. Instance methods Table.prototype.get
() Accessor function -- gets the element stored at a given index. Table.prototype.grow
() Increases the size of the Table instance by a specified number of elements. Table.prototype.set
() Sets an element stored at a given index to a given value. Examples Creating a new WebAssembly Table instance The following example (see table2.html source code and live version) creates a new WebAssembly Table instance with an initial size of 2 elements. ...
...er of elements. Table.prototype.set
() Sets an element stored at a given index to a given value. Examples Creating a new WebAssembly Table instance The following example (see table2.html source code and live version) creates a new WebAssembly Table instance with an initial size of 2 elements. We then print out the table length and contents of the two indexes (retrieved via Table.prototype.get
() to show that the length is two and both elements are null. var tbl = new WebAssembly.Table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" We then create an import object that contains the table: var importObj = { js: { tbl:tbl } }; Finally, we load and instantiate a wasm module (table2.wasm) usi...
...And 3 more matches
let - JavaScript
obally (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. In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function: function varTest
() { var x = 1; { var x = 2; // same variable! console.log(x); // 2 } console.log(x); // 2 } function letTest
() { let x = 1; { let x = 2; // different variable console.log(x); // 2 } console.log(x); // 1 } At the top level of programs and functions, let, unlike var, does not create a property on the global object. For example: var x = 'global'; let y = 'glob...
... functions, let, unlike var, does not create a property on the global object. ...
...te a property on the global object. ...
...And 3 more matches
Structural overview of progressive web apps - Progressive web apps (PWAs)
tor.serviceWorker.register("/pwa-examples/js13kpwa/sw.js"); } After that, the app adds a handler for clicks on a button whose ID is notifications; this handler requests permission to send notifications to the user, then generates and sends a random notification. ...
... adds a handler for clicks on a button whose ID is notifications; this handler requests permission to send notifications to the user, then generates and sends a random notification. ...
... ID is notifications; this handler requests permission to send notifications to the user, then generates and sends a random notification. ...
...And 3 more matches
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
JavaScript/XSLT Bindings JavaScript can run XSLT transformations through the XSLTProcessor object. Once instantiated, an XSLTProcessor has an XSLTProcessor.importStylesheet
() method that takes as an argument the XSLT stylesheet to be used in the transformation. The stylesheet has to be passed in as an XML document, which means that the .xsl file has to be loaded by the page before calling XSLTProcessor.importStylesheet
(). This can be done via XMLHttpRequest or XMLDocument.load
(). ...
...heet
() method that takes as an argument the XSLT stylesheet to be used in the transformation. The stylesheet has to be passed in as an XML document, which means that the .xsl file has to be loaded by the page before calling XSLTProcessor.importStylesheet
(). This can be done via XMLHttpRequest or XMLDocument.load
(). ...
... XML document, which means that the .xsl file has to be loaded by the page before calling XSLTProcessor.importStylesheet
(). This can be done via XMLHttpRequest or XMLDocument.load
(). Figure 1 : Instantiating an XSLTProcessor var xsltProcessor = new XSLTProcessor
(); // Load the xsl file using synchronous (third param is set to false) XMLHttpRequest var myXMLHTTPRequest = new XMLHttpRequest
(); myXMLHTTPRequest.open("GET", "example.xsl", false); myXMLHTTPRequest.send(null); var xslRef = myXMLHTTPRequest.responseXML; // Finally import the .xsl xsltProcessor.importStylesheet(xslRef); For the actual transformation, XSLTProcessor requires an XML document, which is used in conjunction with the imported XSL file to produce the final result. The XML document can be a separate XM...
...And 3 more matches
simple-storage - Archive of obsolete content
u may zero them each time the construction code runs. For example, this add-on tries to store the URLs of pages the user visits: var ss = require("sdk/simple-storage"); ss.storage.pages = []; require("sdk/tabs").on("ready", function(tab) { ss.storage.pages.push(tab.url); }); require("sdk/ui/button/action").ActionButton({ id: "read", label: "Read", icon: "./read.png", onClick: function
() { console.log(ss.storage.pages); } }); But this isn't going to work, because it empties the array each time the add-on runs (for example, each time Firefox is started). Line 2 needs to be made conditional, so the array is only constructed if it does not already exist: if (!ss.storage.pages) ss.storage.pages = []; Deleting data You can delete properties using the delete operator. Here'...
...onstructed if it does not already exist: if (!ss.storage.pages) ss.storage.pages = []; Deleting data You can delete properties using the delete operator. ...
...uttons to write, read, and delete a value: var ss = require("sdk/simple-storage"); require("sdk/ui/button/action").ActionButton({ id: "write", label: "Write", icon: "./write.png", onClick: function
() { ss.storage.value = 1; console.log("Setting value"); } }); require("sdk/ui/button/action").ActionButton({ id: "read", label: "Read", icon: "./read.png", onClick: function
() { console.log(ss.storage.value); } }); require("sdk/ui/button/action").ActionButton({ id: "delete", label: "Delete", icon: "./delete.png", onClick: function
() { delete ss.storage.value; console.log("Deleting value"); } }); If you run it, you'll see that after clicking "Read" after clicking "Delete" gives you the expected output: info: undefined Note that to run this a...
...And 2 more matches
content/worker - Archive of obsolete content
trait, therefore instances of Worker and their descendants expose all the public properties exposed by EventEmitter along with additional public properties that are listed below. Methods postMessage(data) Asynchronously emits "message" events in the enclosed worker, where content script was loaded. Parameters data : number,string,JSON The data to send. Must be stringifiable to JSON. destroy
() Destroy the worker by removing the content script from the page and removing all registered listeners. A detach event is fired just before removal. Properties port Object that allows you to: send customized messages to the worker using the port.emit function receive events from the worker using the port.on function url The URL of the content. tab If this worker is attached to a conte...
...at allows you to: send customized messages to the worker using the port.emit function receive events from the worker using the port.on function url The URL of the content. tab If this worker is attached to a content document, returns the related tab. Events message This event allows the content worker to receive messages from its associated content scripts. Calling the self.postMessage
() function from a content script will asynchronously emit the message event on the corresponding worker. Arguments value : The event listener is passed the message, which must be a JSON-serializable value. error This event allows the content worker to react to an uncaught runtime script error that occurs in one of the content scripts. Arguments Error : The event listener is passed a single ar...
... passed the message, which must be a JSON-serializable value. error This event allows the content worker to react to an uncaught runtime script error that occurs in one of the content scripts. Arguments Error : The event listener is passed a single argument which is an Error object. ...
...And 2 more matches
places/bookmarks - Archive of obsolete content
Create, modify, and retrieve bookmarks. Usage This module exports: three constructors: Bookmark, Group, and Separator, corresponding to the types of objects, referred to as bookmark items, in the Bookmarks database in Firefox two additional functions, save
() to create, update, and remove bookmark items, and search
() to retrieve the bookmark items that match a particular set of criteria. save
() and search
() are both asynchronous functions: they synchronously return a PlacesEmitter object, which then asynchronously emits events as the operation progresses and completes. Each retrieved bookmark item represents only a snapshot of state at a specific time. The module does not automatically sync up a Bookmark instance with ongoing changes to that item in the database from the same add-...
....on("end", function (saves, inputs) { // like the previous example, the "end" event returns an // array of all of our updated saves. Only explicitly saved // items are returned in this array -- the `group` won't be // present here. console.log(saves[0].title); // "Ran" console.log(saves[2].group.title); // "Guitars" }); Searching for bookmarks Bookmarks can be queried with the search
() function, which accepts a query object or an array of query objects, as well as a query options object. Query properties are AND'd together within a single query object, but are OR'd together across multiple query objects. let { search, UNSORTED } = require("sdk/places/bookmarks"); // Simple query with one object search( { query: "firefox" }, { sort: "title" } ).on("end", function (results)...
...me Type group Group The parent group that the bookmark group lives under. Defaults to the Bookmarks.UNSORTED group. index number The index of the bookmark group within its parent group. Last item within the group by default. Functions save(bookmarkItems, options) Creating, saving, and deleting bookmarks are all done with the save
() function. This function takes in any of: a bookmark item (Bookmark, Group, Separator) a duck-typed object (the relative properties for a bookmark item, in addition to a type property of 'bookmark', 'group', or 'separator') an array of bookmark items. All of the items passed in are pushed to the platform and are either created, updated or deleted. adding items: if passing in freshly inst...
...And 2 more matches
test/assert - Archive of obsolete content
by that function. ...
...we define two different custom exceptions: function MyError(message) { this.name = "MyError"; this.message = message || "Default Message"; } MyError.prototype = new Error
(); MyError.prototype.constructor = MyError; function AnotherError(message) { this.name = "AnotherError"; this.message = message || "Default Message"; console.log(this.message); } AnotherError.prototype = new Error
(); AnotherError.prototype.constructor = AnotherError; We can check the type of exception by passing a function as the Error argument: exports["test exception type 1 expected to pass"] = function(assert) { assert.throws(function
() { throw new MyError("custom message"); }, MyError, "test throwing a specific exception"); } exports["test exception type 2 expected to fail"] = function(ass...
...uctor = AnotherError; We can check the type of exception by passing a function as the Error argument: exports["test exception type 1 expected to pass"] = function(assert) { assert.throws(function
() { throw new MyError("custom message"); }, MyError, "test throwing a specific exception"); } exports["test exception type 2 expected to fail"] = function(assert) { assert.throws(function
() { throw new MyError("custom message"); }, AnotherError, "test throwing a specific exception"); } We can check the message by passing a regular expression: exports["test exception message 1 expected to pass"] = function(assert) { assert.throws(function
() { throw new MyError("custom message"); }, /custom message/, "test throwing a specific message"); } exports["test excepti...
...And 2 more matches
Add a Context Menu Item - Archive of obsolete content
efox context menu, use the context-menu module. Here's an add-on that adds a new context menu item. The item is displayed whenever something in the page is selected. When it's clicked, the selection is sent to the main add-on code, which just logs it: var contextMenu = require("sdk/context-menu"); var menuItem = contextMenu.Item({ label: "Log Selection", context: contextMenu.SelectionContext
(), contentScript: 'self.on("click", function
() {' + ' var text = window.getSelection
().toString
();' + ' self.postMessage(text);' + '});', onMessage: function (selectionText) { console.log(selectionText); } }); Try it: run the add-on, load a web page, select some text and right-click. You should see the new item appear: Click it, an...
...ed the item, it is automatically added in the correct context. The constructor in this case takes four options: label, context, contentScript, and onMessage. label The label is just the string that's displayed. context The context describes the circumstances in which the item should be shown. The context-menu module provides a number of simple built-in contexts, including this SelectionContext
(), which means: display the item when something on the page is selected. If these simple contexts aren't enough, you can define more sophisticated contexts using scripts. contentScript This attaches a script to the item. In this case the script listens for the user to click on the item, then sends a message to the add-on containing the selected text. onMessage The onMessage property provides a...
...ent fires, and the add-on code's handler function is passed the selected text, which it logs More options Adding an image You can add an image to a context menu item with the image option. This is a URL pointing to a 16x16 icon that's displayed at the left side of the context menu item. ...
...And 2 more matches
Delayed Execution - Archive of obsolete content
Note: If an nsITimer is garbage collected, it will be deactivated and its callbacks will not fire. A reference to the timer objects must be explicitly kept alive until that point. Some example usages include: const Timer = Components.Constructor("@mozilla.org/timer;1", "nsITimer",...
... Note: If an nsITimer is garbage collected, it will be deactivated and its callbacks will not fire. A reference to the timer objects must be explicitly kept alive until that point. Some example usages include: const Timer = Components.Constructor("@mozilla.org/timer;1", "nsITimer", "initWithCallback...
...g nsITimer instances. Note: If an nsITimer is garbage collected, it will be deactivated and its callbacks will not fire. A reference to the timer objects must be explicitly kept alive until that point. ...
...And 2 more matches
Installing Extensions and Themes From Web Pages - Archive of obsolete content
es the best experience to users. Web Script Example <script type="application/javascript"> <!-- function install (aEvent) { for (var a = aEvent.target; a.href === undefined;) a = a.parentNode; var params = { "Foo": { URL: aEvent.target.href, IconURL: aEvent.target.getAttribute("iconURL"), Hash: aEvent.target.getAttribute("hash"), toString: function
() { return this.URL; } } }; InstallTrigger.install(params); return false; } //--> </script> <a href="http://www.example.com/foo.xpi" iconURL="http://www.example.com/foo.png" hash="sha1:28857e60d043447c5f4550853f2d40770b326a13" onclick="return install(event);">Install Extension!</a> Let's go through this piece by piece. The HTML <a> is the install link. The href attribute contain...
...by right clicking on the link and choosing "Save Link As..." When the link is clicked it calls the function install passing the event object as the parameter. The install first creates a parameter block: var params = { "Foo": { URL: aEvent.target.href, IconURL: aEvent.target.getAttribute("iconURL"), Hash: aEvent.target.getAttribute("hash"), toString: function
() { return this.URL; } }; This specifies the display name (Foo) for use in the confirmation dialog, the URL to the extension (which is the link href, recall), the Icon URL to display in the confirmation dialog, a hash of the xpi file contents (to protect against corrupted downloads), and a toString function which will allow this code to work with versions of Firefox 0.8 and earlier. You could als...
...ize. Hash The Hash property specifies a cryptographic hash of the XPI file contents. This is used to verify the downloaded file, to protect against a corrupted file being served by a mirror download server, for example. You can use any hash function supported by nsICryptoHash. The hash is specified as hash function:hash value, for example, sha1:28857e60d043447c5f4550853f2d40770b326a13. toString
() The toString
() property should return the XPI URL, for compatibility with Firefox browsers older than version 1.0, and other applications such as Seamonkey. Themes Pretty much everything I've described applies to themes too, except you'll use the installChrome function. Because so many sites installed extensions by direct-linking the XPI file and relying on content handling to invoke the confi...
...And 2 more matches
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
apter, save them as text files with .xul extensions and drag and drop them into the Firefox browser window. FIXME: Explain how setting this option and use next listings If we want to run Firefox displaying none of its GUI and only the contents of a certain XUL file, we can launch Firefox and set the option: -chrome file_URL.xul Another way, as shown in Listing 1, is to use the window.openDialog
() method, which can be used only within a XUL window. This is used by extensions to open a separate window. window.openDialog('another.xul', '_blank','chrome,all,dialog=no'); Listing 1: Opening a window without the Firefox GUI XUL as an XML application Listing 2 shows an example of a GUI definition file marked up in XUL (a "XUL document"). The root element in XUL is generally the "window" elem...
...ed, pressing either the accept button or cancel button will simply close that dialog. Listing 8 shows a simple dialog example, and Figure 5 shows its output. <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="chrome://global/skin/"?> <dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" title="My Dialog" buttons="accept,cancel" ondialogaccept="saveValues
(); window.close
();" ondialogcancel="window.close
();"> <checkbox label="My Option"/> </dialog> Listing 8: A dialog Figure 5: Output from Listing 8 Note: The functions behind the dialog elements discussed here require "XPConnect privileges," which are discussed in Chapter 4, so this example will only run correctly if it can run as Firefox code itself or installed extension code. Please be...
...u element. Instead, the menupopup element is a direct child of the root element and we invoke it using its id attribute, which we set as the value for the context attribute on any other XUL element. When we right-click on that XUL element, we reference that menupopup element by its id, and display its contents as a contextual menu. Listing 12 shows an example. <button label="Send" oncommand="send
();" context="button-context"/> <menupopup id="button-context"> <menuitem label="Send with new tab" oncommand="sendInNewTab
();"/> </menupopup> Buttons Buttons that users can click on are defined using the button element. To show one with an icon as shown in Figure 8, define an image's URI as the value for the image attribute. Note: To see this sample in operation, use any image as the one to d...
...And 2 more matches
Observer Notifications - Archive of obsolete content
You could do that by calling all those functions directly, but XPCOM offers you a better and cleaner way to achieve that using observers and the observer service. An observer is an object that is responsible to observe (wait for) notifications and then to carry out subsequent actions. To create an observer, you need to implement the nsIObserver interface. The interface has only one method observe
() which takes three parameters. The first parameter (subject) can be any XPCOM object, the second parameter is a notification topic, and the final parameter is a string that further describes the notification. This example code shows you what an implementation of the nsIObserver interface looks like: let testObserver = { observe : function(aSubject, aTopic, aData) { if (aTopic == "xulscho...
... and non-chrome objects are not, it's tricky to send a message to the chrome. You would have to invoke a method for the chrome objects in all windows. It's much easier to use observers in this case. Let's see the following example code on how to send out a notification from non-chrome code. /** * Notifies all the registered observers with the test notification topic. */ notifyTest : function
() { let observerService = Components.classes["@mozilla.org/observer-service;1"]. getService(Components.interfaces.nsIObserverService); let subject = Components.classes["@mozilla.org/supports-string;1"]. createInstance(Components.interfaces.nsISupportsString); // assign some text to data attribute subject.data = "This is a test."; // notify all registered observers observerS...
...to remove observers that are not longer needed. Not doing so will result in memory leaks. Therefore, the registered observer is unregistered when the browser window is unloaded. /** * Controls the browser overlay for the Hello World extension. */ XULSchoolChrome.BrowserOverlay = { /* Observer service. */ _observerService : null, /** * Initializes this object. ...
...And 2 more matches
XPCOM Objects - Archive of obsolete content
parameter is an input that tells the method where to start looking. The second one will hold the length of the return array, and the third parameter will hold the array itself. Note the metadata included in the square brackets, indicating that the parameter is an array, and that its size is determined by the aCount parameter. Here's one way to invoke this method: let childArrayObj = new Object
(); let childArray; this._prefService.getChildList("", {}, childArrayObj); // .value holds the actual array. childArray = childArrayObj.value; The general rule for out parameters is that you can pass an empty object, and then you can get the result by accessing the value attribute in this object after the method call. The method will set value for you. Also, since JS arrays have the length attr...
...2 is an example of this. void addObserver(in string aDomain, in nsIObserver aObserver, in boolean aHoldWeak); Luckily, you don't have to do anything special if you want to register your JS object as a preference observer. The nsIObserver has a single method observe, so all you need to do is have an observe method in your object and you'll be OK. XULSchool.PrefObserver = { init: function
() { this._prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch2); // pass 'this' as if it implemented nsIObserver. this._prefService.addObserver( "extensions.xulschoolhello.somePref", this, false); }, observe : function(aSubject, aTopic, aData) { // do stuff here. } }; Finally, here's a table summarizing the types you will most li...
... short, long, unsigned long, PRInt32, PRUInt32 PRInt32 is the equivalent to long. Most PR* types have an easier to read equivalent, so it is better to use those. Floating point float Boolean boolean, PRBool Void void Timestamps PRTime This type is used to pass timestamps measured in milliseconds, such as the output of the getTime
() method in a Javascript Date object. There are more details about XPIDL in the XPDIL Syntax definition. Creating Your Own Components JavaScript XPCOM Components As we've said before, we recommend using JSM whenever you can. Yet there are some cases where you don't have a choice and you have to create XPCOM components to add a specific feature. In these cases you can choose between compil...
...And 2 more matches
Creating a Web based tone generator - Archive of obsolete content
This example creates a simple tone generator, and plays the resulting tone. The function requestSoundData
() produces the samples to be played. This function is called at a certain interval through the setInterval
() function. The function mozWriteAudio
() is called to write those samples produced in the audio stream. In order to always have samples to play, a buffer of 500 ms is created. The function mozCurrentSampleOffset
() is used to know the position of the samples being played so that we can fill a 500 ms buffer of audio samples. ...
... to play, a buffer of 500 ms is created. The function mozCurrentSampleOffset
() is used to know the position of the samples being played so that we can fill a 500 ms buffer of audio samples. <!DOCTYPE html> <html> <head> <title>JavaScript Audio Write Example</title> </head> <body> <input type="text" size="4" id="freq" value="440"><label for="hz">Hz</label> <button onclick="start
()">play</button> <button onclick="stop
()">stop</button> <script type="text/javascript"> function AudioDataDestination(sampleRate, readFn) { // Initialize the audio output. ...
... <title>JavaScript Audio Write Example</title> </head> <body> <input type="text" size="4" id="freq" value="440"><label for="hz">Hz</label> <button onclick="start
()">play</button> <button onclick="stop
()">stop</button> <script type="text/javascript"> function AudioDataDestination(sampleRate, readFn) { // Initialize the audio output. var audio = new Audio
(); audio.mozSetup(1, sampleRate); var currentWritePosition = 0; var prebufferSize = sampleRate / 2; // buffer 500ms var tail = null; // The function called with regular interval to populate // the audio output buffer. setInterval(function
() { var written; // Check if some data was not written in previous attempts. ...
...And 2 more matches
Using XML Data Islands in Mozilla - Archive of obsolete content
Here is a complete demo (also available as an attachment): <!DOCTYPE html> <html> <head> <title>XML Data Block Demo</title> <script id="purchase-order" type="appli...
...t): <!DOCTYPE html> <html> <head> <title>XML Data Block Demo</title> <script id="purchase-order" type="application/xml"> <purchaseOrder xmlns="http://example.mozilla.org/PurchaseOrderML"> <lineItem> <name>Line Item 1</name> <price>1.25</price> </lineItem> <lineItem> <name>Line Item 2</name> <price>2.48</price> </lineItem> </purchaseOrder> </script> <script> function runDemo
() { var orderSource = document.getElementById("purchase-order").textContent; var parser = new DOMParser
(); var doc = parser.parseFromString(orderSource, "application/xml"); var lineItems = doc.getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "lineItem"); var firstPrice = lineItems[0].getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "price")[0].textC...
...ElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "lineItem"); var firstPrice = lineItems[0].getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "price")[0].textContent; document.body.textContent = "The purchase order contains " + lineItems.length + " line items. The price of the first line item is " + firstPrice + "."; } </script> </head> <body onload="runDemo
()";> Demo did not run </body> </html> The XML source text can be parsed into a DOM tree using the DOMParser API: var parser = new DOMParser
(); var doc = parser.parseFromString(orderSource, "application/xml"); The HTML5 data block-based way shown here works in Firefox, Opera, WebKit-based browsers such as Chrome and Safari, and IE9 while IE's XML data islands work only in IE. Here is another possib...
...And 2 more matches
XML in Mozilla - Archive of obsolete content
Documentation XHTML W3C Recommendation XML Base W3C Recommendation XLink (simple XLinks only) Obsolete since Gecko 2.0 W3C Recommendation FIXptr Obsolete since Gecko 1.9.1 W3C "proposal" XPointer Framework Obsolete since Gecko 1.9.1 W3C Recommendation XPointer element
() scheme Obsolete since Gecko 1.9.1 W3C Recommendation XPointer xmlns
() scheme Obsolete since Gecko 1.9.1 W3C Recommendation XPointer fixptr
() scheme Obsolete since Gecko 1.9.1 This scheme is simply a wrapper for FIXptr XPointer xpath1
() scheme Obsolete since Gecko 1.9.1 Internet-Draft document.load
(), document.
...ng into resources in XML documents Mozilla also supports FIXptr, a simplified, non-compatible version of XPointer. In addition to using FIXptr in links, it is possible to use it from scripts. See the proprietary dom/interfaces/core/nsIDOMXMLDocument.idl interface. There is test case for FIXptr links and a scripting example. Since 1.4alpha, Mozilla also supports XPointer Framework, XPointer element
() scheme, XPointer xmlns
() scheme, XPointer fixptr
() scheme and XPointer xpath1
() scheme. The XPointer processor is extensible and it is easy to implement support for other schemes - have a look at the API. The xpath1
() scheme was implemented using this extensible mechanism. There is also a proprietary API from scripts to the XPointer processor. There is a testcase for XPointers that you can also s...
...XPointer processor. There is a testcase for XPointers that you can also study. Lastly, there is a pref you might want to try (especially useful with FIXptr) that will select the link target when you traverse it. There is no UI for setting this pref yet, so you will need to manually edit the preferences file. Add this line: pref("layout.selectanchor", true); DOM Load and Save Methods document.load
() is a part of an old version of the W3C DOM Level 3 Load & Save module. Mozilla currently implements only the load
() method and the document.async property. Outside Supported XML W3C Recommendations Specification or Technology Documentation Mozilla Project XSLT W3C Recommendation XSLT XPath W3C Recommendation XSLT ...
...And 2 more matches
Getting File Information - Archive of obsolete content
tes fileSize and lastModifiedTime (nsIFile.Attributes) provide a means of retrieving the size of a file and the time when the file was last changed. File Size The fileSize (nsIFile.Attributes) attribute holds the size of a file in bytes. If the file does not exist, a 'file not found' exception will occur. ...
...This may be useful to truncate a file, however, setting the file size will also increase the size of a file if the value is larger than the current size of the file. ...
...s created using the modification time of a file. You can change the modification time of a file by setting the lastModifiedTime (nsIFile.Attributes) attribute, or you can just write to the file, in which case the value will be adjusted automatically. File Permissions Several methods may be used to check for file permissions. ...
...And 2 more matches
PopupEvents - Archive of obsolete content
d to or modify the menu as needed before it is displayed. For examples of the use of the popupshowing event when used with context menus, see Hiding and Showing Menu Items based on Context. However, this technique can be applied to any type of popup. In this example, a label within a panel is initialized with the current time. <panel id="time-panel" onpopupshowing="this.lastChild.value = (new Date
()).toLocaleFormat('%T')"> <label value="Time:"/> <label id="time"/> </panel> <toolbarbutton label="Show Time" popup="time-panel"/> You can prevent a menu or popup from appearing by calling the preventDefault method of the event from within a popupshowing listener. The default operation of the popupshowing event is to continue showing the popup. The preventDefault method will stop this from h...
...el"/> You can prevent a menu or popup from appearing by calling the preventDefault method of the event from within a popupshowing listener. The default operation of the popupshowing event is to continue showing the popup. The preventDefault method will stop this from happening and the popup will not be opened. <menu label="Edit"> <menupopup onpopupshowing="if (gDisallowed) event.preventDefault
();"> <menuitem label="Undo"/> <menuitem label="Redo"/> </menupopup> </menu> In this example, a global variable gDisallowed is checked and the preventDefault method is called. If you want to prevent a context menu from opening it is better to call preventDefault with a handler for the contextmenu event instead, to avoid the extra steps necessary to fire the popupshowing event if it isn't ...
...hat method returns. The popupshown event will be fired when the UI is updated and the popup is visible. One possible use of the popupshown event is to open another menu. This technique, as shown in the following example, is needed if you wish to open a submenu programmatically. This is because you cannot open a submenu directly without first opening the parent menu. ...
...And 2 more matches
Tree Widget Changes - Archive of obsolete content
property. From there you can get specific columns, the current sort column, and position and size info about the columns. For the most part these objects are readonly; you can modify the columns by just adjusting the treecol attributes directly. The tree and view methods no longer take ids as arguments when columns are used. Instead, they use nsITreeColumns. For example, nsITreeView.getCellValue
() takes a row index and a nsITreeColumn as arguments, whereas before it took a row index and a column id. To get a column in JavaScript: tree.columns.getColumnFor(treeColElement); tree.columns.getNamedColumn(treeColID); tree.columns.getColumnAt(index); You can also just use array syntax to get a column: tree.columns["lastName"]; tree.columns[5]; Once you have a column, you can get various pr...
...ou can also get the atom attribute of nsITreeColumn which returns an nsIAtom for the column, making it fast to do comparisons. nsCOMPtr<nsIAtom> atom; aCol->GetAtom(getter_AddRefs(atom)); if (atom = kMyCol) ... One feature that has been added is restoreNaturalOrder which may be used to restore the original order of the columns before the user moved them around. tree.columns.restoreNaturalOrder
() There is also a command on the end of the tree's column picker which the user may use to restore the original column order. This will be hidden if the column redordering is disabled using enableColumnDrag="false". Some specific changes You should now get the tree selection object from the view, not the box object, meaning use tree.view.selection instead of tree.treeBoxObject.selection. Use t...
...den if the column redordering is disabled using enableColumnDrag="false". Some specific changes You should now get the tree selection object from the view, not the box object, meaning use tree.view.selection instead of tree.treeBoxObject.selection. Use tree.columns[1].id instead of tree.treeBoxObject.getColumnID(1) to get the id of a column, in this case column 1. Use tree.columns.getKeyColumn
().index instead of tree.treeBoxObject.getKeyColumnIndex
(). The nsITreeBoxObject.getPageCount
() method has been renamed to make it clearer what it does. It returns the number of rows that can be displayed in the tree. This should correspond to the rows attribute on the tree if it was specified. tree.treeBoxObject.getPageCount
() is now tree.treeBoxObject.getPageLength
(). The invalidatePrimaryCell(...
...And 2 more matches
Creating an Installer - Archive of obsolete content
process is started by an install trigger. This involves the use of the special global object InstallTrigger. It contains a number of methods which can be used to start an installation. You can use this object in local or remote content, meaning that it is suitable for a download from a Web site. Let's create an example install trigger. This involves the use of the function InstallTrigger.install
(). ...
...You can name the function whatever you like of course. This function has two arguments. The first is the name of the package that was just installed. ...
...You can name the function whatever you like of course. ...
...And 2 more matches
Localization - Archive of obsolete content
shown below with the changes shown in red. ...
... <menuitem label="&pasteCmd.label;" accesskey="&pasteCmd.accesskey;" disabled="true"/> </menupopup> </popupset> <keyset> <key id="cut_cmd" modifiers="accel" key="&cutCmd.commandkey;"/> <key id="copy_cmd" modifiers="accel" key="©Cmd.commandkey;"/> <key id="paste_cmd" modifiers="accel" key="&pasteCmd.commandkey;"/> <key id="close_cmd" keycode="VK_ESCAPE" oncommand="window.close
();"/> </keyset> <vbox flex="1"> <toolbox> <menubar id="findfiles-menubar"> <menu id="file-menu" label="&fileMenu.label;" accesskey="&fileMenu.accesskey;"> <menupopup id="file-popup"> <menuitem label="&openCmd.label;" accesskey="&openCmd.accesskey;"/> <menuitem label="&saveCmd.label;" accesskey="&saveCmd.accesskey;"/> ...
...leMenu.accesskey;"> <menupopup id="file-popup"> <menuitem label="&openCmd.label;" accesskey="&openCmd.accesskey;"/> <menuitem label="&saveCmd.label;" accesskey="&saveCmd.accesskey;"/> <menuseparator/> <menuitem label="&closeCmd.label;" accesskey="&closeCmd.accesskey;" key="close_cmd" oncommand="window.close
();"/> </menupopup> </menu> <menu id="edit-menu" label="&editMenu.label;" accesskey="&editMenu.accesskey;"> <menupopup id="edit-popup"> <menuitem label="&cutCmd.label;" accesskey="&cutCmd.accesskey;" key="cut_cmd"/> <menuitem label="©Cmd.label;" accesskey="©Cmd.accesskey;" key="copy_cmd"/> <menuitem lab...
...And 2 more matches
More Wizards - Archive of obsolete content
ar depending on what the user selects in earlier pages. In this case, place a pageid attribute on each of the pages. This should be set to an identifier for each page. Then, to navigate to a page, use one of two methods: Set the next attribute on each page to the page ID of the next page to go to. You can change these attributes as needed to navigate to different pages. Call the wizard's goTo
() method. It takes one argument, the page ID of a page to go to. You might call this method in the onpageadvanced or onwizardnext handlers. Remember to return false in this case, because you have already changed the page yourself. Note that the goTo
() method, because it causes a page change, will fire the events again, so you'll have to make sure you handle that case. For example, here are a set o...
...until valid input has been entered. The wizard has a property canAdvance, which can be set to true to indicate that the Next button should be enabled. If set to false, the Next button is disabled. You can change the property when invalid or valid data has been entered. In the following example, the user must enter a secret code into a textbox on the first page of the wizard. The function checkCode
() is called whenever the first page is shown as indicated by the onpageshow attribute. It is also called whenever a key is pressed in the textbox, to determine whether the Next button should be enabled again. Wizard example Source <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <wizard id="theWizard" title="Secret Code Wizard" xmlns="http://www.mozilla.org...
...show attribute. It is also called whenever a key is pressed in the textbox, to determine whether the Next button should be enabled again. ...
...And 2 more matches
Dialogs in XULRunner - Archive of obsolete content
dialog element to act as the container for the dialog. Dialog XUL files can have DTD, CSS, and JavaScript, just like windows. ...
... dialog: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <dialog id="myDialog" title="My Dialog" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="window.sizeToContent
();" buttons="accept,cancel" buttonlabelaccept="Set Favorite" buttonaccesskeyaccept="S" ondialogaccept="return doSave
();" buttonlabelcancel="Cancel" buttonaccesskeycancel="n" ondialogcancel="return doCancel
();"> <script> function doSave
(){ //doSomething
() return true; } function doCancel
(){ return true; } </script> <dialogheader title="My dialog" description="Example dialog"/> <groupbox flex="1"> <caption label="Select favorite fruit"/> <ra...
...flex="1"> <caption label="Select favorite fruit"/> <radiogroup> <radio id="1" label="Oranges because they are fruity"/> <radio id="2" selected="true" label="Strawberries because of color"/> <radio id="3" label="Bananna because it pre packaged"/> </radiogroup> </groupbox> </dialog> XUL window elements have a special method to open dialogs, called window.openDialog
(). Here is the code needed to open a dialog: function openDialog
() { window.openDialog("chrome://basicapp/content/dialog.xul", "newdlg", "modal"); } The resulting dialog looks like this on Windows 2000, and will look similar on other operating systems: The first thing that caught my eye about dialog is the button-related attributes on the element. In an effort to make things easier for deve...
...And 2 more matches
NPClass - Archive of obsolete content
tructFunctionPtr construct; }; Warning: Don't call these routines directly. You should instead use the appropriate API functions. Fields structVersion The version number of the structure. This is set to NP_CLASS_STRUCT_VERSION, which is 1 in Mozilla 1.8.*, 2 since Mozilla 1.9a1, and 3 since Firefox 3.0b1. allocate Returns a pointer to a newly allocated NPObject. Called by NPN_CreateObject
() if non-NULL, otherwise the browser calls malloc
(). This function is expected to allocate and return enough storage to hold the NPObject that is being created. deallocate Called by NPN_ReleaseObject
() when an object's reference count reaches zero. If this field is NULL, free
() is called isntead. invalidate Called on live objects that belong to a plugin instance that is being destroyed. This ca...
...s expected to allocate and return enough storage to hold the NPObject that is being created. deallocate Called by NPN_ReleaseObject
() when an object's reference count reaches zero. If this field is NULL, free
() is called isntead. invalidate Called on live objects that belong to a plugin instance that is being destroyed. This call is always followed by a call to the deallocate function, or free
(). Any attempt to use an invalidated object will result in undefined behavior. hasMethod Called by NPN_HasMethod
() to determine whether or not a specified method exists on a given NPObject. Returns true if the method exists, otherwise returns false. invoke Called by NPN_Invoke
() to invoke a specific method on a given NPObject. Returns true if invocation succeeded or false if an error occurred. ...
...will result in undefined behavior. hasMethod Called by NPN_HasMethod
() to determine whether or not a specified method exists on a given NPObject. Returns true if the method exists, otherwise returns false. invoke Called by NPN_Invoke
() to invoke a specific method on a given NPObject. Returns true if invocation succeeded or false if an error occurred. invokeDefault Called by NPN_InvokeDefault
() to invoke the default method (if available) on a given NPObject. Returns true if invocation succeeded or false if an error occurred. hasProperty Called by NPN_HasProperty
() to check whether a given property exists on a given NPObject. Returns true if the specified property exists, otherwise returns false. ...
...And 2 more matches
NPN_MemFlush - Archive of obsolete content
ecified amount of memory. Syntax #include <npapi.h> uint32 NPN_MemFlush(uint32 size); Parameters The function has the following parameters: size Size of memory, in bytes, to free in the browser's memory space. Returns If successful, the function returns the amount of freed memory, in bytes. If no memory can be freed, the browser returns 0. ...
...i.h> uint32 NPN_MemFlush(uint32 size); Parameters The function has the following parameters: size Size of memory, in bytes, to free in the browser's memory space. Returns If successful, the function returns the amount of freed memory, in bytes. If no memory can be freed, the browser returns 0. ...
...wser's memory space. Returns If successful, the function returns the amount of freed memory, in bytes. If no memory can be freed, the browser returns 0. Description The plug-in calls NPN_MemFlush
() when it is not possible to call NPN_MemAlloc
(), for example, when calling system APIs that indirectly allocate memory. To request that the browser free as much memory as possible, call NPN_MemFlush
() repeatedly until it returns 0. On the Mac, you can use this method to free memory before calling memory-intensive system calls. ...
...And 2 more matches
Displaying notifications (deprecated) - Archive of obsolete content
xt of the web content, using the standard notification system provided by the operating system. For example, on Android, notifications appear in the bar at the top of the screen, and in the panel that appears when you drag that bar downward. Creating a notification The first thing you need to do is create the notification object by using the navigator.mozNotification object's createNotification
() method, as follows: var notification = navigator.mozNotification.createNotification( "Hey, check this out!", "This is a notification posted by " + "Firefox 4. You should take some action. Right now!"); This returns a new notification object, but does not actually display the notification. This lets you configure the event listeners before the notification is shown, if you need ...
...s event is fired when the user clicks (or taps) on the notification. onclose This event is fired when the notification is closed (whether by being clicked or by some other means). Note: If the notification is dismissed by the user clicking on it, both events will get fired. ...
...ans). Note: If the notification is dismissed by the user clicking on it, both events will get fired. ...
...And 2 more matches
The global XML object - Archive of obsolete content
XML.prototype and XMLList.prototype (XMLList.prototype is actually just XML.prototype) cannot be extended in the same conventional way as other constructors such as Object. You can only define methods in XML.prototype and not fields. To add a method to XML.prototype, define XML.prototype.function::methodName or XML.prototype.function::[methodNameString]. The following example defines the fooCount
() method, which returns the amount of <foo> elements in the XML: XML.prototype.function::fooCount = function fooCount
() { return this..foo.length
(); }; <foobar><foo/><foo/><foo/></foobar>.fooCount
() // returns 3 ignoreComments true by default. This property tells E4X to ignore comment nodes when serializing and filtering. This means that if ignoreComments is true, the list returned by .comments...
... method, which returns the amount of <foo> elements in the XML: XML.prototype.function::fooCount = function fooCount
() { return this..foo.length
(); }; <foobar><foo/><foo/><foo/></foobar>.fooCount
() // returns 3 ignoreComments true by default. This property tells E4X to ignore comment nodes when serializing and filtering. This means that if ignoreComments is true, the list returned by .comments
() will be empty. ...
...th
(); }; <foobar><foo/><foo/><foo/></foobar>.fooCount
() // returns 3 ignoreComments true by default. This property tells E4X to ignore comment nodes when serializing and filtering. This means that if ignoreComments is true, the list returned by .comments
() will be empty. Observe: var element = <foo> <!-- my comment --> <bar/> </foo>; element.comments
().length
(); // returns 0 element.toXMLString
(); // returns <foo><bar/></foo> XML.ignoreComments = false; element = <foo> <!-- my comment --> <bar/> </foo>; element.comments
().length
(); // returns 1 element.toXMLString
(); // returns <foo><!-- my comment --><bar/></foo> ignoreProcessingInstructions true by default. This property tells E4X to ignore processing inst...
...And 2 more matches
Using JavaScript Generators in Firefox - Archive of obsolete content
t> Then your myScript.js file might look like this: // Need to stash the generator in a global variable. var generator; // Simple event listener function to pass the received event to the generator. function grabEvent(event) { generator.send(event); } // When we're all done we can close the generator, but that must happen outside // of the generator so we use a timeout. ...
...ile might look like this: // Need to stash the generator in a global variable. var generator; // Simple event listener function to pass the received event to the generator. function grabEvent(event) { generator.send(event); } // When we're all done we can close the generator, but that must happen outside // of the generator so we use a timeout. ...
...: // Need to stash the generator in a global variable. var generator; // Simple event listener function to pass the received event to the generator. function grabEvent(event) { generator.send(event); } // When we're all done we can close the generator, but that must happen outside // of the generator so we use a timeout. ...
...And 2 more matches
Iterator - Archive of obsolete content
Properties Iterator.prototype[@@iterator] Returns a function that returns iterator object. Methods Iterator.prototype.next Returns next item in the [property_name, property_value] format or property_name only. It throws StopIteration if there are no more items. ...
...ator] Returns a function that returns iterator object. Methods Iterator.prototype.next Returns next item in the [property_name, property_value] format or property_name only. It throws StopIteration if there are no more items. ...
...iterator object. Methods Iterator.prototype.next Returns next item in the [property_name, property_value] format or property_name only. It throws StopIteration if there are no more items. ...
...And 2 more matches
Enumerator.moveNext - Archive of obsolete content
s the current item to the next item in the collection. Syntax enumObj.moveNext( ) Remarks The required enumObj reference is any Enumerator object. If the enumerator is at the end of the collection or the collection is empty, the current item is set to undefined. ...
...d of the collection or the collection is empty, the current item is set to undefined. ...
... the collection is empty, the current item is set to undefined. ...
...And 2 more matches
Object.prototype.__noSuchMethod__ - Archive of obsolete content
If this method cannot be called, either as if undefined by default, if deleted, or if manually set to a non-function, the JavaScript engine will revert to throwing TypeErrors. Examples Simple test of __noSuchMethod__ var o = { __noSuchMethod__: function(id, args) { console.log(id, '(' + args.join(', ') + ')'); } }; o.foo(1, 2, 3); o.bar(4, 5); o.baz
(); // Output // foo (1, 2, 3) // bar (4, 5) // baz
() Using __noSuchMethod__ to simulate multiple inheritance An example of code that implements a primitive form of multiple inheritance is shown below. // Doesn't work with multiple inheritance objects as parents function noMethod(name, args) { var parents = this.__parents_; // Go through all parents for (var i = 0; i < parents.length; i...
... function addParent(obj, parent) { // If the object isn't initialized, initialize it if (!obj.__parents_) { obj.__parents_ = []; obj.__noSuchMethod__ = noMethod; } // Add the parent obj.__parents_.push(parent); } An example of using this idea is shown below. // Example base class 1 function NamedThing(name) { this.name = name; } NamedThing.prototype = { getName: function
() { return this.name; }, setName: function(newName) { this.name = newName; } } // Example base class 2 function AgedThing(age) { this.age = age; } AgedThing.prototype = { getAge: function
() { return this.age; }, setAge: function(age) { this.age = age; } } // Child class. inherits from NamedThing and AgedThing // as well as defining address function Person(name, age, address){ addParent...
...return this.age; }, setAge: function(age) { this.age = age; } } // Child class. ...
...And 2 more matches
Popup Window Controls - Archive of obsolete content
s for your site and how to get the benefits of popup windows without using popup windows. ...
... Detecting Suppressed Popups Windows If a user has popup controls enabled for your site, any attempt to call window.open in global ...
... Detecting Suppressed Popups Windows If a user has popup controls enabled for your site, any attempt to call window.open in global script, in an onl...
...And 2 more matches
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
e example 2). Two new cases for the above mentioned new variables should be added to the plugin implementation of NPP_GetValue (see example 3). How to call plugin native methods The following HTML code will do the job:</p> This should be changed, we shouldn't advocate EMBED <embed type="application/plugin-mimetype"> <script language="javascript"> var embed = document.embeds[0]; embed.nativeMethod
(); </script> How to build and install Having the built Mozilla tree is probably not necessary, but building the plugin with a scriptable instance interface will require Mozilla headers and the XPCOM compatible idl compiler -- xpidl.exe. MS DevStudio MIDL must not be used. (Let's assume 'TestPlugin' as a plugin name-place holder.) Compile nsITestPlugin.idl with the idl compiler. This will generate...
...l to the Plugins folder. Related sources The full sample plugin code can be found in the Mozilla source tree under modules/plugin/samples/4x-scriptable/ IBM Developer Works has published a good article on XPCOM. Examples Example 1. Sample .idl file #include "nsISupports.idl" [scriptable, uuid(bedb0778-2ee0-11d5-9cf8-0060b0fbd8ac)] interface nsITestPlugin : nsISupports { void nativeMethod
(); }; Example 2. Scriptable instance class #include "nsITestPlugin.h" #include "nsIClassInfo.h" // We must implement nsIClassInfo because it signals the // Mozilla Security Manager to allow calls from JavaScript. // helper class to implement all necessary nsIClassInfo method stubs // and to set flags used by the security system class nsClassInfoMixin : public nsIClassInfo { // These flags are ...
...NS_IMPL_ISUPPORTS2(nsScriptablePeer, nsITestPlugin, nsIClassInfo) // the following method will be callable from JavaScript NS_IMETHODIMP nsScriptab...
...And 2 more matches
Unconventional controls - Game development
n see the difference three years can make -- you can read the whole story in our Building games for Firefox OS TV Hacks post. Using a TV remote to control the game ended up being surprisingly easy, because the events fired by the controller are emulating conventional keyboard keys. Captain Rogers had the keyboard controls implemented already: this.cursors = this.input.keyboard.createCursorKeys
(); //... if(this.cursors.right.isDown) { // move player right } It works out of the box. The cursors are the four directional arrow keys on the keyboard, and these have exactly the same key codes as the arrow keys on the remote. How do you know the codes for the other remote keys? You can check them by printing the responses out in the console: window.addEventListener("keydown", function(even...
...<br />' + ' pitch: ' + verticalDegree + '? <br />' + ' strength: ' + grabStrength + ''; } }); The code above is calculating and assigning the horizontalDe...
...<br />' + ' pitch: ' + verticalDegree + '? <br />' + ' strength: ' + grabStrength + ''; } }); The code above is calculating and assigning the horizontalDegree, verticalDegree and grabStrength values that we will use l...
...And 2 more matches
Implementing game control mechanisms - Game development
c folder contains the JavaScript files split as a separate states -- Boot.js, Preloader.js, MainMenu.js and Game.js -- these are loaded into the index file in this exact order. The first one initializes Phaser, the second preloads all the assets, the third one controls the main menu welcoming the player, and the fourth controls the actual gameplay. Every state has its own default methods: preload
(), create
(), and update
(). The first one is needed for preloading required assets, create
() is executed once the state had started, and update
() is executed on every frame. For example, you can define a button in the create
() function: create: function
() { // ... var buttonEnclave = this.add.button(10, 10, 'logo-enclave', this.clickEnclave, this); // ... } It will be created once at the star...
... if(this.game.input.mousePointer.isDown) { // do something } // ... ...
... if(this.game.input.mousePointer.isDown) { // do something } // ... } This will be executed whenever the mouse button is pressed, and it will be checked against the input's isDown boolean variable on every frame of the game. ...
...And 2 more matches
Create the Canvas and draw on it - Game development
Here we're storing a reference to the <canvas> element to the canvas variable. Then we're creating the ctx variable to store the 2D rendering context -- the actual tool we can use to paint on the Canvas. Let's see an example piece of code that prints a red square on the canvas. Add this below your previous lines of JavaScript, then load your index.html in a browser to try it out. ctx.beginPath
(); ctx.rect(20, 40, 50, 50); ctx.fillStyle = "#FF0000"; ctx.fill
(); ctx.closePath
(); All the instructions are between the beginPath
() and closePath
() methods. We are defining a rectangle using rect
(): the first two values specify the coordinates of the top left corner of the rectangle on the canvas, while the second two specify the width and height of the rectangle. In our case the rectangle is pa...
...ecify the coordinates of the top left corner of the rectangle on the canvas, while the second two specify the width and height of the rectangle. In our case the rectangle is painted 20 pixels from the left side of the screen and 40 pixels from the top side, and is 50 pixels wide and 50 pixels high, which makes it a perfect square. ...
... 40 pixels from the top side, and is 50 pixels wide and 50 pixels high, which makes it a perfect square. The fillStyle property stores a color that will be used by the fill
() method to paint the square, in our case, red. We're not limited to rectangles -- here's a piece of code for printing out a green circle. Try adding this to the bottom of your JavaScript, saving and refreshing: ctx.beginPath
(); ctx.arc(240, 160, 20, 0, Math.PI*2, false); ctx.fillStyle = "green"; ctx.fill
(); ctx.closePath
(); As you can see we're using the beginPath
() and closePath
() methods again. Between them, the most important part of the code above is the arc
() method. It takes six parameters: x and y coordinates of the arc's center arc radius start angle and end angle (what angle to start and finish drawing t...
...And 2 more matches
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. ...
...nts 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. ...
...he 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 = "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. ...
...And 2 more matches
jQuery - MDN Web Docs Glossary: Definitions of Web-related terms
jQuery is a JavaScript Library that focuses on simplifying DOM manipulation, AJAX calls, and Event handling. jQuery uses a format, $(selector).action
() to assign an element(s) to an event. To explain it in detail, $(selector) will call jQuery to select selector element(s), and assign it to an event API called .action
(). ...
... jQuery is a JavaScript Library that focuses on simplifying DOM manipulation, AJAX calls, and Event handling. jQuery uses a format, $(selector).action
() to assign an element(s) to an event. To explain it in detail, $(selector) will call jQuery to select selector element(s), and assign it to an event API called .action
(). ...
...jQuery is a JavaScript Library that focuses on simplifying DOM manipulation, AJAX calls, and Event handling. jQuery uses a format, $(selector).action
() to assign an element(s) to an event. To explain it in detail, $(selector) will call jQuery to select selector element(s), and assign it to an event API called .action
(). ...
...And 2 more matches
Accessible multimedia - Learn web development
including the controls attribute in the first place has the advantage that if our JavaScript fails for any reason, the user still has some controls available. Wiring up our buttons First, let's set up the play/pause button. We can get this to toggle between play and pause with a simple conditional function, like the following. ...
...irst place has the advantage that if our JavaScript fails for any reason, the user still has some controls available. Wiring up our buttons First, let's set up the play/pause button. We can get this to toggle between play and pause with a simple conditional function, like the following. ...
...n, the user still has some controls available. Wiring up our buttons First, let's set up the play/pause button. We can get this to toggle between play and pause with a simple conditional function, like the following. Add it to your code, at the bottom: playPauseBtn.onclick = function
() { if(player.paused) { player.play
(); playPauseBtn.textContent = 'Pause'; } else { player.pause
(); playPauseBtn.textContent = 'Play'; } }; Next, add this code to the bottom, which controls the stop button: stopBtn.onclick = function
() { player.pause
(); player.currentTime = 0; playPauseBtn.textContent = 'Play'; }; There is no stop
() function available on HTMLMediaElements, so instead we pause
() it, and at the same time set the currentTime to 0. Next, our rewind and fast forward...
...And 2 more matches
Adding vector graphics to the Web - Learn web development
margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); const output = document.querySelector('.output'); let code = textarea.value; let userEntry = textarea.value; function updateCode
() { output.innerHTML = textarea.value; } reset.addEventListener('click', function
() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode
(); }); solution.addEventListener('click', function
() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; }...
...area.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode
(); }); solution.addEventListener('click', function
() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Show solution'; } updateCode
(); }); const htmlSolution = ''; let solutionEntry = htmlSolution; textarea.addEventListener('input', updateCode); window.addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault
(); insertAtCaret('\t'); } if (e.keyCode === 27) { ...
...mlSolution = ''; let solutionEntry = htmlSolution; textarea.addEventListener('input', updateCode); window.addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault
(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur
(); } }; function insertAtCaret(text) { const scrollPos = textarea.scrollTop; const caretPos = textarea.selectionStart; const front = (textarea.value).substring(0, caretPos); const back = (textarea.value).substring(textarea.selectionEnd, textarea.value.length); textarea.value = front + text + back; caretPos = caretPos + text.length; textarea.selectionStart = caretPos; textarea.se...
...And 2 more matches
From object to iframe — other embedding technologies - Learn web development
margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); const output = document.querySelector('.output'); let code = textarea.value; let userEntry = textarea.value; function updateCode
() { output.innerHTML = textarea.value; } reset.addEventListener('click', function
() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode
(); }); solution.addEventListener('click', function
() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; }...
...area.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode
(); }); solution.addEventListener('click', function
() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Show solution'; } updateCode
(); }); const htmlSolution = '<iframe width="420" height="315" src="https://www.youtube.com/embed/QH2-TGUlwu4" frameborder="0" allowfullscreen>\n</iframe>\n\n<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d37995.65748333395!2d-2.273568166412784!3d53.473310471916975!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x487bae6c05743d3d%3A0xf82fddd1e49fc0a1!2sThe+Lowry!5e0!3m2!1sen!2...
...5211" width="600" height="450" frameborder="0" style="border:0" allowfullscreen>\n</iframe>'; let solutionEntry = htmlSolution; textarea.addEventListener('input', updateCode); window.addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault
(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur
(); } }; function insertAtCaret(text) { const scrollPos = textarea.scrollTop; const caretPos = textarea.selectionStart; const front = (textarea.value).substring(0, caretPos); const back = (textarea.value).substring(textarea.selectionEnd, textarea.value.length); textarea.value = front + text + back; caretPos ...
...And 2 more matches
Silly story generator - Learn web development
BLE AND FUNCTION DEFINITIONS" and paste it into the top of the main.js file. This gives you three variables that store references to the "Enter custom name" text field (customName), the "Generate random story" button (randomize), and the <p> element at the bottom of the HTML body that the story will be copied into (story), respectively. In addition you've got a function called randomValueFromArray
() that takes an array, and returns one of the items stored inside the array at random. Now look at the second section of the raw text file -- "2. RAW TEXT STRINGS". This contains text strings that will act as input into our program. We'd like you to contain these inside variables inside main.js: Store the first, big long, string of text inside a variable called storyText. Store the first ...
... inside an array called insertZ. Placing the event handler and incomplete function: Now return to the raw text file. Copy the code found underneath the heading "3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION" and paste it into the bottom of your main.js file. This: Adds a click event listener to the randomize variable so that when the button it represents is clicked, the result
() function is run. Adds a partially-completed result
() function definiton to your code. For the remainder of the assessment, you'll be filling in lines inside this function to complete it and make it work properly. Completing the result
() function: Create a new variable called newStory, and set its value to equal storyText. This is needed so we can create a new random story each time t...
...Create a new variable called newStory, and set its value to equal storyText. This is needed so we can create a new random story each time the button is pressed and the function is run. If we made changes directly to storyText, we'd only be able to generate a new story once. Create three new variables called xItem, yItem, and zItem, and make them equal to the result of calling randomValueFromArray
() on your three arrays (the result in each case will be a random item out of each array it is called on). For example you can call the function and get it to return one random string out of insertX by writing randomValueFromArray(insertX). Next we want to replace the three placeholders in the newStory string -- :insertx:, :inserty:, and :insertz: -- with the strings stored in xItem, yItem, and zIt...
...And 2 more matches
Test your skills: Object-oriented JavaScript - Learn web development
this page. Note: In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). OOJS 1 In this task we provide you with a constructor. We want you to: Add a new method to the Shape class's prototype, calcPerimeter
(), which calculates its perimeter (the length of the shape's outer edge) and logs the result to the console. Create a new instance of the Shape class called square. Give it a name of square and a sideLength of 5. Call your calcPerimeter
() method on the instance, to see whether it logs the calculation result to the browser DevTools' console as expected. Create a new instance of Shape called trian...
... the result to the console. Create a new instance of the Shape class called square. Give it a name of square and a sideLength of 5. Call your calcPerimeter
() method on the instance, to see whether it logs the calculation result to the browser DevTools' console as expected. Create a new instance of Shape called triangle, with a name of triangle and a sideLength of 3. Call triangle.calcPerimeter
() to check that it works OK. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. OOJS 2 Next up we want you to take the Shape class you saw in Task #1 (including the calcPerimeter
() method) and recreate it using ES class syntax instead. Test that it works by creating the square and ...
...code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. OOJS 2 Next up we want you to take the Shape class you saw in Task #1 (including the calcPerimeter
() method) and recreate it using ES class syntax instead. Test that it works by creating the square and triangle object instances as before (using new Shape
() for both), and then calling their calcPerimeter
() methods. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. OOJS 3 Finally, we'd like you to start with the ES Shape class you created in the last task. We'd like you to create a Square class that inherits from Shape, and adds a ca...
...And 2 more matches
Ember interactivity: Events, classes and state - Learn web development
om '@glimmer/component'; export default class HeaderComponent extends Component { } Inside this file we will implement the event handler code. ...
...taService extends Service { @tracked todos = []; @action add(text) { let newTodo = new Todo(text); this.todos = [...this.todos, newTodo]; } } Here, the todos property on the service will maintain our list of todos contained inside an array, and we'll mark it with @tracked, because when the value of todos is updated we want the UI to update as well. And just like before, the add
() function that will be called from the template gets annotated with the @action decorator to bind it to the class instance. This function's contents are fairly easy to understand -- when the function is invoked, a new Todo object instance is created with a text value of text, and the todos property value is updated to all of the current items inside the array (accessed conveniently using spread sy...
...mport lines: import { inject as service } from '@ember/service'; With this import in place, we can now make the todo-data service available inside the HeaderComponent class via the todos object, using the @service decorator. Add the following line just below the opening export... line: @service('todo-data') todos; Now the placeholder alert(text); line can be replaced with a call to our new add
() function. Replace it with the following: this.todos.add(text); If we try this out in the todo app in our browser (npm start, go to localhost:4200), it will look like nothing happens after hitting the Enter key (although the fact that the app builds without any errors is a good sign). Using the Ember Inspector however, we can see that our todo was added: Displaying our todos Now that we know...
...And 2 more matches
Routing in Ember - Learn web development
route active The second and third commands should have not only generated new files, but also updated an existing file, app/router.js. It contains the following contents: import EmberRouter from '@ember/routing/router'; import config from './config/environment'; export default class Router extends EmberRouter { location = config.locationType; rootURL = config.rootURL; } Router.map(function
() { this.route('completed'); this.route('active'); }); The highlighted lines were added when the 2nd and 3rd commands above were run. router.js behaves as a "sitemap" for developers to be able to quickly see how the entire app is structured. It also tells Ember how to interact with your route, such as when loading arbitrary data, handling errors while loading that data, or interpreting dynam...
... now we need a way to differentiate between each of these routes, so that they show what they are supposed to show. First of all, return once more to our todo-data.js file. It already contains a getter that returns all todos, and a getter that returns incomplete todos. The getter we are missing is one to return just the completed todos. Add the following below the existing getters: get completed
() { return this.todos.filter(todo => todo.isCompleted); } Models Now we need to add models to our route JavaScript files to allow us to easily return specific data sets to display in those models. model is a data loading lifecycle hook. For TodoMVC, the capabilities of model aren't that important to us; you can find more information in the Ember model guide if you want to dig deeper. We also pr...
...the Ember model guide if you want to dig deeper. We also provide access to the service, like we did for the components. The index route model First of all, update todomvc/app/routes/index.js so it looks as follows: import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; export default class IndexRoute extends Route { @service('todo-data') todos; model
() { let todos = this.todos; return { get allTodos
() { return todos.all; } } } } We can now update the todomvc/app/templates/index.hbs file so that when it includes the <TodoList /> component, it does so explicitly with the available model, calling its allTodos
() getter to make sure all of the todos are shown. In this file, change <TodoList /> To <TodoList @to...
...And 2 more matches
Introduction to client-side frameworks - Learn web development
It follows a similar pattern to the one we used to build a list item element: function buildDeleteButtonEl(id) { const button = document.createElement('button'); const textContent = document.createTex...
...ument.createTextNode(name); span.appendChild(textContent) item.id = id; item.appendChild(span); item.appendChild(buildDeleteButtonEl(id)); return item; } Here, we use the document.createElement
() method to make our <li>, and several more lines of code to create the properties and children it needs. The tenth line of this snippet references another build function: buildDeleteButtonEl
(). It follows a similar pattern to the one we used to build a list item element: function buildDeleteButtonEl(id) { const button = document.createElement('button'); const textContent = document.createTextNode('Delete'); button.setAttribute('type', 'button'); button.appendChild(textContent); return button; } This button doesn't do anything yet, but it will later once we decide to imple...
...n = document.createElement('button'); const textContent = document.createTextNode('Delete'); button.setAttribute('type', 'button'); button.appendChild(textContent); return button; } This button doesn't do anything yet, but it will later once we decide to implement our delete feature. ...
...And 2 more matches
Creating our first Vue component - Learn web development
se components to re-render. So mutating props in a component would trigger the component to rerender, which may in-turn trigger the mutation again. To work around this, we can manage the done state using Vue's data property. The data property is where you can manage local state in a component, it lives inside the component object alongside the props property and has the following structure: data
() { return { key: value } } You'll note that the data property is a function. This is to keep the data values unique for each instance of a component at runtime -- the function is invoked separately for each component instance. If you declared data as just an object, all instances of that component would share the same values. This is a side-effect of the way Vue registers components and s...
...rrow function. So don't use an arrow function for the data property. So let's add a data property to our ToDoItem component. This will return an object containing a single property that we'll call isDone, whose value is this.done. Update the component object like so: export default { props: { label: { required: true, type: String }, done: { default: false, type: Boolean } }, data
() { return { isDone: this.done }; } }; Vue does a little magic here -- it binds all of your props directly to the component instance, so we don't have to call this.props.done. It also binds other attributes (data, which you've already seen, and others like methods, computed, etc.) directly to the instance. This is, in part, to make them available to your template. The down-side to ...
...ve a working checkbox where we can set the state programmatically. However, we can currently only add one ToDoList component to the page because the id is hardcoded. This would result in errors with assistive technology since the id is needed to correctly map labels to their checkboxes. To fix this, we can programmatically set the id in the component data. We can use the lodash package's uniqueid
() method to help keep the index unique. This package exports a function that takes in a string and appends a unique integer to the end of the prefix. This will be sufficient for keeping component ids unique. Let's add the package to our project with npm; stop your server and enter the following command into your terminal: npm install --save lodash.uniqueid Note: If you prefer yarn, you could in...
...And 2 more matches
Multiprocess on Windows
runtime. The mscom library provides an API for doing this: the RegisterProxy and RegisterTypelib functions in mozilla/mscom/Registration.h. Both of these functions return unique pointers and should be treated as opaque by the caller. Save them to a location where they will be able to exist for the lifetime of the process. If your typelib is embedded in a proxy's resources, then use RegisterProxy
(). This is the preferred mechanism, as it will register both your OICF and typelib metadata. If you have a standalone .tlb file that you need to register, then use RegisterTypelib
(). Note: you should register your typelibs and proxies in both the chrome and content processes. If you only register your interfaces in one process, COM won't be able to understand the interface in the other process. ...
...interceptor would only wrap the first element in the array, because it cannot distinguish between scalars and arrays. Note: If your new interface does not contain either of these annotations, then you do not need to worry about this step. For those interfaces that do contain length_is or size_is annotations, we need to use another API declared in mozilla/mscom/Registration.h: RegisterArrayData
(). RegisterArrayData
() accepts an array of ArrayData structs. You should statically define this array in your code, as const. For example: static const mozilla::mscom::ArrayData kMyArrayData[] { { // First ArrayData definition }, { // Second ArrayData definition } }; mozilla::mscom::RegisterArrayData(kMyArrayData); Each ArrayData struct corresponds to one function; with length_is and/or siz...
...ay (excluding the this pointer). The interceptor needs to be able to read this parameter to know how many interface pointers exist in the array. mFlag may currently be set to one of two values: ArrayData::Flag::eNone or ArrayData::Flag::eAllocatedByServer. Setting eAllocatedByServer signals to the interceptor that the array is allocated within the method's implementation by calling CoTaskMemAlloc
(). Using the interceptor in a11y code Unlike the built in COM marshaling schemes, we must explicitly wrap any COM objects that we want to expose, through the MTA with interceptors. The function call to wrap a COM object is mozilla::mscom::MainThreadHandoff::WrapInterface
(). This receives the COM interface which you want to wrap as its first parameter, and outputs the wrapped object (with the sam...
...And 2 more matches
AsyncShutdown.jsm
nd has been known to) cause data loss. Example At some point during shutdown, the Add-On Manager needs to ensure that all add-ons have safely written their data to disk, before writing its own data. Since the data is saved to the profile, this must be completed during phase profileBeforeChange. AsyncShutdown.profileBeforeChange.addBlocker( "Add-on manager: shutting down", function condition
() { let promise = ... // Do whatever must be done before the end of phase profileBeforeChange return promise; }, function info
() { let status = ... // Collect any information that may be useful for debugging shutdown issues with this blocker return status; } }); In this example, at some point during phase profileBeforeChange, function condition will be called. Phase profi...
...ed or rejected. If, for some reason, promise is never resolved/rejected, Firefox will crash during shutdown to avoid blocking system shutdown, preventing the user from restarting Firefox or burning through a battery. In this case, a crash report is produced, with information on all the shutdown blockers that have not been resolved, and all the additional debug information returned by calls to info
(). ...
... void addBlocker( in string name, in function|promise|* condition, optional in function info ) Arguments name The human-readable name of the blocker. Used for debugging/error reporting. ...
...And 2 more matches
Localization and Plurals
eed plural forms. People using the extension can then copy/paste this input. chrome://mozapps/locale/downloads/do...tes,hours,days chrome://mozapps/locale/downloads/do...dsTitlePercent chrome://browser/locale/browser.prop...ausedDownloads Version history 0.1: Initial version with pluralRule check, properties input loading, table generation, sample output display 0.2: Use PluralForm.numForms
() to get the number of forms instead of figuring out locally to better support future rules - Requires build from 2007/01/27 or later 0.3: Generate a list of what numbers fall into which plural form to minimize the sample output to at most 3 of each form Developing with PluralForm The functionality for getting the correct plural forms is provided by a JavaScript Module, PluralForm.jsm. This modu...
...This is because someone installing the extension on a different locale will be using the strings provided by your default extension locale. For example, your extension localized for English with plural rule #1, which expects 2 plural forms, is installed on a localized version of Firefox with plural rule #4, which expects 3 forms: /** * Create a pair of plural form func...
...ce("#1", numDownloads)); // Get the correct plural form of seconds let timeLeft = 55; let seconds = PluralForm.get(timeLeft, getStr("seconds")); // Print the localized string for "55 seconds" print(getStr("timePair").replace("#1", timeLeft).replace("#2", seconds)); Method: makeGetter If you're writing an extension, you'll want to use makeGetter instead of PluralForm.get
() or PluralForm.numForms
(). This is because someone installing the extension on a different locale will be using the strings provided by your default extension locale. For example, your extension localized for English with plural rule #1, which expects 2 plural forms, is installed on a localized version of Firefox with plural rule #4, which expects 3 forms: /** * Create a pair of plural form functions for the given plura...
...And 2 more matches
Enc Dec MAC Output Public Key as CSR
key = PK11_TokenKeyGen(slot, mechanism, NULL, keySize, keyID, PR_FALSE, pwdata); if (!key) { PR_fprintf(PR_STDERR, "Symmetric Key Generation Failed \n"); } return key; } /* * MacInit */ SECStatus MacInit(PK11Context *ctx) { SECStatus rv = PK11_DigestBegin(ctx); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : PK11_DigestBegin
()\n"); } return rv; } /* * MacUpdate */ SECStatus MacUpdate(PK11Context *ctx, unsigned char *msg, unsigned int msgLen) { SECStatus rv = PK11_DigestOp(ctx, msg, msgLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : DigestOp
()\n"); } return rv; } /* * Finalize MACing */ SECStatus MacFinal(PK11Context *ctx, unsigned char *...
...CSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : DigestOp
()\n"); } return rv; } /* * Finalize MACing */ SECStatus MacFinal(PK11Context *ctx, unsigned char *mac, unsigned int *macLen, unsigned int maxLen) { SECStatus rv = PK11_DigestFinal(ctx, mac, macLen, maxLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Compute MAC Failed : PK11_DigestFinal
()\n"); } return SECSuccess; } /* * Compute Mac */ SECStatus ComputeMac(PK11Context *ctxmac, unsigned char *ptext, unsigned int ptextLen, unsigned char *mac, unsigned int *macLen, unsigned int maxLen) { SECStatus rv = MacInit(ctxmac); if (rv != SECSuccess) return rv; rv = MacUpdate(ctxmac, ptext, ptextLen); if (rv != SECSuccess) return rv; ...
...ol *arena = NULL; PRFileDesc *outFile = NULL; /* Open the certificate request file to write */ outFile = PR_Open(certReqFileName, PR_CREATE_FILE | PR_RDWR | PR_TRUNCATE, 00660); if (!outFile) { PR_fprintf(PR_STDERR, "unable to open \"%s\" for writing (%ld, %ld).\n", certReqFileName, PR_GetError
(), PR_GetOSError
()); goto cleanup; } /* Create info about public key */ spki = SECKEY_CreateSubjectPublicKeyInfo(pubk); if (!spki) { PR_fprintf(PR_STDERR, "unable to create subject public key\n"); rv = SECFailure; goto cleanup; } /* Generate certificate request */ cr = CERT_CreateCertificateRequest(subject, spki, NULL); if (!cr) { ...
...And 2 more matches
NSS Sample Code Sample_2_Initialization of NSS
*/ rv = ChangePW(slot, plainPass, 0, pwFile, 0); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Failed to change password\n"); } if (slot) { PK11_FreeSlot(slot); } rvShutdown = NSS_Sh...
...troyOptState(optstate); if (!dbdir) Usage(progName); PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); /* Create the database */ rv = NSS_InitReadWrite(dbdir); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "NSS_Initialize Failed"); PR_Cleanup
(); exit(rv); } if (PL_strcmp(slotname, "internal") == 0) slot = PK11_GetInternalKeySlot
(); /* If creating new database, initialize the password. ...
... exit(rv); } if (PL_strcmp(slotname, "internal") == 0) slot = PK11_GetInternalKeySlot
(); /* If creating new database, initialize the password. ...
...And 2 more matches
Initialize NSS database - sample 2
*/ rv = ChangePW(slot, plainPass, 0, pwFile, 0); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Failed to change password\n"); } if (slot) { PK11_FreeSlot(slot); } rvShutdown = NSS_Sh...
...troyOptState(optstate); if (!dbdir) Usage(progName); PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); /* Create the database */ rv = NSS_InitReadWrite(dbdir); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "NSS_Initialize Failed"); PR_Cleanup
(); exit(rv); } if (PL_strcmp(slotname, "internal") == 0) slot = PK11_GetInternalKeySlot
(); /* If creating new database, initialize the password. ...
... exit(rv); } if (PL_strcmp(slotname, "internal") == 0) slot = PK11_GetInternalKeySlot
(); /* If creating new database, initialize the password. ...
...And 2 more matches
FC_InitPIN
The role of the PKCS #11 SO is to initialize a token and to initialize the normal user's PIN. ...
...The role of the PKCS #11 SO is to initialize a token and to initialize the normal user's PIN. ...
...The role of the PKCS #11 SO is to initialize a token and to initialize the normal user's PIN. ...
...And 2 more matches
Rhino scopes and contexts
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. ...
...e 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. To associate the current thread with a Context, simply call the enter method of Context: Context cx = Context.enter
(); Once you are done with execution, simply exit the Context: Context.exit
(); These calls will work properly even if there is already a Context associated with the current thread. That context will be returned and an internal counter incremented. Only when the counter reaches zero will it be disassociated from the thread. Remember to put the exit
() call in a finally block if you're executing code that could throw an exception. Scopes A scope is a set of JavaScript ob...
...atomic across threads, but doesn't make any more guarantees for scripts executing in the same scope at the same time. If two scripts use the same scope simultaneously, the scripts are responsible for coordinating any accesses to shared variables. A top-level scope is created by calling Context.initStandardObjects to create all the standard objects: ScriptableObject scope = cx.initStandardObjects
(); The easiest way to embed Rhino is just to create a new scope this way whenever you need one. However, initStandardObjects is an expensive method to call and it allocates a fair amount of memory. We'll see below that there are ways to share a scope created this way among multiple scopes and threads. Name Lookup So how are scopes used to look up names? In general, variables are looked up by st...
...And 2 more matches
SpiderMonkey Internals
ions ("lvalues" in C parlance), and whether / is the division symbol or the start of a regular expression. The compiler attempts no error recovery; it bails out on the first error. The emitter does some constant folding and a few codegen optimizations; about the fanciest thing it does is to attach source notes to the script for the decompiler's benefit. The decompiler implements Function.toSource
(), which reconstructs a function's source code. It translates postfix bytecode into infix source by consulting a separate byte-sized code, called source notes, to disambiguate bytecodes that result from more than one grammatical production. Garbage collector The GC is a mark-and-sweep, non-conservative (exact) collector. It is used to hold JS objects and string descriptors (JSString), but not str...
...as a C++ double (noting that JavaScript NaN must be represented as one canonical NaN format). Other values are encoded as a value and a type tag: On x86, ARM, and similar 32-bit platforms, we use what we call "nunboxing", in which non-double values are a 32-bit type tag and a 32-bit payload, which is normally either a pointer or a signed 32-bit integer. There are a few special values: NullValue
(), UndefinedValue
(), TrueValue
() and FalseValue
(). On x64 and similar 64-bit platforms, pointers are longer than 32 bits, so we can't use the nunboxing format. Instead, we use "punboxing", which has 17 bits of tag and 47 bits of payload. 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 als...
...o we can determine whether it's perfect // already by evaluating. ...
...And 2 more matches
JIT Optimization Strategies
roperty needs to be well-defined on the object. For objects constructed by constructor functions, this means that the property needs to be defined in the constructor, before any complex logic occurs within the constructor. This is the best case for a regular "field" type property that is not turned into a constant. It compiles down to a single CPU-level load instruction. function SomeConstructor
() { this.x = 10; // x is a definite slot property this.y = 10; // y is a definite slot property someComplicatedFunctionCall
(); this.z = 20; // z is not a definite slot property. } In the above example, the properties x and y can always be determined to exist on any instance of SomeConstructor at definite locations, allowing the engine to infer deterministically the positi...
...onGetter Optimizes access to properties which are implemented by a getter function, where the getter is shared between multiple types. This optimization applies most often when the property access site is polymorphic, but all the object types are derived variants of a single base class, where the property access refers to a getter on the base class. Consider the following example: function Base
() {} Base.prototype = { get x
() { return 3; } }; function Derived1
() {} Derived1.prototype = Object.create(Base.prototype); function Derived2
() {} Derived1.prototype = Object.create(Base.prototype); If a property access for d.x sees only instances of both Derived1 and Derived2 for d, it can optimize the access to x to a call to the getter function defined on Base. This optimization applies to ...
...onSetter Optimizes access to properties which are implemented by a setter function, where the setter is shared between multiple types. This optimization applies most often when the property access site is polymorphic, but all the object types are derived variants of a single base class, where the property access refers to a setter on the base class. Consider the following example: function Base
() {} Base.prototype = { set x(val) { ... } }; function Derived1
() {} Derived1.prototype = Object.create(Base.prototype); function Derived2
() {} Derived1.prototype = Object.create(Base.prototype); If a property write for d.x = val sees only instances of both Derived1 and Derived2 for d, it can optimize the write to x to a call to the setter function defined on Base. This optimization applies to...
...And 2 more matches
JS::AutoVectorRooter
bool append(const T &v) Appends an element v to the array. ...
... bool append(const T &v) Appends an element v to the array. ...
...with a pointer ptr and length len to the array. bool appendAll(const AutoVectorRooter<T> &other) Appends all elements of other to the array. bool insert(T *p, const T &val) Inserts an element val at the position specified by p. void infallibleAppend(const T &v) Appends an element v to the array. For use when space has already been reserved. void popBack
() Pops an element from the array. T popCopy
() Pops an element from the array and returns it. bool growBy(size_t inc) Grows the array by inc. bool resize(size_t newLength) Resizes the array to newLength. void clear
() Clears all elements. bool reserve(size_t newLength) Reserves the array with newLength. JS::MutableHandle<T> opera...
...And 2 more matches
JS::CallArgs
gument of JSNative) Methods Methods of JS::CallArgs Method Description bool requireAtLeast(JSContext *cx, const char *fnname, unsigned required) Returns true if there are at least required arguments passed in. If false, it reports an error message on the context. Methods inherited from JS::CallArgsBase Method Description unsigned length
() const Returns the number of arguments.. JS::MutableHandleValue operator[](unsigned i) const Returns the i-th zero-indexed argument. JS::HandleValue get(unsigned i) const Returns the i-th zero-indexed argument, or undefined if there's no such argument. bool hasDefined(unsigned i) const Returns true if the i-th zero-indexed argument is present and is not undef...
...th zero-indexed argument. JS::HandleValue get(unsigned i) const Returns the i-th zero-indexed argument, or undefined if there's no such argument. bool hasDefined(unsigned i) const Returns true if the i-th zero-indexed argument is present and is not undefined. Methods inherited from JS::detail::CallReceiverBase Method Description JSObject &callee
() const Returns the function being called, as an object. Must not be called after rval
() has been used! JS::HandleValue calleev
() const Returns the function being called, as a value. Must not be called after rval
() has been used! JS::HandleValue thisv
() const Returns the this value passed to the function. This method must not be called when the function is being called as...
...ed to the function. This method must not be called when the function is being called as a constructor via new. The value may or may not be an object: it is the individual function's responsibility to box the value if needed. JS::Value computeThis(JSContext *cx) const Returns the this value if this is an object, otherwise calls JS_ComputeThis and returns it. bool isConstructing
() const Returns true if the function is called via new. MutableHandleValue rval
() const Returns the currently-set return value. The initial contents of this value are unspecified. Once this method has been called, callee
() and calleev
() can no longer be used. (If you're compiling against a debug build of SpiderMonkey, these methods will assert to aid debugging.) If the meth...
...And 2 more matches
Using the Places livemark service
rk folders that contain the most recent items from an RSS feed. Initiating the livemark service Before using the livemark service, you need to obtain an instance: var livemarkService = Components.classes["@mozilla.org/browser/livemark-service;2"] .getService(Components.interfaces.nsILivemarkService); Creating a new livemark The nsILivemarkService.createLivemark
() method creates a new livemark. var newLvmkId = livemarkService.createLivemark(parentFolderId, "Livemark name", uri("http://example.com/"), uri("http://example.com/rss.xml"), -1); The first parameter is the ID of the folder in which to create the livemark. ...
...RI of the site the livemark was created from (specified as an nsIURI object. Fourth argument is the URI of the actual RSS feed. The last argument takes in the index to insert at, or -1 to append the new livemark to the end of the folder. You can convert a string into an nsIURI using nsIIOService. When creating livemarks during startup, you should use the nsILivemarkService.createLivemarkFolderOnly
() to avoid HTTP traffic. This creates the encapsulating livemark without actually fetching the RSS feed's contents. var bmsvc = Components.classes["@mozilla.org/browser/nav-bookmarks-service;1"]. getService(Components.interfaces.nsINavBookmarksService); var root = bmsvc.bookmarksMenuFolder; // Item ID of the Bookmarks Menu var newLvmkId = livemarkService.createLivemarkFolder...
...var newLvmkId = livemarkService.createLivemarkFolderOnly(bmsvc, root, "Livemark name", uri("http://example.com/"), uri("http://example.com/rss.xml"), -1); The parameters here are the same as for nsILivemarkService.createLivemark
(), except for the insertion of a new parameter at the beginning, which is the nsINavBookmarksService to use when creating the livemark. Determine whether a folder is a livemark You can use the nsILivemarkService.isLivemark
() method to determine whether or not a given folder is a livemark container: if (livemarkService.isLivemark(folderID)) { // it's a livemark } else { // it's not a livemark ...
...And 2 more matches
XML Extras
r Available XMLHttpRequest Available DOMParser (string and stream input source) Available Web Services with SOAP and WSDL No longer available from Gecko 1.9/Firefox 3. XML Persistence FIXptr and XPointer Available since 1.4alpha in the core Mozilla. Moved to XML Extras during 1.4beta. See also: XML in Mozilla document.load
() A few examples dealing with XML from MozillaZine Knowledge Base. QA and Testing There are some online tests for mainly exercising the HTTP GET method via XMLHttpRequest. Other test cases for each of the implemented components listed above exist in extensions/xmlextras/tests/. More exhaustive test suites need to be created, however. If you'd like to help out with QA, you can do one of the fol...
...pping cart with XML and ASP". The Mozilla Developer Center has several pages for XMLHttpRequest. Below are some key differencies in "XML Extras" between Mozilla and Microsoft software: Difference Microsoft Mozilla Member names Case insensitive? Begins with lower case letter XMLHttpRequest Creation new ActiveXObject("Msxml2.XMLHTTP") new XMLHttpRequest
() XMLHttpRequest.send("some string") ok ok starting with milestone 0.9.7 (actually nightly 2001-11-28). With older builds, passing strings to send
() works only in chrome, see post.html sample. The "workaround" is to use DOMParser object's parseFromString
() method to create a document from string, and pass the temporary document into send
(). XMLHttpRequest.open("aHost") ok...
...he JavaScript Security: Signed Scripts document for more details. Normally your files should reside on a webserver so this shouldn't pose a problem (there you do not need that line either). Additionally, "foo.com:80" and "foo.com:313" are considered different hosts for security purposes. You cannot open a connection to a different host. DOMParser Creation not available new DOMParser
() XMLSerializer Creation not available new XMLSerializer
() Minimal documentation for the components listed above can be found using Mozilla documentation generated by Doxygen. File new bugs for additional documentation contributions, either specifically aimed at JavaScript developers or to complete & clarify the JavaDoc-style comments in the IDL files. nsIDOMSerializer (Cur...
...And 2 more matches
XPCOM changes in Gecko 2.0
en the XPCOM component manager needs to create a component. ...
... a component. chrome.manifest: # The {classID} here must match the classID in mycomponent.js component {e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8} components/mycomponent.js contract @foobar/mycomponent;1 {e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8} category profile-after-change MyComponent @foobar/mycomponent;1 The JavaScript code no longer exports a NSGetModule
() function. ...
... {e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8} category profile-after-change MyComponent @foobar/mycomponent;1 The JavaScript code no longer exports a NSGetModule
() function. It now must export a NSGetFactory
() function, which accepts a class ID (CID) as a parameter. For example, in your component's JavaScript code : Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); function myComponent
() { } myComponent.prototype = { // this must match whatever is in chrome.manifest! classID: Components.ID("{e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8}"), QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIMyComponent]), /* nsIMyComponent implementation goes here */ ... }; // The following line is what XPCOM uses to create components. Each component prototype // must have a .cla...
...And 2 more matches
Making cross-thread calls using runnables
on a new thread and be notified when the result is available. ...
...o all you need to do is override the Run
() function. In our example, we actually need two runnables: one dispatched to the worker thread, and one to hand us back the result. #include "nsThreadUtils.h" class PiResultTask : public nsRunnable { public: PiResultTask(PiCallback callback, const nsACString& result) : mCallback(callback) , mResult(result) , mWorkerThread(do_GetCurrentThread
()) { MOZ_ASSERT(!NS_IsMainThread
()); // This should be running on the worker thread } NS_IMETHOD Run
() { MOZ_ASSERT(NS_IsMainThread
()); // This method is supposed to run on the main thread! mCallback(mResult); // If we don't destroy the thread when we're done with it, it will hang around forever... bad! // But thread->Shutdown must be called from the main thread, not fro...
... mCallback(mResult); // If we don't destroy the thread when we're done with it, it will hang around forever... bad! ...
...And 2 more matches
Components.utils.Sandbox
principal The security principal defined for a sandbox determines what code running in that sandbox will be allowed to do. ...
... create a new sandbox, call Components.utils.Sandbox: var sandbox = Components.utils.Sandbox(principal[, options]); Using new Components.utils.Sandbox(...) to create a sandbox has the same effect as calling Sandbox(...) without new. 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 T...
...dow's DOM) can be executed without interference from untrusted content code. wantComponents A Boolean indicating whether the Components object is available or not in the sandbox. Default: true. If the sandbox interacts with untrusted content this should be set to false when possible to further reduce possible attack surface. wantExportHelpers A Boolean: if true, then createObjectIn
(), evalInWindow
(), and exportFunction
() are available in the sandbox. Default: false. wantGlobalProperties An array of strings. Each string is the name of an object that you want to make available as a global to code running in the sandbox. The exception is "-Promise": the Promise constructor is available by default for sandboxes, and you use this option to remove it from the sandbox. Note th...
...And 2 more matches
IAccessibleAction
[propget] HRESULT description( [in] long actionIndex, [out] BSTR description ); Parameters actionIndex 0 based index specifying which action's description to return. If it lies outside the valid range an empty string is returned. description The returned value is a localized string of the specified action. Return value E_INVALIDA...
... [out] BSTR description ); Parameters actionIndex 0 based index specifying which action's description to return. If it lies outside the valid range an empty string is returned. description The returned value is a localized string of the specified action. Return value E_INVALIDARG if bad [in] passed, [out] value is null. S_FALSE if there is nothing to return, [out] value is null. S_OK. ...
...The returned strings are the localized human readable key sequences to be used to activate each action, e.g. "Ctrl+Shift+D". ...
...And 2 more matches
IAccessibleValue
umerical value like progress bars and spin boxes. This interface lets you access the value and its upper and lower bounds. ...
...[propget] HRESULT maximumValue( [out] VARIANT maximumValue ); Parameters maximumValue Returns the maximal value in an implementation dependent type. ...
... Parameters currentValue Returns the current value represented by this object. See the section about. Return value S_FALSE if there is nothing to return, [out] value is null. S_OK. maximumValue
() Returns the maximal value that can be represented by this object. The type of the returned value is implementation dependent. It does not have to be the same type as that returned by method currentValue
(). [propget] HRESULT maximumValue( [out] VARIANT maximumValue ); Parameters maximumValue Returns the maximal value in an implementation dependent type. If this object has no upper bound then an empty object is returned. See the section about. Return value S_OK. minimumValue
() Returns the minimal value that can be represented by this object. The type of the returned value is implementation depe...
...And 2 more matches
nsIAccessNode
The previous nsIAccessNode sibling. Read only. Obsolete since Gecko 2.0 rootDocument nsIAccessibleDocument The root document accessible that this access node resides in. Read only. uniqueID voidPtr A unique ID calculated for this DOM node, for the purposes of caching and referencing this object. Read only. Native code only! Methods getChildNodeAt
() Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Get the nth child of this node. nsIAccessNode getChildNodeAt( in long childNum ); Parameters childNum Zero-based child index. Return value The nth nsIAccessNode child. Exceptions thrown NS_ERROR_FAILURE Indicates that the access node is unattached from the accessible tree. getComputedStyleC...
... Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Get the nth child of this node. nsIAccessNode getChildNodeAt( in long childNum ); Parameters childNum Zero-based child index. Return value The nth nsIAccessNode child. Exceptions thrown NS_ERROR_FAILURE Indicates that the access node is unattached from the accessible tree. getComputedStyleCSSValue
() Retrieve the computed style value as nsIDOMCSSPrimitiveValue for the DOM node this access node is associated with. Note: The meanings of width, height and other size measurements depend on the version of CSS being used. Therefore, for bounds information, it is better to use nsIAccessible.getBounds
(). nsIDOMCSSPrimitiveValue getComputedStyleCSSValue( in DOMString pseudoElt, in DOMString pro...
...s pseudoElt The pseudo element to retrieve style for, or empty string for general computed style information for the node. propertyName Retrieve the computed style value for this property name. Return value The nsIDOMCSSPrimitiveValue computed style value. Exceptions thrown NS_ERROR_FAILURE Indicates that the access node is unattached from the accessible tree. getComputedStyleValue
() Retrieve the computed style value for this DOM node, if it is a DOM element. Note: The meanings of width, height and other size measurements depend on the version of CSS being used. Therefore, for bounds information, it is better to use nsIAccessible.getBounds
(). DOMString getComputedStyleValue( in DOMString pseudoElt, in DOMString propertyName ); Parameters pseudoElt The pseudo elem...
...And 2 more matches
nsIAccessibleEditableText
void pasteText(in long position); void setAttributes(in long startPos, in long endPos, in nsISupports attributes); Unimplemented void setTextContents(in AString text); Attributes Attribute Type Description associatedEditor nsIEditor Returns an editor associated with the accessible. Read only. ...
...Native code only! ...
... cutText
() Deletes a range of text and copies it to the clipboard. void cutText( in long startPos, in long endPos ); Parameters startPos Start offset of the text to be deleted and copied to clipboard. endPos End offset of the text to be copied into the clipboard. Exceptions thrown NS_ERROR_FAILURE Indicates the text cannot be deleted or copied into the clipboard. deleteText
() Deletes a range of text. void deleteText( in long startPos, in long endPos ); Parameters startPos Start offset of the text to be deleted. endPos End offset of the text to be deleted. Exceptions thrown NS_ERROR_FAILURE Indicates the text cannot be deleted. insertText
() Inserts text at the specified position. void insertText( in AString text, in long position ); Parame...
...And 2 more matches
nsIAccessibleRelation
face gives access to an accessibles set of relations. 1.0 66 Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) Note: Be carefull, do not change constants until ATK has a structure to map gecko constants into ATK constants. Method overview nsIAccessible getTarget(in unsigned long index); nsIArray getTargets
(); Attributes Attribute Type Description relationType unsigned long Returns the type of the relation. Read only. targetsCount unsigned long Returns the number of targets for this relation. Read only. Constants Constant Value Description RELATION_NUL 0...
...ted by a target object. RELATION_CONTROLLER_FOR 0x02 This object is interactive and controls some attribute of a target object. RELATION_LABEL_FOR 0x03 This object is label for a target object. RELATION_LABELLED_BY 0x04 This object is labelled by a target object. If the accessible has an nsIAccessible.name
() , you can get the nsIAccessible that it was labelled by in order to get more formatting information. Note: The label and description (see RELATION_DESCRIBED_BY) relations may be used to prevent redundant information from being presented by the screen reader, since the label and description can occur both on their own, and in the name or description fields of an nsIAccessible. ...
...ect is a transient component related to the target object. When this object is activated the target object doesn't lose focus. RELATION_PARENT_WINDOW_OF 0x0d This object is a parent window of the target object. RELATION_DESCRIBED_BY 0x0e This object is described by the target object. If the accessible has an nsIAccessible.description
() , you can get the nsIAccessible that it was described by in order to get more formatting information. Note: The label (see RELATION_LABELLED_BY) and description relations may be used to prevent redundant information from being presented by the screen reader, since the label and description can occur both on their own, and in the name or description fields of an nsIAccessible. ...
...And 2 more matches
nsIAccessibleSelectable
accessible/public/nsIAccessibleSelectable.idlScriptable An interface for the accessibility module and in-process accessibility clients for dealing with getting and changing the selection of accessible nodes. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void addChildToSelection(in long index); void clearSelection
(); nsIArray GetSelectedChildren
(); boolean isChildSelected(in long index); nsIAccessible refSelection(in long index); void removeChildFromSelection(in long index); boolean selectAllSelection
(); Attributes Attribute Type Description selectionCount long The number of accessible children currently selected. Read only. Constants Constant Value Description eSelection_Add 0 eSelection_Remove 1 eSelection_GetSta...
... nsIAccessible refSelection(in long index); void removeChildFromSelection(in long index); boolean selectAllSelection
(); Attributes Attribute Type Description selectionCount long The number of accessible children currently selected. Read only. Constants Constant Value Description eSelection_Add 0 eSelection_Remove 1 eSelection_GetState 2 Methods addChildToSelection
() Adds the specified accessible child of the object to the object's selection. If the specified object is already selected, then it does nothing. void addChildToSelection( in long index ); Parameters index The zero-based accessible child index. ...
... eSelection_GetState 2 Methods addChildToSelection
() Adds the specified accessible child of the object to the object's selection. If the specified object is already selected, then it does nothing. void addChildToSelection( in long index ); Parameters index The zero-based accessible child index. Exceptions thrown NS_ERROR_FAILURE If the specified object is not selectable. clearSelection
() Clears the selection in the object so that no children in the object are selected. void clearSelection
(); Parameters None. GetSelectedChildren
() Returns an nsIArray of the selected nsIAccessible children. nsIArray GetSelectedChildren
(); Parameters None. Return value An nsIArray. isChildSelected
() Determines if the current child of this object is selected. boolean isChildSelected( in long inde...
...And 2 more matches
nsIApplicationCacheService
Note: This method should propagate the entry to other application caches with the same opportunistic namespace; however, this is not currently implemented. void cacheOpportunistically( in nsIApplicationCache cache, in ACString key ); Parameters cache The cache in which the entry is currently cached. key The cache entry'...
...e that should be cached opportunistically. Note: This method should propagate the entry to other application caches with the same opportunistic namespace; however, this is not currently implemented. void cacheOpportunistically( in nsIApplicationCache cache, in ACString key ); Parameters cache The cache in which the entry is currently cached. key The cache entry's key. ...
...ached. key The cache entry's key. chooseApplicationCache
() Tries to find the best application cache to serve a specified resource. nsIApplicationCache chooseApplicationCache( in ACString key ); Parameters key The cache entry key for which to select an application cache. Return value The nsIApplicationCache best able to serve the resource indicated by the key parameter. createApplicationCache
() Creates a new, empty application cache for the specified cache group. nsIApplicationCache createApplicationCache( in ACString group ); Parameters group The cache group for which to create an application cache. Return value The newly-created nsIApplicationCache. deactivateGroup
() Deactivates the currently active cache object for the specified cache group. void deactivateGroup( in ACString g...
...And 2 more matches
nsIApplicationUpdateService
ks. It also provides utilities for selecting and downloading update patches. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview void addDownloadListener(in nsIRequestObserver listener); AString downloadUpdate(in nsIUpdate update, in boolean background); void pauseDownload
(); void removeDownloadListener(in nsIRequestObserver listener); nsIUpdate selectUpdate([array, size_is(updateCount)] in nsIUpdate updates, in unsigned long updateCount); Attributes Attribute Type Description backgroundChecker nsIUpdateChecker The update checker being used for background update checking. Read only. canApplyUpdates boolean true if the Update Service can download and ins...
...e application is running on. Read only. canUpdate boolean true if the update service is able to download and install updates. This depends on whether or not the current user has the necessary access privileges for the install directory. Read only. Obsolete since Gecko 1.9.1.7pre isDownloading boolean true if a download is in progress, otherwise false. Read only. Methods addDownloadListener
() Adds a listener that receives progress and state information about the update that is currently being downloaded. This information is most commonly used to update a user interface that informs the user as to the status of an update. void addDownloadListener( in nsIRequestObserver listener ); Parameters listener An object implementing nsIRequestObserver and optionally nsIProgressEventSink that...
... being downloaded. This information is most commonly used to update a user interface that informs the user as to the status of an update. void addDownloadListener( in nsIRequestObserver listener ); Parameters listener An object implementing nsIRequestObserver and optionally nsIProgressEventSink that will be notified of state and progress information as the update is downloaded. downloadUpdate
() Starts downloading a software update. AString downloadUpdate( in nsIUpdate update, in boolean background ); Parameters update An nsIUpdate object indicating the update to download. background true to download the update in the background or false to download it in the foreground. Return value A string indicating the status of the update upon return: "downloading" The update is being d...
...And 2 more matches
nsIAsyncOutputStream
herits from: nsIOutputStream Last changed in Gecko 1.7 If an output stream is non-blocking, it may return NS_BASE_STREAM_WOULD_BLOCK when written to. The caller must then wait for the stream to become writable. If the stream implements nsIAsyncOutputStream, then the caller can use this interface to request an asynchronous notification when the stream becomes writable or closed (via the AsyncWait
() method). While this interface is almost exclusively used with non-blocking streams, it is not necessary that nsIOutputStream.isNonBlocking
() return true. Nor is it necessary that a non-blocking nsIOutputStream implementation also implement nsIAsyncOutputStream. Method overview void asyncWait(in nsIOutputStreamCallback aCallback, in unsigned long aFlags, in unsigned long aRequestedCount, in nsI...
...t necessary that a non-blocking nsIOutputStream implementation also implement nsIAsyncOutputStream. Method overview void asyncWait(in nsIOutputStreamCallback aCallback, in unsigned long aFlags, in unsigned long aRequestedCount, in nsIEventTarget aEventTarget); void closeWithStatus(in nsresult reason); Constants Constant Value Description WAIT_CLOSURE_ONLY (1<<0) If passed to asyncWait
(), this flag overrides the default behavior, causing the OnOutputStreamReady notification to be suppressed until the stream becomes closed (either as a result of closeWithStatus
()/close being called on the stream or possibly due to some error in the underlying stream). Methods asyncWait
() Asynchronously wait for the stream to be writable or closed. The notification is one-shot, meaning that each...
...It is safe to call asyncWait again from the notification handler. This method may be called at any time (even if write has not been called). In other words, this method may be called when the stream already has room for more data. ...
...And 2 more matches
nsICRLManager
security/manager/ssl/public/nsICRLManager.idlScriptable Please add a summary to this article. ...
... 1.7 Method overview wstring computeNextAutoUpdateTime(in nsICRLInfo info, in unsigned long autoUpdateType, in double noOfDays); void deleteCrl(in unsigned long crlIndex); nsIArray getCrls
(); void importCrl([array, size_is(length)] in octet data, in unsigned long length, in nsIURI uri, in unsigned long type, in boolean doSilentDownload, in wstring crlKey); void rescheduleCRLAutoUpdate
(); boolean updateCRLFromURL(in wstring url, in wstring key); Constants Constant Value Description TYPE_AUTOUPDATE_TIME_BASED 1 TYPE_AUTOUPDATE_FREQ_BASED 2 Methods computeNextAutoUpdateTime
() wstring computeNextAutoUpdateTime( in nsICRLInfo info, in unsigned long autoUpdateType, in double noOfDays ); Parameters info autoUpdateType noOfDays Return value deleteCrl
() De...
... Description TYPE_AUTOUPDATE_TIME_BASED 1 TYPE_AUTOUPDATE_FREQ_BASED 2 Methods computeNextAutoUpdateTime
() wstring computeNextAutoUpdateTime( in nsICRLInfo info, in unsigned long autoUpdateType, in double noOfDays ); Parameters info autoUpdateType noOfDays Return value deleteCrl
() Delete the crl. void deleteCrl( in unsigned long crlIndex ); Parameters crlIndex getCrls
() Get a list of Crl entries in the DB. nsIArray getCrls
(); Parameters None. Return value importCrl
() Import a CRL into the certificate database. void importCrl( [array, size_is(length)] in octet data, in unsigned long length, in nsIURI uri, in unsigned long type, in boolean doSilentDownload, in wstring crlKey ); Parameters data length uri type doSilentDownload crlKey reschedu...
...And 2 more matches
nsICacheService
Starting in Gecko 2.0, cache I/O is handled asynchronously. Method overview nsICacheSession createSession(in string clientID, in nsCacheStoragePolicy storagePolicy, in boolean streamBased); ACString createTemporaryClientID(in nsCacheStoragePolicy storagePolicy); Obsolete since Gecko 1.9.2 void evictEntries(in nsCacheStoragePolicy storagePolicy); void init
(); Obsolete since Gecko 1.8 void shutdown
(); Obsolete since Gecko 1.8 void visitEntries(in nsICacheVisitor visitor); Attributes Attribute Type Description cacheIOTarget nsIEventTarget The event target for cache I/O operation notifications. Read only. Methods createSession
() This method creates a cache session. A cache session represe...
...policy will not be searched when opening entries from the returned session. streamBased Indicates whether or not the data being cached can be represented as a stream. The storagePolicy must be consistent with the value of this field. For example, a non-stream-based cache entry can only have a storage policy of STORE_IN_MEMORY. Return value Returns a new cache session. createTemporaryClientID
() Obsolete since Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. This method creates and returns a unique, temporary cache client ID. This is used by the offline cache. The offline cache lets clients accumulate entries in a tempo...
... 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 method creates and returns a unique, temporary cache client ID. This is used by the offline cache. The offline cache lets clients accumulate entries in a temporary client and merge them in as a group using nsIOfflineCacheSession.mergeTemporaryClient
(). ACString createTemporaryClientID( in nsCacheStoragePolicy storagePolicy ); Parameters storagePolicy The cache storage policy. Return value Returns a newly created unique, temporary cache client ID. Exceptions thrown NS_ERROR_NOT_IMPLEMENTED This method is deprecated. evictEntries
() This method evicts all entries in all devices implied by the storage policy. Note: This functi...
...And 2 more matches
nsIClassInfo
classDescription string A human readable string naming the class, or null. Read only. classID nsCIDPtr A classID through which an instance of this class can be created, or null. If the flags attribute has the SINGLETON bit set, then the value of this attribute specifies a ClassID through which this class can be accessed as a service using nsIServiceManager.getService
(). Read only. classIDNoAlloc nsCID A classID through which an instance of this class can be created, or null. If the flags attribute has the SINGLETON bit set, then the value of this attribute specifies a ClassID through which this class can be accessed as a service using nsIServiceManager.getService
(). This attribute is similar to the classID attribute; however, this attri...
... NS_ERROR_NOT_AVAILABLE If the class does not have a ClassID contractID string A contractID through which an instance of this class can be created, or null. If the flags attribute has the SINGLETON bit set, then the value of this attribute specifies a ContractID through which this class may be accessed as a service using nsIServiceManager.getServiceByContractID
(). Read only. flags PRUint32 Specifies various binary properties of this class. Possible values for this attribute include a bit-wise combination of the constants Read only. implementationLanguage Obsolete since Gecko 40 PRUint32 The language type in which this class is implemented. See nsIProgrammingLanguage.Constants for a list of possible values. Read only. C...
...D for consumers of these flags. No implementor of this interface should ever return flags with this bit set. EAGER_CLASSINFO 1 << 5 This flag is designed for use with nsGenericFactory and can be set in nsModuleComponentInfo::mFlags. It has no meaning when returned from the flags attribute of a nsIClassInfo implementation. ...
...And 2 more matches
nsIContentSecurityPolicy
ent so it doesn't load any sub-content until either it knows that a Content Security Policy is ready or will not be used. policy AString A read-only string version of the policy for debugging. Read only. reportOnlyMode boolean When set to true, content load-blocking and fail-closed are disabled: Content Security Policy will only send reports, and not modify behavior. ...
... reports, and not modify behavior. Methods permitsAncestry
() Verifies ancestry as permitted by the policy. Calls to this may trigger violation reports when queried, so this value should not be cached. boolean permitsAncestry( in nsIDocShell docShell ); Parameters docShell Containing the protected resource. Return value true if the frame's ancestors are all permitted by policy. refinePolicy
() Updates the policy currently stored in the Content Security Policy to be "refined" or tightened by the one specified in the string policyString. ...
... docShell Containing the protected resource. Return value true if the frame's ancestors are all permitted by policy. refinePolicy
() Updates the policy currently stored in the Content Security Policy to be "refined" or tightened by the one specified in the string policyString. void refinePolicy( in AString policyString, in nsIURI selfURI ); Parameters policyString selfURI scanRequestData
() Called after the Content Security Policy object is created to fill in the appropriate request and request header information needed in case a report needs to be sent. void scanRequestData( in nsIHttpChannel aChannel ); Parameters aChannel sendReports
() Manually triggers violation report sending given a URI and reason. The URI may be null, in which case "self" is sent. void sendReports( in...
...And 2 more matches
nsICookieManager2
nsICookieService is the normal way to do this. This method is something of a back door. void add( in AUTF8String aHost, in AUTF8String aPath, in ACString aName, in ACString aValue, in boolean aIsSecure, in boolean aIsHttpOnly, in boolean aIsSession, in PRInt64 aExpiry ); Parameters aHost The host or domain for which the cookie is set. presence of a leading d...
...aValue The cookie data. aIsSecure true if the cookie should only be sent over a secure connection. aIsHttpOnly true if the cookie should only be sent to, and can only be modified by, an HTTP connection. aIsSession true if the cookie should exist for the current session only. aExpiry Holds the expiration date, in seconds since the epoch. Only relevant if aIsSession is false. cookieExists
() Returns whether or not a matching cookie already exists. boolean cookieExists( in nsICookie2 aCookie ); Parameters aCookie The cookie to look for. Return value Returns true if a cookie was found which matches the host, path, and name fields of aCookie. countCookiesFromHost
() Returns the number of cookies that would be returned to a given host. This ignores the cookie flags isDomai...
...hile a cookie for "my.weather.yahoo.com" would not. unsigned long countCookiesFromHost( in AUTF8String aHost ); Parameters aHost The host string to look for, such as "google.com". This should consist only of the host portion of the URI and should not contain a leading dot, port number, or other information. Return value The number of matching cookies found. findMatchingCookie
() Obsolete since Gecko 1.9 (Firefox 3) Find whether a matching cookie already exists, and how many cookies a given host has already set. This is useful when e.g. prompting the user whether to accept a given cookie. boolean findMatchingCookie( in nsICookie2 aCookie, out unsigned long aCountFromHost ); Parameters aCookie The cookie to look for. aCountFromHost The number...
...And 2 more matches
nsIDOMChromeWindow
dom/interfaces/base/nsIDOMChromeWindow.idlScriptable This interface is implemented on the window object in chrome. Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview void beginWindowMove(in nsIDOMEvent mouseDownEvent); void getAttention
(); void getAttentionWithCycleCount(in long aCycleCount); void maximize
(); void minimize
(); void notifyDefaultButtonLoaded(in nsIDOMElement defaultButton); void restore
(); void setCursor(in DOMString cursor); Attributes Attribute Type Description browserDOMWindow nsIBrowserDOMWindow The related nsIBrowserDOMWindow instance which provides access to yet another layer of utility functions by chrome script. It will be null for DOMWindows not corresponding to b...
...OMString Obsolete since Gecko 1.9.1 windowState unsigned short Returns current window state, the value is one of STATE_* constants. Read only. Constants Constant Value Description STATE_MAXIMIZED 1 The window is maximized. STATE_MINIMIZED 2 The window is minimized. STATE_NORMAL 3 The window is normal. STATE_FULLSCREEN 4 The window is in full screen mode. Methods beginWindowMove
() On some operating systems, we must allow the window manager to handle window dragging. This method tells the window manager to start dragging the window. This method will fail unless called while the left mouse button is held down, callers must check this. void beginWindowMove( in nsIDOMEvent mouseDownEvent ); Parameters mouseDownEvent Exceptions thrown NS_ERROR_NOT_IMPLEMENTED If the oper...
...ager to handle window dragging. This method tells the window manager to start dragging the window. This method will fail unless called while the left mouse button is held down, callers must check this. void beginWindowMove( in nsIDOMEvent mouseDownEvent ); Parameters mouseDownEvent Exceptions thrown NS_ERROR_NOT_IMPLEMENTED If the operating system does not support this method. getAttention
() void getAttention
(); Parameters None. getAttentionWithCycleCount
() Same as getAttention method excepting that this can specify the maximum number of times to animate the window per system conventions. void getAttentionWithCycleCount( in long aCycleCount ); Parameters aCycleCount The maximum number of times to animate the window per system conventions. If set to -1, cycles indefinitely until ...
...And 2 more matches
nsIDOMStorage2
be accessed by the same origin that created the items in the first place. A DOM window's local storage object can be retrieved from the window's localStorage attribute. dom/public/idl/storage/nsIDOMStorage2.idlScriptable Please add a summary to this article. ...
... 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) Inherits from: nsISupports Method overview void clear
(); DOMString getItem(in DOMString key); DOMString key(in unsigned long index); void removeItem(in DOMString key); void setItem(in DOMString key, in DOMString data); Attributes Attribute Type Description length unsigned long The number of keys stored in local storage. Methods clear
() Clears the contents of this storage context; this removes all values bound to the domain or origin. void clear
(); Parameters None. getItem
() Returns from local storage the data corresponding to the specified key. DOMString getItem( in DOMString key ); Parameters key The key for which data should be returned. Return value A string containing the data corresponding to the specified key, or nul...
...xt; this removes all values bound to the domain or origin. void clear
(); Parameters None. getItem
() Returns from local storage the data corresponding to the specified key. DOMString getItem( in DOMString key ); Parameters key The key for which data should be returned. Return value A string containing the data corresponding to the specified key, or null if no data exists for the given key. key
() Returns the key for the item stored at the specified index in the data store. DOMString key( in unsigned long index ); Parameters index The index for which the corresponding key should be returned. Return value A string containing the requested key. Exceptions thrown INDEX_SIZE_ERRThere is no key at the specified index. ...
...And 2 more matches
nsIDebug
xpcom/base/nsIDebug.idlScriptable Provides debugging support for scripted languages, such as JavaScript, Java, Python, Perl, and so forth. ...
... scripted languages, such as JavaScript, Java, Python, Perl, and so forth. Inherits from: nsISupports Last changed in Gecko 1.7 Note: C/C++ consumers who are planning to use the nsIDebug interface with the @mozilla.org/xpcom;1 contract should use NS_DebugBreak
() from XPCOM glue instead, or alternatively the NS_ABORT, NS_ASSERTION, NS_BREAK, and NS_WARNING macros, which also call NS_DebugBreak
() if used in a debugging build. Method overview void abort(in string aFile, in long aLine); void assertion(in string aStr, in string aExpr, in string aFile, in long aLine); void break(in string aFile, in long aLine); void warning(in string aStr, in string aFile, in long aLine); Methods abort
() Requests the process to trigger a fatal abort. void abort( in string aFile, in long aLine ...
...d assertion(in string aStr, in string aExpr, in string aFile, in long aLine); void break(in string aFile, in long aLine); void warning(in string aStr, in string aFile, in long aLine); Methods abort
() Requests the process to trigger a fatal abort. void abort( in string aFile, in long aLine ); Parameters aFile File containing abort request. aLine Line number of abort request. assertion
() Shows an assertion and triggers optional behavior based on the XPCOM_DEBUG_BREAK environment variable, defaulting to calling break
() on Windows and OS/2 and warning on other platforms. void assertion( in string aStr, in string aExpr, in string aFile, in long aLine ); Parameters aStr assertion message. aExpr Expression that failed. aFile File containing assertion. aLine Line number of as...
...And 2 more matches
nsIDynamicContainer
ed to its service. Method overview void onContainerMoved(in long long aItemId, in long long aNewParent, in long aNewIndex); void onContainerNodeClosed(in nsINavHistoryContainerResultNode aContainer); void onContainerNodeOpening(in nsINavHistoryContainerResultNode aContainer, in nsINavHistoryQueryOptions aOptions); void onContainerRemoving(in long long aItemId); Methods onContainerMoved
() This method is called when the given container has just been moved, in case the service needs to do any bookkeeping. It is called after the container has been moved. void onContainerMoved( in long long aItemId, in long long aNewParent, in long aNewIndex ); Parameters aItemId The item-id of the container item. aNewParent The item of the new parent folder for the container. aNewIndex The in...
...keeping. It is called after the container has been moved. void onContainerMoved( in long long aItemId, in long long aNewParent, in long aNewIndex ); Parameters aItemId The item-id of the container item. aNewParent The item of the new parent folder for the container. aNewIndex The index at which the container will be inserted, or "-1" to append to the end of the list. onContainerNodeClosed
() This method is called when the given container has just been collapsed so that the service can do any necessary cleanup. This is not guaranteed to get called. In particular, if the query just goes away, you will not get this call. This only happens when the container itself goes from the open state to the closed state. A service with large numbers of dynamically populated items might use this to ...
...s of dynamically populated items might use this to do some cleanup so those items don't hang around. void onContainerNodeClosed( in nsINavHistoryContainerResultNode aContainer ); Parameters aContainer The container node of the container being closed. The service need not worry about removing any created nodes, they will be automatically removed when this call completes. onContainerNodeOpening
() This method is called when the given container node is about to be populated so that the service can populate the container if necessary. Note: All result nodes implement a property bag if you need to store state. void onContainerNodeOpening( in nsINavHistoryContainerResultNode aContainer, in nsINavHistoryQueryOptions aOptions ); Parameters aContainer The container node for the container be...
...And 2 more matches
nsIEditor
t doc, in nsIContent aRoot, in nsISelectionController aSelCon, in unsigned long aFlags); void setAttributeOrEquivalent(in nsIDOMElement element, in AString sourceAttrName, in AString sourceAttrValue, in boolean aSuppressTransaction); void removeAttributeOrEquivalent(in nsIDOMElement element, in DOMString sourceAttrName, in boolean aSuppressTransaction); void postCreate
(); void preDestroy(in boolean aDestroyingFrames); Selected Content Removal void deleteSelection(in short action, in short stripWrappers); Document Info and File Methods void resetModificationCount
(); long getModificationCount
(); void incrementModificationCount(in long aModCount); void incrementModificationCount(in long aModCoun...
...t(in long aModCount); Transaction Methods void doTransaction(in nsITransaction txn); void enableUndo(in boolean enable); void undo(in unsigned long count); void canUndo(out boolean isEnabled, out boolean canUndo); void redo(in unsigned long count); void canRedo(out boolean isEnabled, out boolean canRedo); void beginTransaction
(); void endTransaction
(); void beginPlaceHolderTransaction(in nsIAtom name); void endPlaceHolderTransaction
(); boolean shouldTxnSetSelection
(); void setShouldTxnSetSelection(in boolean should); Inline Spellchecking Methods nsIInlineSpellChecker getInlineSpellChecker(in boolean autoCreate); void syncRealTimeSpell
(); voi...
...; void endPlaceHolderTransaction
(); boolean shouldTxnSetSelection
(); void setShouldTxnSetSelection(in boolean should); Inline Spellchecking Methods nsIInlineSpellChecker getInlineSpellChecker(in boolean autoCreate); void syncRealTimeSpell
(); void setSpellcheckUserOverride(in boolean enable); Clipboard Methods void cut
(); boolean canCut
(); void copy
(); boolean canCopy
(); void paste(in long aSelectionType); boolean canPaste(in long aSelectionType); Selection Methods void selectAll
(); void beginningOfDocument
(); void endOfDocument
(); Drag/Drop Methods boolean canDrag(in nsIDOMEvent aEvent); void doDrag(in nsI...
...And 2 more matches
nsIErrorService
eKey(in nsresult error); void registerErrorStringBundle(in short errorModule, in string stringBundleURL); void registerErrorStringBundleKey(in nsresult error, in string stringBundleKey); void unregisterErrorStringBundle(in short errorModule); void unregisterErrorStringBundleKey(in nsresult error); Methods getErrorStringBundle
() Retrieves a string bundle URL for an error module. string getErrorStringBundle( in short errorModule ); Parameters errorModule The module for which the string bundle is registered. Error modules are obtained from nsresult code with NS_ERROR_GET_MODULE. Return value The URL of the string bundle registered for that module. getErrorStringBundleKey
() Retrieves a key in a string bun...
...d for the specified nsresult, then the caller should use the nsresult's code (obtained with NS_ERROR_GET_CODE) instead. string getErrorStringBundleKey( in nsresult error ); Parameters error The nsresult for which the string bundle key is to be retrieved. Return value The key to use to retrieve the error string from the nsresult's module's string bundle. registerErrorStringBundle
() Registers a string bundle URL for an error module. void registerErrorStringBundle( in short errorModule, in string stringBundleURL ); Parameters errorModule The module for which the string bundle is to be registered. Should be one of the modules listed in xpcom/base/nsError.h, such as NS_ERROR_MODULE_STORAGE. stringBundleURL The URL of the string bundle to regist...
...le. void registerErrorStringBundle( in short errorModule, in string stringBundleURL ); Parameters errorModule The module for which the string bundle is to be registered. Should be one of the modules listed in xpcom/base/nsError.h, such as NS_ERROR_MODULE_STORAGE. stringBundleURL The URL of the string bundle to register for the module. registerErrorStringBundleKey
() Registers a key in a string bundle for an nsresult error code. void registerErrorStringBundleKey( in nsresult error, in string stringBundleKey ); Parameters error The nsresult for which the string bundle key is to be registered. stringBundleKey The key that should be used to retrieve the error string from string bundle for the given nsresult. unregisterErrorStri...
...And 2 more matches
nsIFeedProgressListener
void handleEntry( in nsIFeedEntry entry, in nsIFeedResult result ); Parameters entry Pointer to an nsIFeedEntry containing information about the entry that was ju...
...sIFeedEntry entry, in nsIFeedResult result); void handleFeedAtFirstEntry(in nsIFeedResult result); void handleStartFeed(in nsIFeedResult result); void reportError(in AString errorText, in long lineNumber, in boolean bozo); Methods handleEntry
() Called after each entry or item is processed. If the document is a standalone item or entry, the HandleFeedAtFirstEntry
() method will not already have been called, and the received nsIFeedEntry will have a null parent value. void handleEntry( in nsIFeedEntry entry, in nsIFeedResult result ); Parameters entry Pointer to an nsIFeedEntry containing information about the entry that was just processed. result Pointer to an nsIFeedResult containing the current information about the feed being processed. han...
...ready have been called, and the received nsIFeedEntry will have a null parent value. void handleEntry( in nsIFeedEntry entry, in nsIFeedResult result ); Parameters entry Pointer to an nsIFeedEntry containing information about the entry that was just processed. result Pointer to an nsIFeedResult containing the current information about the feed being processed. handleFeedAtFirstEntry
() Called when the first entry or item in the feed is encountered. In Atom, all feed data is required to precede the entries; in RSS, this isn't required but is typically the case. In other words, by the time this method is called, it is most likely that most or all of the feed-level metadata has been processed and is available in the received nsIFeedResult object. Note: If the feed type is one of...
...And 2 more matches
nsIFileProtocolHandler
Should only be called on fi...
...); nsIURI readURLFile(in nsIFile file); Methods getFileFromURLSpec
() Converts the URL string into the corresponding nsIFile if possible. A local file will be created if the URL string begins with file://. nsIFile getFileFromURLSpec( in AUTF8String url ); Parameters url The url string to convert. Return value A reference to a new nsIFile object. getURLSpecFromActualFile
() Converts the nsIFile to the corresponding URL string. Should only be called on files which are not directories. Otherwise identical to getURLSpecFromFile
(), but is usually more efficient. Warning: This restriction may not be enforced at runtime! AUTF8String getURLSpecFromActualFile( in nsIFile file ); Parameters file The nsIFile to convert. Return value Corresponding url string. T...
...led on files which are not directories. Otherwise identical to getURLSpecFromFile
(), but is usually more efficient. Warning: This restriction may not be enforced at runtime! AUTF8String getURLSpecFromActualFile( in nsIFile file ); Parameters file The nsIFile to convert. Return value Corresponding url string. The resulting string may contain URL-escaped characters. getURLSpecFromDir
() Converts the nsIFile to the corresponding URL string. Should only be called on files which are directories. Otherwise identical to getURLSpecFromFile
(), but is usually more efficient. WARNING: This restriction may not be enforced at runtime! AUTF8String getURLSpecFromDir( in nsIFile file ); Parameters file The nsIFile to convert. Return value Corresponding url string. The resulting s...
...And 2 more matches
nsIGlobalHistory3
lobalHistory2, but was split off during the transition to Places. Method overview void addDocumentRedirect(in nsIChannel aOldChannel, in nsIChannel aNewChannel, in PRInt32 aFlags, in boolean aTopLevel); unsigned long getURIGeckoFlags(in nsIURI aURI); void setURIGeckoFlags(in nsIURI aURI, in unsigned long aFlags); Methods addDocumentRedirect
() Notifies the history system that the page loading via aOldChannel redirected to aNewChannel. Implementations should generally add the URI for aOldChannel to history for link coloring, but are advised not to expose it in the history user interface. This function is preferred if nsIGlobalHistory3 is available. Otherwise, nsIGlobalHistory2.addURI
() should be called with redirect=true. This function ...
...ge loading via aOldChannel redirected to aNewChannel. Implementations should generally add the URI for aOldChannel to history for link coloring, but are advised not to expose it in the history user interface. This function is preferred if nsIGlobalHistory3 is available. Otherwise, nsIGlobalHistory2.addURI
() should be called with redirect=true. This function is preferred to nsIGlobalHistory2.addURI
() because it provides more information (including the redirect destination, channels involved, and redirect flags) to the history implementation. For implementors of nsIGlobalHistory3: The history implementation is responsible for sending NS_LINK_VISITED_EVENT_TOPIC to observers for redirect pages. This notification must be sent for history consumers for all non-redirect pages. The other params to ...
...annels involved, and redirect flags) to the history implementation. For implementors of nsIGlobalHistory3: The history implementation is responsible for sending NS_LINK_VISITED_EVENT_TOPIC to observers for redirect pages. This notification must be sent for history consumers for all non-redirect pages. The other params to this function are the same as those for nsIChannelEventSink.OnChannelRedirect
(). Implementors who wish to implement this interface but rely on nsIGlobalHistory2.addURI
() for redirect processing may throw NS_ERROR_NOT_IMPLEMENTED from this method. If they do so, then callers must call nsIGlobalHistory2.addURI
() upon getting the NS_ERROR_NOT_IMPLEMENTED result. void addDocumentRedirect( in nsIChannel aOldChannel, in nsIChannel aNewChannel, in PRInt32 aFlags, in boolean...
...And 2 more matches
nsIInstallLocation
t from these values each time you create a new Install Location. Offsetting can be brittle but you should know what Install Locations are being defined for your own application. ...
... Methods getIDForLocation
() Retrieves the GUID for an item at the specified location. Note: This function makes no promises about whether or not this path is actually maintained by this Install Location. AString getIDForLocation( in nsIFile file ); Parameters file The location where an item might live. Return value The ID for an item that might live at the location specified. getItemFile
() Gets a nsIFile object for a file within an item's directory structure. nsIFile getItemFile( in AString id, in AString path ); Parameters id The GUID of the item. path The path to the file beneath an Extension's directory. Return value A file object at the requested location. The file does not necessarily have to exist. getItemLocation
() Gets the directory that contains an item. nsIFile get...
...path ); Parameters id The GUID of the item. path The path to the file beneath an Extension's directory. Return value A file object at the requested location. The file does not necessarily have to exist. getItemLocation
() Gets the directory that contains an item. nsIFile getItemLocation( in AString id ); Parameters id The GUID of the item. Return value The location of the item. getStageFile
() Returns the most recently staged package (for example the last XPI or JAR in a directory) for an item and removes items that do not qualify. ...
...And 2 more matches
nsIJetpack
.3 / SeaMonkey 2.1) Method overview void sendMessage(in AString aMessageName /* [optional] in jsval v1, [optional] in jsval v2, ... */); void registerReceiver(in AString aMessageName, in jsval aReceiver); void unregisterReceiver(in AString aMessageName, in jsval aReceiver); void unregisterReceivers(in AString aMessageName); void evalScript(in AString aScript); nsIVariant createHandle
(); void destroy
(); Methods sendMessage
() This method asynchronously sends a message to the Jetpack process. void sendMessage( in AString aMessageName, [optional] in jsval v1, Optional [optional] in jsval v2, Optional ... ); Parameters aMessageName The name of the message to send. v1, v2, ... Optional JavaScript values to send with the message; they must be either JSON-serializable ty...
...Note: Multiple callbacks may be registered for the same message; they will all be triggered. void registerReceiver( in AString aMessageName, in jsval aReceiver ); Parameters aMessageName The name of the message from the Jetpack process on which the callback is triggered. ...
...g aMessageName, in jsval aReceiver ); Parameters aMessageName The name of the message from the Jetpack process on which the callback is triggered. aReceiver A JavaScript function. The first argument passed to it is the name of the message, and all arguments following it are either JSON-serializable types or handles. If the message was sent synchronously from the Jetpack process via callMessage
(), then the return value of this function is passed back to the Jetpack process. unregisterReceiver
() This unregisters a callback previously registered with registerReceiver
() void unregisterReceiver( in AString aMessageName, in jsval aReceiver ); Parameters aMessageName The name of the message on which the callback should no longer be triggered. aReceiver The JavaScript function that should...
...And 2 more matches
nsIMsgCustomColumnHandler
lease add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Inherits from: nsITreeView This interface is meant to be implemented by extensions, as shown in the tutorial. The interface inherits from nsITreeView, however when you're implementing a custom handler in Javascript its not necessary to implement all of nsITreeView's methods. You must implement: nsITreeView.isEditable
() nsITreeView.GetCellProperties
() nsITreeView.GetImageSrc
() nsITreeView.GetCellText
() nsITreeView.cycleCell
() nsIMsgCustomColumnHandler.getSortStringForRow
() nsIMsgCustomColumnHandler.getSortLongForRow
() nsIMsgCustomColumnHandler.isString
() and optionally: nsITreeView.GetRowProperties
() From C++ you must implement all of nsITreeView and nsIMsgCustomColumnHandler. Example Implementation An example ...
...rom C++ you must implement all of nsITreeView and nsIMsgCustomColumnHandler. ...
...on(aRow, aCol) { }, getSortStringForRow: function(aHdr) { return ""; }, isString: function
() {return true;}, getCellProperties: function(aRow, aCol, aProps) { }, getRowProperties: function(aRow, aProps) { }, getImageSrc: function(aRow, aCol) {return null;}, getSortLongForRow: function(aHdr) {return 0;} } to attach it use the nsIMsgDBView.addColumnHandler
() method (recall gDBView is the global nsIMsgDBView in Thunderbird): gDBView.addColumnHandler("newColumn", columnHandler); after which it can be retrieved using the nsIMsgDBView.getColumnHandler
() method: var handler = gDBView.getColumnHandler("newColumn"); and removed using the nsIMsgDBView.removeColumnHandler
() method: gDBView.removeColumnHandler("newColumn"); Method overview AString get...
...And 2 more matches
nsIMsgFilterList
n nsIMsgFilterList::shouldDownloadAllHeaders filterCount readonly attribute unsigned long nsIMsgFilterList::filterCount loggingEnabled attribute boolean nsIMsgFilterList::loggingEnabled defaultFile attribute nsILocalFile nsIMsgFilterList::defaultFile logStream attribute nsIOutputStream nsIMsgFilterList::logStream logURL readonly attribute ACString nsIMsgFilterList::logURL Methods getFilterAt
() nsIMsgFilter nsIMsgFilterList::getFilterAt (in unsigned long filterIndex ) getFilterNamed
() nsIMsgFilter nsIMsgFilterList::getFilterNamed (in AString filterName) setFilterAt
() nsIMsgFilter nsIMsgFilterList::setFilterAt ( in unsigned long filterIndex, in nsIMsgFilter filter ) removeFilter
() void nsIMsgFilterList::removeFilter (in nsIMsgFilter filter) removeFilterA...
...nsIMsgFilter nsIMsgFilterList::getFilterAt (in unsigned long filterIndex ) getFilterNamed
() nsIMsgFilter nsIMsgFilterList::getFilterNamed (in AString filterName) setFilterAt
() nsIMsgFilter nsIMsgFilterList::setFilterAt ( in unsigned long filterIndex, in nsIMsgFilter filter ) removeFilter
() void nsIMsgFilterList::removeFilter (in nsIMsgFilter filter) removeFilterAt
() void nsIMsgFilterList::removeFilterAt (in unsigned long filterIndex) moveFilterAt
() void nsIMsgFilterList::moveFilterAt ( in unsigned long filterIndex, in nsMsgFilterMotionValue motion ) insertFilterAt
() void nsIMsgFilterList::insertFilterAt ( in unsigned long filterIndex, in nsIMsgFilter filter ) moveFilter
() void nsIMsgFilterList::moveFil...
...FilterList::moveFilterAt ( in unsigned long filterIndex, in nsMsgFilterMotionValue motion ) insertFilterAt
() void nsIMsgFilterList::insertFilterAt ( in unsigned long filterIndex, in nsIMsgFilter filter ) moveFilter
() void nsIMsgFilterList::moveFilter ( in nsIMsgFilter filter, in nsMsgFilterMotionValue motion ) createFilter
() nsIMsgFilter nsIMsgFilterList::createFilter ( in AString name ) saveToFile
() void nsIMsgFilterList::saveToFile ( in nsIOutputStream stream ) parseCondition
() void nsIMsgFilterList::parseCondition ( in nsIMsgFilter aFilter, in string condition ) saveToDefaultFile
() void nsIMsgFilterList::saveToDefaultFile ( ) applyFiltersToHdr
() void nsIMsgFilterList::applyFiltersToHdr ( ...
...And 2 more matches
nsINavHistoryQuery
rom: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) The nsINavHistoryQuery is not intended to be a super-general query mechanism. This was designed so that most queries can be done in only one SQL query. ...
...list, only unique tags are returned. When called as a getter, this returns an array of strings sorted in ascending lexicographical (alphabetical) order. This array may be empty, in which case no filtering by tags is performed. To search for items that are tagged with any given tags instead of all, multiple queries may be passed to the nsINavHistoryService method nsINavHistoryService.executeQueries
(). tagsAreNot boolean If true, the results include only items that are not tagged with the specified tags. If false, only tags in the tags list are included in the results. uri nsIURI This is a URI to match, to, for example, find out every time you visited a given URI. Use uriIsPrefix to control whether this is an exact match. uriIsPrefix boolean Controls the interpretation of uri. When uns...
...y time. TIME_RELATIVE_TODAY 1 The time is relative to this morning at midnight. Normally used for queries relative to today. For example, a "past week" query would be (today-6 days -> today+1 day). TIME_RELATIVE_NOW 2 The time is relative to right now. Note: PRTime is in MICROseconds since 1 Jan 1970. JavaScript date objects are expressed in MILLIseconds since 1 Jan 1970. Methods getFolders
() This method retrieves all the folders with the folder count. void getFolders( [optional] out unsigned long count, [retval,array,size_is(count)] out long long folders ); Parameters count Optional The count of the folders. This optional parameter was required prior to Gecko 2.0. folders The retrieved folders. setFolders
() This method sets the folders with the given folder count. void se...
...And 2 more matches
nsIPlacesView
n. Rather, each view is responsible for translating its own selection format into one the controller can understand. Views do this, and other things, by implementing the nsIPlacesView interface. Note: nsIPlacesView does not exist in IDL at the moment. It's currently implemented directly on each of the built-in Places views. Method overview nsINavHistoryResultNode[] getDragableSelection
(); nsINavHistoryResultNode[][] getRemovableSelectionRanges
(); nsINavHistoryResult getResult
(); nsINavHistoryContainerResultNode getResultNode
(); nsINavHistoryResultNode[] getSelectionNodes
(); void selectAll
(); Attributes Attribute Type Description hasSelection boolean Whether or not there are selected items. Read onl...
...n. Read only. place string TheURI (as a string) of the root Place that the view displays. This may be modified dynamically to update the view. See Displaying Places information using views for examples. selectedNode nsINavHistoryResultNode The selected node in the view. If there are multiple selected nodes, this is null. Read only. Methods getDragableSelection
() Returns an array of selected nsINavHistoryResultNode objects that can be dragged from the view. nsINavHistoryResultNode[] getDragableSelection
(); Parameters None. Return value An array of nsINavHistoryResultNode objects. getRemovableSelectionRanges
() Returns an array whose elements are themselves arrays of nsINavHistoryResultNode objects that can be removed from the view. Each inner arra...
...Node[] getDragableSelection
(); Parameters None. Return value An array of nsINavHistoryResultNode objects. getRemovableSelectionRanges
() Returns an array whose elements are themselves arrays of nsINavHistoryResultNode objects that can be removed from the view. Each inner array represents a contiguous range of nodes that can be removed. nsINavHistoryResultNode[][] getRemovableSelectionRanges
(); Parameters None. Return value An array of arrays of nsINavHistoryResultNode objects. getResult
() Returns the nsINavHistoryResult object that the view displays. nsINavHistoryResult getResult
(); Parameters None. Return value The nsINavHistoryResult object that the view displays. getResultNode
() Returns the root node, an nsINavHistoryContainerResultNode object, of the view's result. ...
...And 2 more matches
nsIPrincipal
This means that codebase principals are only allowed to load resources from the same domain, the system principal is allowed to load anything, and null principals are not allowed to load anything. Note: Prior to Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1), thi...
...Principals are considered equal if they are the same principal, they have the same origin, or have the same certificate fingerprint ID. boolean equals( in nsIPrincipal other ); Parameters other The other principal to compare against. Return value true if the two principals are equivalent; otherwise false. Native cod...
...n equals( in nsIPrincipal other ); Parameters other The other principal to compare against. Return value true if the two principals are equivalent; otherwise false. Native code only!getJSPrincipals Returns the JS equivalent of the principal. JSPrincipals getJSPrincipals( in JSContext cx ); Parameters cx Missing Description Return value Missing Description getPreferences
() Returns the security preferences associated with this principal. void getPreferences( out string prefBranch, out string id, out string subjectName, out string grantedList, out string deniedList, out boolean isTrusted ); Parameters prefBranch On return, contains the preference branch to which the preferences pertain. id A semi-unique ID relating to either the fingerpr...
...And 2 more matches
nsIRequest
initiator to control the request. Inherits from: nsISupports Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) For example nsIChannel typically passes itself as the nsIRequest argument to the nsIStreamListener on each onStartRequest, onDataAvaliable, and onStopRequest invocation. Method overview void cancel(in nsresult aStatus); boolean isPending
(); void resume
(); void suspend
(); Attributes Attribute Type Description loadFlags nsLoadFlags The load flags of this request. Bits 0-15 are reserved. When added to a load group, this request's load flags are merged with the load flags of the load group. loadGroup nsILoadGroup The load group of this request. While pendin...
... Constant Value Description LOAD_ANONYMOUS 1 << 14 When set, this flag indicates that no user-specific data should be added to the request when opened. This means that things like authorization tokens or cookie headers should not be added. Note: This will prevent proxy authentications from working, so use this flag with caution. Methods cancel
() Cancels the current request. This will close any open input or output streams and terminate any async requests. Users should normally pass NS_BINDING_ABORTED, although other errors may also be passed. The error passed in will become the value of the status attribute. Implementations must not send any notifications (for example via nsIRequestObserver) synchronously from this function. Similarly,...
...eamListener must not call onDataAvailable anymore after cancel has been called. Note: Most nsIRequest implementations expect aStatus to be a failure code; however, some implementations may allow aStatus to be a success code such as NS_OK. In general, aStatus should be a failure code. void cancel( in nsresult aStatus ); Parameters aStatus The reason for canceling this request. isPending
() Indicates whether the request is pending. isPending is true when there is an outstanding asynchronous event that will make the request no longer be pending. Requests do not necessarily start out pending; in some cases, requests have to be explicitly initiated (for example nsIChannel implementations are only pending once asyncOpen returns successfully). Requests can become pending multiple times...
...And 2 more matches
nsIScriptableUnicodeConverter
1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Implemented by: @mozilla.org/intl/scriptableunicodeconverter. ...
...tToByteArray(in AString aString,[optional] out unsigned long aLen,[array, size_is(aLen),retval] out octet aData); nsIInputStream convertToInputStream(in AString aString); Attributes Attribute Type Description charset string Current character set. Throws NS_ERROR_UCONV_NOCONV if the requested charset is not supported. ...
...iption charset string Current character set. Throws NS_ERROR_UCONV_NOCONV if the requested charset is not supported. Methods ConvertFromUnicode
() Converts the data from Unicode to one Charset. Returns the converted string. After converting, Finish should be called and its return value appended to this return value. ACString ConvertFromUnicode( in AString aSrc ); Finish
() Returns the terminator string. Should be called after ConvertFromUnicode
() and appended to that function's return value. ACString Finish
(); ConvertToUnicode
() Converts the data from one Charset to Unicode. AString ConvertToUnicode( in ACString aSrc ); convertFromByteArray
() Converts an array of bytes to a unicode string. AString convertFromByteArray( [const,array,size_is(aCount)] in...
...And 2 more matches
nsISound
ode. Please use the HTML 5 <audio> tag instead. Note that nsISound instances may play the sounds using another thread; however, this is not controlled by the caller. Implemented by: @mozilla.org/sound;1. To use this interface, use: var sound = Components.classes["@mozilla.org/sound;1"] .createInstance(Components.interfaces.nsISound); Method overview void beep
(); void init
(); void play(in nsIURL aURL); void playEventSound(in unsigned long aEventId); void playSystemSound(in AString soundAlias); Constants Sound event constants Constant Value Description EVENT_NEW_MAIL_RECEIVED 0 The system receives email. EVENT_A...
... EVENT_SELECT_DIALOG_OPEN 4 A select dialog (one that contains a list box) is opened. EVENT_MENU_EXECUTE 5 A menu item is executed. EVENT_MENU_POPUP 6 A popup menu is shown. EVENT_EDITOR_MAX_LEN 7 More characters than the maximum allowed are typed into a text field. ...
..._OPEN 4 A select dialog (one that contains a list box) is opened. EVENT_MENU_EXECUTE 5 A menu item is executed. EVENT_MENU_POPUP 6 A popup menu is shown. EVENT_EDITOR_MAX_LEN 7 More characters than the maximum allowed are typed into a text field. Methods beep
() Plays a beep sound. void beep
(); Parameters None. init
() Not strictly necessary, but avoids a delay before the first sound. Other methods will call Init if they need to. void init
(); Parameters None. play
() Plays a sound specified by URL. void play( in nsIURL aURL ); Parameters aURL The URL of the sound file to play. playEventSound
() Plays the system sound for the specified event. If the user's system is co...
...And 2 more matches
nsIStreamConverter
ter users There are currently two ways to use a stream converter: Synchronous: Stream to Stream. You can supply the service with a stream of type X and it will convert it to your desired output type and return a converted (blocking) stream to you. Asynchronous: nsIStreamListener to nsIStreamListener. You can supply data directly to the converter by calling it's nsIStreamListener.OnDataAvailable
() method. It will then convert that data from type X to your desired output type and return converted data to you via the nsIStreamListener you passed in by calling its nsIStreamListener.OnDataAvailable
() method. Stream converter suppliers Registering a stream converter: Stream converter registration is a two step process. First of all the stream converter implementation must register itself with ...
...Use this method when you want to proxy (and convert) nsIStreamListener callbacks asynchronously. void asyncConvertData( in string aFromType, in string aToType, in nsIStreamListener...
...Use this method when you want to proxy (and convert) nsIStreamListener callbacks asynchronously. void asyncConvertData( in string aFromType, in string aToType, in nsIStreamListener aListener, in nsISupports aCtxt ); Parameters aFromType The MIME type of the original/ra...
...And 2 more matches
nsIThread
Threads have a built-in event queue, and a thread is an event target that can receive nsIRunnable objects (events) to be processed on the thread. To create a thread, use the nsIThreadManager interface. xpcom/threads/nsIThread.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Inherits from: nsIEventTarget Method overview void shutdown
() boolean hasPendingEvents
() boolean processNextEvent(in boolean mayWait) Attributes Attribute Type Description PRThread PRThread The NSPR thread object corresponding to the nsIThread. Read only. Methods shutdown
() Shuts down the thread. This causes events to stop being dispatched to the thread, and causes any pending events to run to...
...During the execution of this method call, events for the current thread may continue to be processed. Warning: This method may not be called from the thread itself. ...
...ution of this method call, events for the current thread may continue to be processed. Warning: This method may not be called from the thread itself. Instead, you must only call it from another thread (usually the thread that created it, or the main application thread). When this function returns, the thread will be shut down and will no longer be available to receive events. void shutdown
() Parameters None. Exceptions thrown NS_ERROR_UNEXPECTED shutdown
() was erroneously called from within the thread itself, the thread was not created with the Thread Manager's nsIThreadManager.newThread
() method, or the thread is already in the process of being shut down. hasPendingEvents
() Determines whether or not the thread has events that are ready to be processed. Note: This method ...
...And 2 more matches
nsITimer
onkey 2.2) Inherits from: nsISupports Implemented by: @mozilla.org/timer;1. To create an instance, use: var timer = Components.classes["@mozilla.org/timer;1"] .createInstance(Components.interfaces.nsITimer); Users of instances of nsITimer should keep a reference to the timer until it is no longer needed in order to assure the timer is fired. ...
...back(in nsITimerCallback aCallback, in unsigned long aDelay, in unsigned long aType); void initWithFuncCallback(in nsTimerCallbackFunc aCallback, in voidPtr aClosure, in unsigned long aDelay, in unsigned long aType); Native code only! Attributes Attribute Type Description callback nsITimerCallback The nsITimerCallback object passed to initWithCallback
(). Read only. closure voidPtr The opaque pointer pass to initWithFuncCallback
(). Read only. Native code only! delay unsigned long The timeout delay in millisecond. Note: Re-setting the delay on a one-shot timer that has already fired doesn't restart the timer. Call one of the init
() methods to restart a one-shot timer. target nsIEventTarget The...
...nfluence the timer period. However this timer type guarantees that it will not queue up new events to fire the callback until the previous callback event finishes firing. If the callback takes a long time, then the next callback will be scheduled immediately afterward, but only once, unlike TYPE_REPEATING_PRECISE. If you want a non-slack timer, you probably want this one. Methods cancel
() Cancels the timer. This method works on all types, not just on repeating timers -- you might want to cancel a TYPE_ONE_SHOT timer, and even reuse it by re-initializing it (to avoid object destruction and creation costs by conserving one timer instance). void cancel
(); Parameters None. init
() Initialize a timer that will fire after the specified delay. A user must keep a reference to this t...
...And 2 more matches
nsITraceableChannel
data on to the original nsIStreamListener (possibly modifying it). See nsITraceableChannel, Intercept HTTP Traffic for a more detailed description with code samples. See Modify URL before loading page in firefox for an overview of how to modify a request before it is made. Method overview nsIStreamListener setNewListener(in nsIStreamListener aListener); Methods setNewListener
() Replaces the channel's current listener with a new one, returning the listener previously assigned to the channel. nsIStreamListener setNewListener( in nsIStreamListener aListener ); Parameters aListener An nsIStreamListener to be notified of events on the HTTP channel. Return value The previous listener for the channel. Each listener call through to the previous listener for every c...
...er ); Parameters aListener An nsIStreamListener to be notified of events on the HTTP channel. Return value The previous listener for the channel. Each listener call through to the previous listener for every call, in order to establish a call chain to allow all interested parties a chance to act on each event. Implementing nsIStreamListener The nsIStreamListener passed to setNewListener
() should implement the following methods, which are called to notify it of events that occur on the HTTP stream: onStartRequest: An HTTP request is beginning. onDataAvailable: Data is arriving on the HTTP channel. onStopRequest: The HTTP request is ending. Note: It is critical that you pass along requests to the previous listener as soon as possible -- especially for onStartRequest. Channel...
...holds chunks as they come, onStopRequest we join these junks to get the full source this.responseBody; // we'll set this to the this.responseStatusCode; this.deferredDone = { promise: null, resolve: null, reject: null }; this.deferredDone.promise = new Promise(function(resolve, reject) { this.resolve = resolve; this.reject =...
...And 2 more matches
nsITransaction
editor/txmgr/idl/nsITransaction.idlScriptable Please add a summary to this article. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void doTransaction
(); boolean merge(in nsITransaction aTransaction); void redoTransaction
(); void undoTransaction
(); Attributes Attribute Type Description isTransient boolean The transaction's transient state. This attribute is checked by the transaction manager after the transaction's Execute
() method is called. If the transient state is false, a reference to the transaction is held by the transaction manager so that the transactions' undoTransaction
() and redoTransaction
() methods can be called. If the transient state is true, the transaction manager returns immediately after the transaction's doTransaction...
...ttribute is checked by the transaction manager after the transaction's Execute
() method is called. If the transient state is false, a reference to the transaction is held by the transaction manager so that the transactions' undoTransaction
() and redoTransaction
() methods can be called. If the transient state is true, the transaction manager returns immediately after the transaction's doTransaction
() method is called, no references to the transaction are maintained. Transient transactions cannot be undone or redone by the transaction manager. Read only. Methods doTransaction
() Executes the transaction. void doTransaction
(); Parameters None. merge
() Attempts to merge a transaction into "this" transaction. ...
...saction's doTransaction
() method is called, no references to the transaction are maintained. Transient transactions cannot be undone or redone by the transaction manager. Read only. Methods doTransaction
() Executes the transaction. void doTransaction
(); Parameters None. merge
() Attempts to merge a transaction into "this" transaction. Both transactions must be in their undo state, doTransaction
() methods already called. The transaction manager calls this method to coalesce a new transaction with the transaction on the top of the undo stack. This method returns a boolean value that indicates the merge result. A true value indicates that the transactions were merged successfully, a false value if the merge was not possible or failed. ...
...And 2 more matches
nsITransactionList
from: nsISupports Last changed in Gecko 1.7 Method overview nsITransactionList getChildListForItem(in long aIndex); nsITransaction getItem(in long aIndex); long getNumChildrenForItem(in long aIndex); boolean itemIsBatch(in long aIndex); Attributes Attribute Type Description numItems long The number of transactions contained in this list. Read only. Methods getChildListForItem
() Returns the list of children associated with the item at aIndex. Implementations may return null if there are no children, or an empty list. The list returned is AddRef'd so it is up to the caller to Release the transaction when it is done. nsITransactionList getChildListForItem( in long aIndex ); Parameters aIndex The index of the item in the list. Return value The nsITransactionList of chi...
... item at aIndex. Implementations may return null if there are no children, or an empty list. The list returned is AddRef'd so it is up to the caller to Release the transaction when it is done. nsITransactionList getChildListForItem( in long aIndex ); Parameters aIndex The index of the item in the list. Return value The nsITransactionList of children associated with the item at aIndex. ...
...at aIndex. getItem
() Returns the transaction at the given index in the list. Note that a null can be returned here if the item is a batch. The transaction returned is AddRef'd so it is up to the caller to Release the transaction when it is done. nsITransaction getItem( in long aIndex ); Parameters aIndex The index of the item in the list. Return value Missing Description getNumChildrenForItem
() Returns the number of child (auto-aggreated) transactions the item at aIndex has. long getNumChildrenForItem( in long aIndex ); Parameters aIndex The index of the item in the list. Return value The number of child (auto-aggreated) transactions the item at aIndex has. itemIsBatch
() Returns true if the item at aIndex is a batch. Note that currently there is no requirement for a TransactionMana...
...And 2 more matches
nsITreeColumns
The nsITreeColumns interface represents the tree columns. layout/xul/base/src/tree/public/nsITreeColumns.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Inherits from: nsISupports Method overview nsITreeColumn getColumnAt(in long index); nsITreeColumn getColumnFor(in nsIDOMElement element); nsITreeColumn getFirstColumn
(); nsITreeColumn getKeyColumn
(); nsITreeColumn getLastColumn
(); nsITreeColumn getNamedColumn(in AString id); nsITreeColumn getPrimaryColumn
(); nsITreeColumn getSortedColumn
(); void invalidateColumns
(); void restoreNaturalOrder
(); Attributes Attribute Type Description count long The number of columns. Read only. length long An alias for count (for the benefit of scripts which treat this as an arr...
...getPrimaryColumn
(); nsITreeColumn getSortedColumn
(); void invalidateColumns
(); void restoreNaturalOrder
(); Attributes Attribute Type Description count long The number of columns. Read only. length long An alias for count (for the benefit of scripts which treat this as an array). Read only. tree nsITreeBoxObject The tree widget for these columns. Read only. Methods getColumnAt
() Get the column for a given index. nsITreeColumn getColumnAt( in long index ); Parameters index Index of the column Return value A nsITreeColumn for this index. getColumnFor
() Get the column for a given element. nsITreeColumn getColumnFor( in nsIDOMElement element ); Parameters element A DOM element Return value A nsITreeColumn for this element. getFirstColumn
() Get the first column. nsI...
...en index. nsITreeColumn getColumnAt( in long index ); Parameters index Index of the column Return value A nsITreeColumn for this index. getColumnFor
() Get the column for a given element. nsITreeColumn getColumnFor( in nsIDOMElement element ); Parameters element A DOM element Return value A nsITreeColumn for this element. getFirstColumn
() Get the first column. nsITreeColumn getFirstColumn
(); Parameters None. Return value The first nsITreeColumn. getKeyColumn
() Get the key column. nsITreeColumn getKeyColumn
(); Parameters None. Return value The key nsITreeColumn. getLastColumn
() Get the last column. nsITreeColumn getLastColumn
(); Parameters None. Return value The last nsITreeColumn. getNamedColumn
() Get a column for a given name. nsITreeColumn getNamedColumn( in AString id ); Pa...
...And 2 more matches
nsIUpdatePrompt
toolkit/mozapps/update/nsIUpdateService.idlScriptable This interface describes an object that can be used to show various update-related notifications to the user. ...
... Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method overview void checkForUpdates
(); void showUpdateAvailable(in nsIUpdate update); void showUpdateDownloaded(in nsIUpdate update, [optional] in boolean background); void showUpdateError(in nsIUpdate update); void showUpdateHistory(in nsIDOMWindow parent); void showUpdateInstalled
(); Methods checkForUpdates
() Presents a user interface that checks for and displays the available updates. void checkForUpdates
(); Parameters None. showUpdateAvailable
() Shows a message advising the user that an update is available to be downloaded and installed. If the app.update.silent preference is true or the user interface is already displayed the call will be a no-op. void showUpdateAvail...
...If background is true (for example the download was not user initiated) and the app.update.silent preference is true the call will be a no-op. ...
...And 2 more matches
nsIWebBrowserChrome
embedding/browser/webBrowser/nsIWebBrowserChrome.idlScriptable Corresponds to the top-level, outermost window containing an embedded Gecko web browser. Inherits from: nsISupports Last changed in Gecko 0.9.6 Method overview void destroyBrowserWindow
(); void exitModalEventLoop(in nsresult aStatus); boolean isWindowModal
(); void setStatus(in unsigned long statusType, in wstring status); void showAsModal
(); void sizeBrowserTo(in long aCX, in long aCY); Attributes Attribute Type Description chromeFlags unsigned long The chrome flags for this browser chrome. The implementation should reflect the value of this attribute by hiding or showing its chrome appropriately. webBrowser nsIWe...
...et the WebBrowser object to a new object by setting this attribute. In this case the implementer is responsible for taking the new WebBrowser object and doing any necessary initialization or setup as if it had created the WebBrowser itself. This includes positioning setting up listeners etc. Constants Constant Value Description STATUS_SCRIPT 1 Flag for SetStatus
() STATUS_SCRIPT_DEFAULT 2 Flag for SetStatus
() STATUS_LINK 3 Flag for SetStatus
() CHROME_DEFAULT 1 Value for the chromeFlags attribute. CHROME_WINDOW_BORDERS 2 Value for the chromeFlags attribute. CHROME_WINDOW_CLOSE 4 Value for the chromeFlags attribute. CHROME_WINDOW_RESIZE 8 Value for the chromeFlags attrib...
... way the window looks and does not mean it's actually modal. CHROME_OPENAS_DIALOG 1073741824 Represent special cases. CHROME_OPENAS_CHROME 2147483648 Represent special cases. CHROME_ALL 4094 Represent special cases. CHROME_REMOTE_WINDOW 1048576 Whether this window should use remote (out-of-process) tabs. Methods destroyBrowserWindow
() Asks the implementer to destroy the window associated with this WebBrowser object. void destroyBrowserWindow
(); Parameters None. exitModalEventLoop
() Exit a modal event loop if we're in one. The implementation should also exit out of the loop if the window is destroyed. void exitModalEventLoop( in nsresult aStatus ); Parameters aStatus The result code to return from showAsModal
(). i...
...And 2 more matches
nsIWebNavigation
ecifies that any intermediate proxy caches should be bypassed (That is, that the content should be loaded from the origin server). LOAD_FLAGS_CHARSET_CHANGE 1024 This flag specifies that a reload was triggered as a result of detecting an incorrect character encoding while parsing a previously loaded document. LOAD_FLAGS_STOP_CONTENT 2048 If this flag is set, Stop
() will be called before the load starts and will stop both content and network activity (the default is to only stop network activity). Effectively, this passes the STOP_CONTENT flag to Stop
(), in addition to the STOP_NETWORK flag. LOAD_FLAGS_FROM_EXTERNAL 4096 A hint this load was prompted by an external program: take care! LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP 8192 ...
...nt DOM document for the frame, or lazily creates a blank document if there is none. This attribute never returns null except for unexpected error situations. Read only. referringURI nsIURI The referring URI for the currently loaded URI or null. Read only. sessionHistory nsISHistory The session history object used by this web navigation instance. Methods goBack
() Tells the object to navigate to the previous session history item. When a page is loaded from session history, all content is loaded from the cache (if available) and page state (such as form values and scroll position) is restored. void goBack( ); goForward
() Tells the object to navigate to the next session history item. When a page is loaded from session history, all content is loaded from...
... loaded from the cache (if available) and page state (such as form values and scroll position) is restored. void goBack( ); goForward
() Tells the object to navigate to the next session history item. When a page is loaded from session history, all content is loaded from the cache (if available) and page state (such as form values and scroll position) is restored. void goForward( ); gotoIndex
() Tells the object to navigate to the session history item at a given index. void gotoIndex( in long index ); Parameters index The index of the session history item to go to. loadURI
() Loads a given URI. This will give priority to loading the requested URI in the object implementing this interface. If it can't be loaded here however, the URI dispatcher will go through its normal proces...
...And 2 more matches
nsIWritablePropertyBag2
value); void setPropertyAsInt32(in AString prop, in PRInt32 value); void setPropertyAsInt64(in AString prop, in PRInt64 value); void setPropertyAsInterface(in AString prop, in nsISupports value); void setPropertyAsUint32(in AString prop, in PRUint32 value); void setPropertyAsUint64(in AString prop, in PRUint64 value); Methods setPropertyAsACString
() void setPropertyAsACString( in AString prop, in ACString value ); Parameters prop Property to set the value of. value Value to set the property to. setPropertyAsAString
() void setPropertyAsAString( in AString prop, in AString value ); Parameters prop Property to set the value of. value Value to set the property to. setPropertyAsAUTF8String
() void setP...
...AString
() void setPropertyAsAString( in AString prop, in AString value ); Parameters prop Property to set the value of. value Value to set the property to. setPropertyAsAUTF8String
() void setPropertyAsAUTF8String( in AString prop, in AUTF8String value ); Parameters prop Property to set the value of. value Value to set the property to. setPropertyAsBool
() void setPropertyAsBool( in AString prop, in boolean value ); Parameters prop Property to set the value of. value Value to set the property to. setPropertyAsDouble
() void setPropertyAsDouble( in AString prop, in double value ); Parameters prop Property to set the value of. value Value to set the property to. ...
...y to. setPropertyAsBool
() void setPropertyAsBool( in AString prop, in boolean value ); Parameters prop Property to set the value of. value Value to set the property to. setPropertyAsDouble
() void setPropertyAsDouble( in AString prop, in double value ); Parameters prop Property to set the value of. value Value to set the property to. setPropertyAsInt32
() void setPropertyAsInt32( in AString prop, in PRInt32 value ); Parameters prop Property to set the value of. value Value to set the property to. setPropertyAsInt64
() void setPropertyAsInt64( in AString prop, in PRInt64 value ); Parameters prop Property to set the value of. value Value to set the property to. ...
...And 2 more matches
nsIXmlRpcClient
unreachable or not yet contacted. Constants Constant Type Description INT unsigned long nsISupportsPRInt32 BOOLEAN unsigned long nsISupportsPRBool STRING unsigned long nsISupportsCString DOUBLE unsigned long nsISupportsDouble DATETIME unsigned long nsISupportsPRTime ARRAY readonly unsigned long nsISupportsArray STRUCT readonly unsigned long nsISupportsDictionary Methods init
() Set server URL. Call this before using this object void getData ( in string serverURL ) ; Parameters serverURL URL of server side object on which methods should be called setAuthentication
() Set authentication info if needed. Both parameters must be specified for authentication to be enabled void setAuthentication ( in string username, in string password ) ; Parameters u...
... server side object on which methods should be called setAuthentication
() Set authentication info if needed. Both parameters must be specified for authentication to be enabled void setAuthentication ( in string username, in string password ) ; Parameters username username to be used if asked to authenticate password password to be used if asked to authenticate clearAuthentication
() Clear authentication info void setAuthentication ( in string username, in string password ) ; Parameters username password setEncoding
() Set character encoding. ...
... to authenticate clearAuthentication
() Clear authentication info void setAuthentication ( in string username, in string password ) ; Parameters username password setEncoding
() Set character encoding. The default charset if this function is not called is "UTF-8" void setAuthentication ( in string encoding ) ; Parameters encoding encoding charset to be used asyncCall
() Call remote method methodName asynchronously with given arguments. Supported arguments are: nsISupportsPRUint8, nsISupportsPRUint16, nsISupportsPRInt16, nsISupportsPRInt32: i4, nsISupportsPRBool: boolean, nsISupportsChar, nsISupportsCString: string, nsISupportsFloat, nsISupportsDouble: double, nsISupportsPRTime: dateTime.iso8601, nsIInputStream: base64, nsISupportsArray: array, nsIDictionary: str...
...And 2 more matches
Using Objective-C from js-ctypes
This can run with a copy-and-paste into a JavaScript shell. This example uses a busy loop, and thus, Firefox won't respond until the speaking is done. If this code were to be used in a production add-on, then to avoid Firefox locking up, run th...
...while (!objc_msgSend_BOOL(synth, isSpeaking)) {} // Wait while speaking. while (objc_msgSend_BOOL(synth, isSpeak...
...gisterName("startSpeakingString:"); objc_msgSend(synth, startSpeakingString, text); let isSpeaking = sel_registerName("isSpeaking"); // Wait until start speaking. while (!objc_msgSend_BOOL(synth, isSpeaking)) {} // Wait while speaking. while (objc_msgSend_BOOL(synth, isSpeaking)) {} let release = sel_registerName("release"); objc_msgSend(synth, release); objc_msgSend(text, release); lib.close
(); Creating Objective-C Blocks Objective-C API calls sometimes require you to pass in a block. Reading the Apple Developer :: Programming with Objective-C - Working with Blocks you can learn more about blocks. To create a block with js-ctypes, use the function: function createBlock(aFuncTypePtr) { /** * Creates a C block instance from a JS Function. * Blocks are regular Objective-C objects...
...And 2 more matches
Declaring and Using Callbacks
wise js-ctypes will throw error saying unexpected type return } var myCCallback = myFuncTypeDeclaration.ptr(myJSCallback); Example 2 This callback that returns void and no arguments. When void is the return type, the javascript callback must not return, or it should return undefined. var myFuncTypeDeclaration = ctypes.FunctionType(ctypes.default_abi, ctypes.void_t, []); function myJSCallback
() { return undefined; // as the return of the FunctionType was ctypes.void_t we must return undefined OR dont return at all otherwise js-ctypes will throw an error saying unexpected type } var myCCallback = myFuncTypeDeclaration.ptr(myJSCallback); Using Callbacks Since callbacks are function pointers in C, js-ctypes has special handling for function pointer types. Consider the following cod...
... throw an error saying unexpected type } var myCCallback = myFuncTypeDeclaration.ptr(myJSCallback); Using Callbacks Since callbacks are function pointers in C, js-ctypes has special handling for function pointer types. Consider the following code: function myJSCallback(foo, bar) { .... }; var funcType = ctypes.FunctionType(...); var funcPtrType = funcType.ptr; var regularFuncPtr = funcPtrType
(); var callback = funcPtrType(myJSCallback); js-ctypes detects that funcPtrType is a type of function pointer, and adds a special case to its constructor. In the ordinary case, invoking the type object creates a regular CData object containing a pointer to the data. However, if the first argument is a function, js-ctypes creates a special object (known internally as a CClosure) that wraps the Jav...
...e object creates a regular CData object containing a pointer to the data. However, if the first argument is a function, js-ctypes creates a special object (known internally as a CClosure) that wraps the JavaScript function within an ordinary C function. ...
...And 2 more matches
Library
This can be used both for exported data symbols and for functions. ...
...This can be used both for exported data symbols and for functions. ...
...This can be used both for exported data symbols and for functions. ...
...And 2 more matches
Debugger - Firefox Developer Tools
ference to its debuggee globals: if a debuggee global is not otherwise reachable, then it is dropped from the Debugger's set of debuggees. (Naturally, the Debugger.Object instance this method returns does hold a strong reference to the added global.) If this debugger is tracking allocation sites and cannot track allocation sites forglobal, this method throws an Error. addAllGlobalsAsDebuggees
() This method is like addDebuggee, but adds all the global objects from all compartments to this Debugger instance's set of debuggees. Note that it skips this debugger's compartment. If this debugger is tracking allocation sites and cannot track allocation sites for some global, this method throws an Error. Otherwise this method returns undefined. This method is only available to debuggers r...
...gees is only available to privileged code. removeDebuggee(global) Remove the global object designated byglobal from this Debugger instance's set of debuggees. Return undefined. This method interpretsglobal using the same rules that addDebuggee does. Removing a global as a debuggee from this Debugger clears all breakpoints that belong to that Debugger in that global. ...
...er clears all breakpoints that belong to that Debugger in that global. removeAllDebuggees
() Remove all the global objects from this Debugger instance's set of debuggees. Return undefined. hasDebuggee(global) Return true if the global object designated byglobal is a debuggee of this Debugger instance. This method interpretsglobal using the same rules that addDebuggee does. getDebuggees
() Return an array of distinct Debugger.Object instances whose referents are all the global objects this Debugger instance is debugging. ...
...And 2 more matches
Monster example - Firefox Developer Tools
This article describes a very simple web page that we'll use to illustrate some features of the Memory tool. You can try the site at https://mdn.github.io/performance-scenarios/js-allocs/alloc.html. ...
... This article describes a very simple web page that we'll use to illustrate some features of the Memory tool. You can try the site at https://mdn.github.io/performance-scenarios/js-allocs/alloc.html. ...
...ge that we'll use to illustrate some features of the Memory tool. You can try the site at https://mdn.github.io/performance-scenarios/js-allocs/alloc.html. ...
...And 2 more matches
Call Tree - Firefox Developer Tools
t is a very inefficient algorithm. We have about six times as many samples in bubble sort as in selection sort, and 13 times as many as in quicksort. Walking up the call tree Next to each function name is a disclosure arrow: Click that, and you can see the path back up the call tree, from the function in which the sample was taken, to the root. For example, we can expand the entry for bubbleSort
(): So we can see the call graph is like this: sortAll
() -> sort
() -> bubbleSort
() Note also that Self Cost for sort
() here is 1.45%, and note that this is the same as for the separate entry for sort
() later in the list. This is telling us that some samples were taken in sort
() itself, rather than in the functions it calls. Sometimes there's more than one path back from an entry ...
...sortAll
() -> sort
() -> bubbleSort
() Note also that Self Cost for sort
() here is 1.45%, and note that this is the same as for the separate entry for sort
() later in the list. This is telling us that some samples were taken in sort
() itself, rather than in the functions it calls. Sometimes there's more than one path back from an entry to the top level. Let's expand the entry for swap
(): There were 253 samples taken inside swap
(). But swap
() was reached by two different paths: both bubbleSort
() and selectionSort
() use it. We can also see that 252 of the 253 samples in swap
() were taken in the bubbleSort
() branch, and only one in the selectionSort
() branch. This result means that bubble sort is even less efficient than we had thought! It can shoulder the blame for another 252...
... that 252 of the 253 samples in swap
() were taken in the bubbleSort
() branch, and only one in the selectionSort
() branch. This result means that bubble sort is even less efficient than we had thought! It can shoulder the blame for another 252 samples, or almost another 10% of the total cost. With this kind of digging, we can figure out the whole call graph, with associated sample count: sortAll
() // 8 -> sort
() // 37 -> bubbleSort
() // 1345 -> swap
() // 252 -> selectionSort
() // 190 -> swap
() // 1 -> quickSort
() // 103 -> partition
() // 12 Platform data You'll also see some rows labeled Gecko, Input & E...
...And 2 more matches
Tips - Firefox Developer Tools
Node: Right-click a node within the Inspector and click "Screenshot Node". Via Web Console command: screenshot <filename.png> --fullpage. Settings: Choose between a light and a dark theme for the developer tools. Change the keyboard bindings to Vim, Emacs or Sublime Text if you're used to different shortcuts. Check or uncheck the different tools to enable or disable them. ...
...in the page (same as right-click a node and click "Scroll Into View"). Right-click a node and click "Use in Console" to command line as tempN variable. When selecting elements: Shift + click to select an element but keep selecting (picker mode doesn't disengage). Use <-/-> to navigate to parents/children elements (if they're hard to select). In the rules view: Click the inspector icon
() next to any selector to highlight all elements that match it. Click the inspector icon
() next to the element{} rule to lock the highlighter on the current element. Right-click any property and select "Show MDN Docs" to view the MDN docs for this property. Click on the filter icon
() next to an overridden property to find which other property overrides it. Right-click on a name, value, or rul...
...filter icon
() next to an overridden property to find which other property overrides it. Right-click on a name, value, or rule to copy anything from the name, the value, the declaration or the whole rule to your clipboard. Web Console In all panels: Esc opens the split console; useful when debugging, or inspecting nodes In the command line: $0 references the currently selected node. $
() is a shortcut to document.querySelector
(). $$
() returns an array with the results from document.querySelectorAll
(). copy copies anything as a string. Right-click a node in the Inspector and click "Use in Console" to create a tempN variable for it. cd switches the JavaScript evaluation context to a different iframe in the page. console.table
() displays tabular data as table. help opens the M...
...And 2 more matches
Console messages - Firefox Developer Tools
nes discussed here, or are interested in contributing, check out the metabug and its dependencies. Logging Messages logged from Shared Workers, Service Workers, add-ons, and Chrome Workers are not shown by default. Use the filtering feature to show them. The Logging category includes messages logged using the Console API. ...
...ssed here, or are interested in contributing, check out the metabug and its dependencies. Logging Messages logged from Shared Workers, Service Workers, add-ons, and Chrome Workers are not shown by default. Use the filtering feature to show them. The Logging category includes messages logged using the Console API. ...
..., or are interested in contributing, check out the metabug and its dependencies. Logging Messages logged from Shared Workers, Service Workers, add-ons, and Chrome Workers are not shown by default. Use the filtering feature to show them. The Logging category includes messages logged using the Console API. ...
...And 2 more matches
ANGLE_instanced_arrays - Web APIs
For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is only available to WebGL1 contexts. ...
... the constants and methods are available without the "ANGLE" suffix. Despite the name "ANGLE", this extension works on any device if the hardware supports it and not just on Windows when using the ANGLE library. "ANGLE" just indicates that this extension has been written by the ANGLE library authors. ...
... just on Windows when using the ANGLE library. "ANGLE" just indicates that this extension has been written by the ANGLE library authors. Constants This extension exposes one new constant, which can be used in the gl.getVertexAttrib
() method: ext.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE Returns a GLint describing the frequency divisor used for instanced rendering when used in the gl.getVertexAttrib
() as the pname parameter. Methods This extension exposes three new methods. ...
...And 2 more matches
AbortController.signal - Web APIs
The signal read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort a DOM request as desired. Syntax var signal = abortController.signal; Value An AbortSignal object instance. Examples In the following snippet, we aim to download a video using the Fetch API. ...
...ng the AbortController
() constructor, then grab a reference to its associated AbortSignal object using the AbortController.signal property. When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). This associates the signal and controller with the fetch request and allows us to abort it by calling AbortController.abort
(), as seen below in the second event listener. ...
...gnal object using the AbortController.signal property. When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal}, below). This associates the signal and controller with the fetch request and allows us to abort it by calling AbortController.abort
(), as seen below in the second event listener. var controller = new AbortController
(); var signal = controller.signal; var downloadBtn = document.querySelector('.download'); var abortBtn = document.querySelector('.abort'); downloadBtn.addEventListener('click', fetchVideo); abortBtn.addEventListener('click', function
() { controller.abort
(); console.log('Download aborted'); }); function fetchVideo
() { ... fetch(url, {signal}).then(function(response) { ... }).catch(...
...And 2 more matches
AnalyserNode.frequencyBinCount - Web APIs
The frequencyBinCount read-only property of the AnalyserNode interface is an unsigned integer half that of the AnalyserNode.fftSize. This generally equates to the number of data values you will have to play with for the visualization. Syntax var arrayLength = analyserNode.frequencyBinCount; Value An unsigned integer, equal to the number of values that AnalyserNode.getByteFrequencyData
() and AnalyserNode.getFloatFrequencyData
() copy into the provided TypedArray. For technical reasons related to how the Fast Fourier transform is defined, it is always half the value of AnalyserNode.fftSize. Therefore, it will be one of 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, and 16384. Example The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestA...
...ge of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). ...
...rNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). ...
...And 2 more matches
AnalyserNode.maxDecibels - Web APIs
The maxDecibels property of the AnalyserNode interface is a double value representing the maximum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte/float values -- basically, this specifies the maximum value for the range of results when using getFloatFrequencyData
() or getByteFrequencyData
(). Syntax var curValue = analyserNode.maxDecibels; analyserNode.maxDecibels = newValue; Value A double, representing the maximum decibel value for scaling the FFT analysis data, where 0 dB is the loudest possible sound, -10 dB is a 10th of that, etc. The default value is -30 dB. When getting data from getFloatFrequencyData
() or getByteFrequencyData
(), any frequencies with an amplitude of maxDecibels or higher will be returned as +1.0 or 255, respectively. ...
...ge of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). ...
...rNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). ...
...And 2 more matches
AnalyserNode.minDecibels - Web APIs
The minDecibels property of the AnalyserNode interface is a double value representing the minimum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte/float values -- basically, this specifies the minimum value for the range of results when using getFloatFrequencyData
() or getByteFrequencyData
(). Syntax var curValue = analyserNode.minDecibels; analyserNode.minDecibels = newValue; Value A double, representing the minimum decibel value for scaling the FFT analysis data, where 0 dB is the loudest possible sound, -10 dB is a 10th of that, etc. The default value is -100 dB. When getting data from getFloatFrequencyData
() or getByteFrequencyData
(), any frequencies with an amplitude of minDecibels or lower will be returned as 0.0 or 0, respectively. No...
...ge of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). ...
...rNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). ...
...And 2 more matches
BlobBuilder - Web APIs
The BlobBuilder interface provides an easy way to construct Blob objects. Just create a BlobBuilder and append chunks of data to it by calling the append
() method. When you're done building your blob, call getBlob
() to retrieve a Blob containing the data you sent into the blob builder. Note: The BlobBuilder interface has been deprecated in favor of the newly introduced Blob constructor. ...
...ce has been deprecated in favor of the newly introduced Blob constructor. Method overview void append(in ArrayBuffer data); void append(in Blob data); void append(in String data, [optional] in String endings); Blob getBlob([optional] in DOMString contentType); File getFile(in DOMString name, [optional] in DOMString contentType); Methods append
() Appends the contents of the specified JavaScript object to the Blob being built. If the value you specify isn't a Blob, ArrayBuffer, or String, the value is coerced to a string before being appended to the blob. void append( in ArrayBuffer data ); void append( in Blob data ); void append( in String data, [optional] in String endings ); Parameters data The data to append to the ...
...void append( in Blob data ); void append( in String data, [optional] in String endings ); Parameters data The data to append to the Blob being constructed. endings Specifies how strings containing \n are to be written out. This can be "transparent" (endings unchanged) or "native" (endings changed to match host OS filesystem convention). The default value is "transparent". ...
...And 2 more matches
Body - Web APIs
d by both Request and Response. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence). Properties Body.body Read only A simple getter used to expose a ReadableStream of the body contents. Body.bodyUsed Read only A Boolean that indicates whether the body has been read. ...
...et), and a MIME type (initially the empty byte sequence). Properties Body.body Read only A simple getter used to expose a ReadableStream of the body contents. Body.bodyUsed Read only A Boolean that indicates whether the body has been read. Methods Body.arrayBuffer
() Takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer. Body.blob
() Takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob. ...
... expose a ReadableStream of the body contents. Body.bodyUsed Read only A Boolean that indicates whether the body has been read. Methods Body.arrayBuffer
() Takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer. Body.blob
() Takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob. Body.formData
() Takes a Response stream and reads it to completion. It returns a promise that resolves with a FormData object. Body.json
() Takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON. Body.text
() Takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString (text). The respon...
...And 2 more matches
CSSStyleDeclaration - Web APIs
properties. A CSSStyleDeclaration object can be exposed using three different APIs: Via HTMLElement.style, which deals with the inline styles of a single element (e.g., <div style="...">). Via the CSSStyleSheet API. For example, document.styleSheets[0].cssRules[0].style returns a CSSStyleDeclaration object on the first CSS rule in the document's first stylesheet. Via Window.getComputedStyle
(), which exposes the CSSStyleDeclaration object as a read-only interface. Attributes CSSStyleDeclaration.cssText Textual representation of the declaration block. Setting this attribute changes the style. CSSStyleDeclaration.lengthRead only The number of properties. See the item
() method below. CSSStyleDeclaration.parentRuleRead only The containing CSSRule. CSS Properties CSSStyleDe...
...laration.lengthRead only The number of properties. See the item
() method below. CSSStyleDeclaration.parentRuleRead only The containing CSSRule. CSS Properties CSSStyleDeclaration.cssFloat Special alias for the float CSS property. CSSStyleDeclaration named properties Dashed and camel-cased attributes for all supported CSS properties. Methods CSSStyleDeclaration.getPropertyPriority
() Returns the optional priority, "important". CSSStyleDeclaration.getPropertyValue
() Returns the property value given a property name. CSSStyleDeclaration.item
() Returns a CSS property name by its index, or the empty string if the index is out-of-bounds. An alternative to accessing nodeList[i] (which instead returns undefined when i is out-of-bounds). This is mostly useful for non-JavaScript ...
...Returns the property value as a CSSPrimitiveValue or null for shorthand properties. ...
...And 2 more matches
CanvasRenderingContext2D.filter - Web APIs
.filter property of the Canvas 2D API provides filter effects such as blurring and grayscaling. It is similar to the CSS filter property and accepts the same values. Syntax ctx.filter = "<filter-function1> [<filter-function2>] [<filter-functionN>]"; ctx.filter = "none"; Values The filter property accepts a value of "none" or one or more of the following filter functions in a DOMString. url
() A CSS <url>. Takes an IRI pointing to an SVG filter element, which may be embedded in an external XML file. blur
() A CSS <length>. Applies a Gaussian blur to the drawing. It defines the value of the standard deviation to the Gaussian function, i.e., how many pixels on the screen blend into each other; thus, a larger value will create more blur. A value of 0 leaves the input unchanged. brightn...
... CSS <url>. Takes an IRI pointing to an SVG filter element, which may be embedded in an external XML file. blur
() A CSS <length>. Applies a Gaussian blur to the drawing. It defines the value of the standard deviation to the Gaussian function, i.e., how many pixels on the screen blend into each other; thus, a larger value will create more blur. A value of 0 leaves the input unchanged. brightness
() A CSS <percentage>. Applies a linear multiplier to the drawing, making it appear brighter or darker. A value under 100% darkens the image, while a value over 100% brightens it. A value of 0% will create an image that is completely black, while a value of 100% leaves the input unchanged. contrast
() A CSS <percentage>. Adjusts the contrast of the drawing. A value of 0% will create a drawing that...
...ar brighter or darker. A value under 100% darkens the image, while a value over 100% brightens it. A value of 0% will create an image that is completely black, while a value of 100% leaves the input unchanged. contrast
() A CSS <percentage>. Adjusts the contrast of the drawing. A value of 0% will create a drawing that is completely black. A value of 100% leaves the drawing unchanged. drop-shadow
() Applies a drop shadow effect to the drawing. A drop shadow is effectively a blurred, offset version of the drawing's alpha mask drawn in a particular color, composited below the drawing. This function takes up to five arguments: <offset-x>: See <length> for possible units. Specifies the horizontal distance of the shadow. <offset-y>: See <length> for possible units. Specifies the vertical d...
...And 2 more matches
ChannelMergerNode - Web APIs
to process. In that case, when the signal is sent to the AudioContext.listener object, supernumerary channels will be ignored. Number of inputs variable; default to 6. Number of outputs 1 Channel count mode "max" Channel count 2 (not used in the default count mode) Channel interpretation "speakers" Constructor ChannelMergerNode
() Creates a new ChannelMergerNode object instance. Properties No specific property; inherits properties from its parent, AudioNode. Methods No specific method; inherits methods from its parent, AudioNode. Example The following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. To use them, you need to use the seco...
...Example The following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. To use them, you need to use the second and third parameters of the AudioNode.connect(AudioNode) method, which allow you to specify both the index of the channel to connect from and the index of the channel to connect to. ...
...usic), and process the left and right channel differently. To use them, you need to use the second and third parameters of the AudioNode.connect(AudioNode) method, which allow you to specify both the index of the channel to connect from and the index of the channel to connect to. ...
...And 2 more matches
ConvolverNode.buffer - Web APIs
then be used as the buffer. This AudioBuffer must have the same sample-rate as the AudioContext or an exception will be thrown. At the time when this attribute is set, the buffer and the state of the attribute will be used to configure the ConvolverNode with this impulse response having the given normalization. The initial value of this attribute is null. ...
...r must have the same sample-rate as the AudioContext or an exception will be thrown. At the time when this attribute is set, the buffer and the state of the attribute will be used to configure the ConvolverNode with this impulse response having the given normalization. The initial value of this attribute is null. ...
...e state of the attribute will be used to configure the ConvolverNode with this impulse response having the given normalization. The initial value of this attribute is null. Syntax var audioCtx = new AudioContext
(); var convolver = audioCtx.createConvolver
(); convolver.buffer = myAudioBuffer; Value An AudioBuffer. Example var audioCtx = new (window.AudioContext || window.webkitAudioContext)
(); var convolver = audioCtx.createConvolver
(); ... ...
...And 2 more matches
ConvolverNode.normalize - Web APIs
r not. Its default value is true in order to achieve a more uniform output level from the convolver, when loaded with diverse impulse responses. If normalize is set to false, then the convolution will be rendered with no pre-processing/scaling of the impulse response. Changes to this value do not take effect until the next time the buffer attribute is set. ...
...o achieve a more uniform output level from the convolver, when loaded with diverse impulse responses. If normalize is set to false, then the convolution will be rendered with no pre-processing/scaling of the impulse response. Changes to this value do not take effect until the next time the buffer attribute is set. ...
...then the convolution will be rendered with no pre-processing/scaling of the impulse response. Changes to this value do not take effect until the next time the buffer attribute is set. Syntax var audioCtx = new AudioContext
(); var convolver = audioCtx.createConvolver
(); convolver.normalize = false; Value A boolean. Example var audioCtx = new (window.AudioContext || window.webkitAudioContext)
(); var convolver = audioCtx.createConvolver
(); ... ...
...And 2 more matches
CustomElementRegistry - Web APIs
The CustomElementRegistry interface provides methods for registering custom elements and querying registered elements. To get an instance of it, use the window.customElements property. Methods CustomElementRegistry.define
() Defines a new custom element. CustomElementRegistry.get
() Returns the constuctor for the named custom element, or undefined if the custom element is not defined. CustomElementRegistry.upgrade
() Upgrades a custom element directly, even before it is connected to its shadow root. CustomElementRegistry.whenDefined
() Returns an empty promise that resolves when a custom element becomes defined with the given name. If such a custom element is already defined, the returned promise is immediately fulfilled. Examples The following code is taken from our word-count-we...
...d to its shadow root. CustomElementRegistry.whenDefined
() Returns an empty promise that resolves when a custom element becomes defined with the given name. If such a custom element is already defined, the returned promise is immediately fulfilled. Examples The following code is taken from our word-count-web-component example (see it live also). Note how we use the CustomElementRegistry.define
() method to define the custom element after creating its class. ...
... such a custom element is already defined, the returned promise is immediately fulfilled. Examples The following code is taken from our word-count-web-component example (see it live also). Note how we use the CustomElementRegistry.define
() method to define the custom element after creating its class. ...
...And 2 more matches
DOMUserData - Web APIs
DOMUserData is not persisted nor serialized and will not be present after the application has restarted or after a crash. ...
... DOMUserData is not persisted nor serialized and will not be present after the application has restarted or after a crash. ...
... DOMUserData is not persisted nor serialized and will not be present after the application has restarted or after a crash. ...
...And 2 more matches
DelayNode - Web APIs
When creating a graph that has a cycle, it is mandatory to have at least one DelayNode in the cycle, or the nodes taking part in the cycle will be muted. Number of inputs 1 Number of outputs 1 Channel count mode "max" Channel count 2 (not used in the default count mode) Channel interpretation "speakers" Constructor DelayNode
() Creates a new instance of an DelayNode object instance. Alternatively, you can use the BaseAudioContext.createDelay
() factory method. Properties Inherits properties from its parent, AudioNode. DelayNode.delayTime Read only Is an a-rate AudioParam representing the amount of delay to apply, specified in seconds. Methods No specific methods; inherits methods from its parent, AudioNode. ...
...op -- see create-delay (you can also view the source code). If you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time. ...
...ps will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time. var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext
(); var synthDelay = audioCtx.createDelay(5.0); ... ...
...And 2 more matches
EXT_disjoint_timer_query - Web APIs
For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension should be available in WebGL1 contexts only. EXT_disjoint_timer_query_webgl2 is available in WebGL 2 contexts . In WebGL 2, the getQueryObject was renamed to getQueryParameter. ...
...T containing the query result. ext.QUERY_RESULT_AVAILABLE_EXT A GLboolean indicating whether or not a query result is available. ext.TIME_ELAPSED_EXT Elapsed time (in nanoseconds). ext.TIMESTAMP_EXT The current time. ext.GPU_DISJOINT_EXT A GLboolean indicating whether or not the GPU performed any disjoint operation. Methods This extension exposes eight new methods. ...
...LABLE_EXT A GLboolean indicating whether or not a query result is available. ext.TIME_ELAPSED_EXT Elapsed time (in nanoseconds). ext.TIMESTAMP_EXT The current time. ext.GPU_DISJOINT_EXT A GLboolean indicating whether or not the GPU performed any disjoint operation. Methods This extension exposes eight new methods. ext.createQueryEXT
() Creates a new WebGLQuery. ext.deleteQueryEXT
() Deletes a given WebGLQuery. ext.isQueryEXT
() Returns true if a given object is a WebGLQuery. ext.beginQueryEXT
() The timer starts when all commands prior to beginQueryEXT have been fully executed. ext.endQueryEXT
() The timer stops when all commands prior to endQueryEXT have been fully executed. ext.queryCounterEXT
() Records the current time into the corresponding query object. ...
...And 2 more matches
EffectTiming.fill - Web APIs
ning, while "forwards" ensures that once the animation's end time has been passed, the element will continue to be drawn in the state it was in at its last rendered frame. Note that authors are discouraged from using fill modes to persist the effect of an animation indefinitely. See the alternatives to fill modes section below for approaches that are simpler and more performant. Element.animate
(), and KeyframeEffect
() accept an object of timing properties including fill. The value of fill corresponds directly to fill in EffectTiming objects returned by getTiming
() in AnimationEffect and KeyframeEffect. Syntax var timingProperties = { fill: "none" | "forwards" | "backwards" | "both" | "auto" } Value A DOMString indicating the fill type to use in order to properly render an affected...
...e the animation isn't actively running. document.getElementById("animateButton").addEventListener("click", event => { document.getElementById("box").animate( boxRotationKeyframes, boxRotationTiming ); }, false); The rest of the code is pretty simple: it adds an event listener to the "Animate" button so that when it's clicked by the user, the box is animated by calling Element.animate
() on it, providing the boxRotationKeyframes and boxRotationTiming objects to describe the animation that should occur. Result Below we see what the result looks like. Notice how before the animation starts running, the box is upright, then upon clicking the "Animate!" button, the box is instantly rotated 90? to the left (to correspond to the first keyframe in the animation sequence). Then, when t...
...When used to persist the effect of an animation indefinitely, however, they have a number of drawbacks: The forwards fill of an animation (or backwards fill if the ani...
...And 2 more matches
Element.onfullscreenchange - Web APIs
r the fullscreenchange event that is fired when the element has transitioned into or out of full-screen mode. Syntax targetDocument.onfullscreenchange = fullscreenChangeHandler; Value An event handler for the fullscreenchange event, indicating that the element has changed in or out of full-screen mode. Example This example establishes a fullscreenchange event handler, handleFullscreenChange
(). ...
...full-screen mode. Example This example establishes a fullscreenchange event handler, handleFullscreenChange
(). This function determines which element it was called on by checking the value of event.target, then compares the document's fullscreenElement value to the element to see if they're the same node. This gives us a value, isFullscreen, which we pass into a function called adjustMyControls
(), which we imagine to be a function that makes adjustments to the app's user interface to present itself optimally when it's in full-screen mode versus being displayed in a window. ...
...hen compares the document's fullscreenElement value to the element to see if they're the same node. This gives us a value, isFullscreen, which we pass into a function called adjustMyControls
(), which we imagine to be a function that makes adjustments to the app's user interface to present itself optimally when it's in full-screen mode versus being displayed in a window. ...
...And 2 more matches
File and Directory Entries API - Web APIs
ment the synchronous API. Check the browser compatibility for any part of the API you use carefully, and see File and Directory Entries API support in Firefox for more details. Getting access to a file system There are two ways to get access to file systems defined in the current specification draft: When handling a drop event for drag and drop, you can call DataTransferItem.webkitGetAsEntry
() to get the FileSystemEntry for a dropped item. If the result isn't null, then it's a dropped file or directory, and you can use file system calls to work with it. The HTMLInputElement.webkitEntries property lets you access the FileSystemFileEntry objects for the currently selected files, but only if they are dragged-and-dropped onto the file chooser (bug 1326031). If HTMLInputElement.webkitdirec...
... file system. FileSystemEntry The basic interface representing a single entry in a file system. This is implemented by other interfaces which represent files or directories. FileSystemFileEntry Represents a single file in a file system. FileSystemDirectoryEntry Represents a single directory in a file system. FileSystemDirectoryReader Created by calling FileSystemDirectoryEntry.createReader
(), this interface provides the functionality which lets you read the contents of a directory. FileSystemFlags Defines a set of values which are used when specifying option flags when calling certain methods in the File and Directory Entries API. FileError Represents an error which is generated by asynchronous file system calls. There are also two global functions (which are not part of the ...
...ng option flags when calling certain methods in the File and Directory Entries API. FileError Represents an error which is generated by asynchronous file system calls. There are also two global functions (which are not part of the specification at this time and are implemented only by Google Chrome). They're available on the Window object and implemented in LocalFileSystem: requestFileSystem
() and resolveLocalFileSystemURL
(). Synchronous API The synchronous API is should only be used in Workers; these calls block until they're finished executing, and simply return the results instead of using callbacks. Using them on the main thread will block the browser, which is naughty. The interfaces below otherwise mirror the ones from the asynchronous API. FileSystemSync Represents a file ...
...And 2 more matches
FormData - Web APIs
The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send
() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data". You can also pass it directly to the URLSearchParams constructor if you want to generate query parameters in the way a <form> would do if it were using simple GET submission. ...
...XMLHttpRequest.send
() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data". You can also pass it directly to the URLSearchParams constructor if you want to generate query parameters in the way a <form> would do if it were using simple GET submission. An object implementing FormData can directly be used in a for...of structure, instead of entries
(): for (var p of myFormData) is equivalent to for (var p of myFormData.entries
()). Note: This feature is available in Web Workers. Constructor FormData
() Creates a new FormData object. Methods FormData.append
() Appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. ...
...d in a for...of structure, instead of entries
(): for (var p of myFormData) is equivalent to for (var p of myFormData.entries
()). Note: This feature is available in Web Workers. Constructor FormData
() Creates a new FormData object. Methods FormData.append
() Appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. FormData.delete
() Deletes a key/value pair from a FormData object. FormData.entries
() Returns an iterator allowing to go through all key/value pairs contained in this object. FormData.get
() Returns the first value associated with a given key from within a FormData object. ...
...And 2 more matches
HTMLCanvasElement - Web APIs
ent.mozPrintCallback Is a function that is Initially null. Web content can set this to a JavaScript function that will be called when the canvas is to be redrawn while the page is being printed. When called, the callback is passed a "printState" object that implements the MozCanvasPrintState interface. The callback can get the context to draw to from the printState object and must then call done
() on it when finished. The purpose of mozPrintCallback is to obtain a higher resolution rendering of the canvas at the resolution of the printer being used. See this blog post. Methods Inherits methods from its parent, HTMLElement. HTMLCanvasElement.captureStream
() Returns a CanvasCaptureMediaStream that is a real-time video capture of the surface of the canvas. HTMLCanvasElement.getConte...
...n it when finished. The purpose of mozPrintCallback is to obtain a higher resolution rendering of the canvas at the resolution of the printer being used. See this blog post. Methods Inherits methods from its parent, HTMLElement. HTMLCanvasElement.captureStream
() Returns a CanvasCaptureMediaStream that is a real-time video capture of the surface of the canvas. HTMLCanvasElement.getContext
() Returns a drawing context on the canvas, or null if the context ID is not supported. A drawing context lets you draw on the canvas. ...
...t
() Returns a drawing context on the canvas, or null if the context ID is not supported. A drawing context lets you draw on the canvas. Calling getContext with "2d" returns a CanvasRenderingContext2D object, whereas calling it with "webgl" (or "experimental-webgl") returns a WebGLRenderingContext object. This context is only available on browsers that implement WebGL. HTMLCanvasElement.toDataURL
() Returns a data-URL containing a representation of the image in the format specified by the type parameter (defaults to png). The returned image is in a resolution of 96dpi. HTMLCanvasElement.toBlob
() Creates a Blob object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent. HTMLCanvasElement.transferContro...
...And 2 more matches
HTMLDialogElement.returnValue - Web APIs
lement interface gets or sets the return value for the <dialog>, usually to indicate which button the user pressed to close it. Syntax dialogInstance.returnValue = 'myReturnValue'; var myReturnValue = dialogInstance.returnValue; Value A DOMString representing the returnValue of the dialog. Examples The following example displays a button to open a <dialog> containing a form via the showModal
() method. From there, either button will close the dialog. <!-- Simple pop-up dialog box containing a form --> <dialog id="favDialog"> <form method="dialog"> <p><label>Favorite animal: <select name="favAnimal" required> <option></option> <option>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </se...
... <option></option> <option>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </select> </label></p> <menu> <button>Cancel</button> <button>Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function
() { var updateButton = document.getElementById('updateDetails'); var dialog = document.getElementById('favDialog'); dialog.returnValue = 'favAnimal'; function openCheck(dialog) { if (dialog.open) { console.log('Dialog open'); } else { console.log('Dialog closed'); } } function handleUserInput(returnValue) { if...
... Specifications Specification Status Comment HTML Living StandardThe definition of 'returnvalue' in that specification. Living Standard ...
...And 2 more matches
HTMLElement: transitioncancel event - Web APIs
ion. ...
...lobalEventHandlers.ontransitioncancel Examples This code gets an element that has a transition defined and adds a listener to the transitioncancel event: const transition = document.querySelector('.transition'); transition.addEventListener('transitioncancel',
() => { console.log('Transition canceled'); }); The same, but using the ontransitioncancel property instead of addEventListener
(): const transition = document.querySelector('.transition'); transition.ontransitioncancel =
() => { console.log('Transition canceled'); }; Live example In the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition"></div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,...
...ioncancel and transitionend events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends. ...
...And 2 more matches
HTMLElement: transitionend event - Web APIs
are 0s or neither is declared, there is no transition, and none of the transition events are fired. If the transitioncancel event is fired, the transitionend event will not fire. ...
.... ...
...ioncancel and transitionend events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends. ...
...And 2 more matches
HTMLImageElement - Web APIs
Properties Inherits properties from its parent, HTMLElement. HTMLImageElement.alt A DOMString ...
... Properties Inherits properties from its parent, HTMLElement. HTMLImageElement.alt A DOMString that reflects...
... Properties Inherits properties from its parent, HTMLElement. ...
...And 2 more matches
HTMLTableElement - Web APIs
y Is a DOMString containing a description of the purpose or the structure of the table. It reflects the obsolete summary attribute. HTMLTableElement.width Is a DOMString containing the length in pixels or in percentage of the desired width fo the entire table. It reflects the obsolete width attribute. Methods Inherits methods from its parent, HTMLElement. HTMLTableElement.createTHead
() Returns an HTMLElement representing the first <thead> that is a child of the element. If none is found, a new one is created and inserted in the tree immediately before the first element that is neither a <caption>, nor a <colgroup>, or as the last child if there is no such element. HTMLTableElement.deleteTHead
() Removes the first <thead> that is a child of the element. HTMLTableElement.creat...
...rns an HTMLElement representing the first <thead> that is a child of the element. If none is found, a new one is created and inserted in the tree immediately before the first element that is neither a <caption>, nor a <colgroup>, or as the last child if there is no such element. HTMLTableElement.deleteTHead
() Removes the first <thead> that is a child of the element. HTMLTableElement.createTFoot
() Returns an HTMLElement representing the first <tfoot> that is a child of the element. If none is found, a new one is created and inserted in the tree immediately before the first element that is neither a <caption>, a <colgroup>, nor a <thead>, or as the last child if there is no such element. HTMLTableElement.deleteTFoot
() Removes the first <tfoot> that is a child of the element. HTMLTableEl...
...ement representing the first <tfoot> that is a child of the element. If none is found, a new one is created and inserted in the tree immediately before the first element that is neither a <caption>, a <colgroup>, nor a <thead>, or as the last child if there is no such element. HTMLTableElement.deleteTFoot
() Removes the first <tfoot> that is a child of the element. HTMLTableElement.createCaption
() Returns an HTMLElement representing the first <caption> that is a child of the element. If none is found, a new one is created and inserted in the tree as the first child of the <table> element. HTMLTableElement.deleteCaption
() Removes the first <caption> that is a child of the element. HTMLTableElement.insertRow
() Returns an HTMLTableRowElement representing a new row of the table. It insert...
...And 2 more matches
Recommended Drag Types - Web APIs
Dragging Text For dragging text, use the text/plain type. The second data parameter should be the dragged string. ...
... dt = event.dataTransfer; dt.setData("text/html", "Hello there, <strong>stranger</strong>"); dt.setData("text/plain", "Hello there, stranger"); Dragging Files A local file is dragged using the application/x-moz-file type with a data value that is an nsIFile object. Non-privileged web pages canot retrieve or modify data of this type. Because a file is not a string, you must use the mozSetDataAt
() method to assign the data. Similarly, when retrieving the data, you must use the mozGetDataAt
() method. event.dataTransfer.mozSetDataAt("application/x-moz-file", file, 0); If possible, include the file URL of the file using both the text/uri-list and text/plain types. These types should be added afterward so that the more specific application/x-moz-file type has higher priority. Multiple file...
...nts.interfaces.nsIFile) { event.currentTarget.appendItem(file.leafName); } } </script> In this example, the event returns false only if the data transfer contains the application/x-moz-file type. During the drop event, the data associated with the file type is retrieved, and the filename of the file is added to the listbox. Note that the instanceof operator is used here as the mozGetDataAt
() method will return an nsISupports that needs to be checked and converted into an nsIFile. This is also a good extra check in case someone made a mistake and added a non-file for this type. Updates to DataTransfer.types The latest spec dictates that DataTransfer.types should return a frozen array of DOMStrings rather than a DOMStringList (this is supported in Firefox 52 and above). As a result,...
...And 2 more matches
History - Web APIs
toration Allows web applications to explicitly set default scroll restoration behavior on history navigation. This property can be either auto or manual. state Read only Returns an any value representing the state at the top of the history stack. This is a way to look at the state without having to wait for a popstate event. Methods The History interface doesn't inherit any methods. ...
...ait for a popstate event. Methods The History interface doesn't inherit any methods. back
() This asynchronous method goes to the previous page in session history, the same action as when the user clicks the browser's Back button. Equivalent to history.go(-1). Calling this method to go back beyond the first page in the session history has no effect and doesn't raise an exception. forward
() This asynchronous method goes to the next page in session history, the same action as when the user clicks the browser's Forward button; this is equivalent to history.go(1). ...
... page in the session history has no effect and doesn't raise an exception. forward
() This asynchronous method goes to the next page in session history, the same action as when the user clicks the browser's Forward button; this is equivalent to history.go(1). Calling this method to go forward beyond the most recent page in the session history has no effect and doesn't raise an exception. go
() Asynchronously loads a page from the session history, identified by its relative location to the current page, for example -1 for the previous page or 1 for the next page. ...
...And 2 more matches
IDBRequest.transaction - Web APIs
ansaction. ...
... openRequest.onupgradeneeded = function(event) { console...
... openRequest.onupgradeneeded = function(event) { console.log(openRequest.transaction.mode); // Will log "versionchange". var db = openReques...
...And 2 more matches
IDBTransaction.onabort - Web APIs
king example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...xample live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
... open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...And 2 more matches
LocalFileSystem - Web APIs
The LocalFileSystem interface of the File System API gives you access to a sandboxed file system. The methods are implemented by window and worker objects. Basic concepts This section includes a few key concepts for the methods. Creating new storage You request access to a sandboxed file system by calling window.requestFileSystem
(). The argument of a successful callback is the FileSystem object, which has two properties: the name and root of the file system. You can call the method more than once if you want to create two file systems: one that's temporary and one that's persistent. (To learn more about the storage types, see the Basic Concepts article.) In most cases, you need to create only one file system, but in a few cases, it might be useful to create a second one. For...
...e a second one. For example, if you were to create a mail app, you might create a temporary storage for caching assets (like images and attachments) to speed up performance, while creating persistent storage for unique data--such as drafts of emails that were composed while offline--that should not be lost before they are backed up into the cloud. Using persistent storage The requestFileSystem
() method lets you ask for PERSISTENT or TEMPORARY storage. Persistent storage is storage that stays in the browser unless the app or the user removes it, but the user must grant you permission before you can use it. In contrast, temporary storage is automatically granted without any user permission, but it can be expunged by the browser at any time. To use PERSISTENT storage with the File System A...
...navigator.webkitPersistentStorage.requestQuota ( requestedBytes, function(grantedBytes) { window.requestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler); }, function(e) { console.log('Error', e); } ); Your user must grant your app permission to store data locally before your app can use persistent storage. Once your user grants it, you don't need to call requestQuota
() again. Subsequent calls are a noop. Another API, the Quota Management API, lets you query an origin's current quota usage and allocation using window.webkitPersistentStorage.queryUsageAndQuota
(). To learn more, see this StackOverflow Answer. (An older version of the API is described at Managing HTML5 Offline Storage.) Working within a single origin The file system is sandboxed to a single ori...
...And 2 more matches
MediaQueryList - Web APIs
The resulting object handles sending notifications to listeners when the media query state changes (i.e. when the media query test starts or stops evaluating to true). ...
...erties The MediaQueryList interface inherits properties from its parent interface, EventTarget. matchesRead only A Boolean that returns true if the document currently matches the media query list, or false if not. mediaRead only A DOMString representing a serialized media query. Methods The MediaQueryList interface inherits methods from its parent interface, EventTarget. ...
...edia query. Methods The MediaQueryList interface inherits methods from its parent interface, EventTarget. addListener
() Adds to the MediaQueryList a callback which is invoked whenever the media query status--whether or not the document matches the media queries in the list--changes. This method exists primarily for backward compatibility; if possible, you should instead use addEventListener
() to watch for the change event. removeListener
() Removes the specified listener callback from the callbacks to be invoked when the MediaQueryList changes media query status, which happens any time the document switches between matching and not matching the media queries listed in the MediaQueryList. This method has been kept for backward compatibility; if possible, you should generally use remov...
...And 2 more matches
MediaSession - Web APIs
eliver the metadata provided by calling MediaSession to the device in order to be controllable using the global user interface. Properties metadata Returns an instance of MediaMetadata which contains rich media metadata, for display in a platform UI. playbackState Indicates whether the current media session is playing. Valid values are none, paused, or playing. Methods setActionHandler
() Sets an event handler for a media session action, such as play or pause. See the method page for a full list. setPositionState
() Sets the current playback position and speed of the media currently being presented. Examples The following example creates a new media session and assigns action handlers to it: if ('mediaSession' in navigator){ navigator.mediaSession.metadata = new MediaMetad...
...tly being presented. ...
...w media session and assigns action handlers to it: if ('mediaSession' in navigator){ navigator.mediaSession.metadata = new MediaMetadata({ title: "Podcast Episode Title", artist: "Podcast Host", album: "Podcast Name", artwork: [{src: "podcast.jpg"}] }); navigator.mediaSession.setActionHandler('play', function
() {}); navigator.mediaSession.setActionHandler('pause', function
() {}); navigator.mediaSession.setActionHandler('seekbackward', function
() {}); navigator.mediaSession.setActionHandler('seekforward', function
() {}); navigator.mediaSession.setActionHandler('previoustrack', function
() {}); navigator.mediaSession.setActionHandler('nexttrack', function
() {}); } The following example sets up event handlers for pausing and playing: var audio = document.queryS...
...And 2 more matches
MediaStreamConstraints.audio - Web APIs
The MediaStreamConstraints dictionary's audio property is used to indicate what kind of audio track, if any, should be included in the MediaStream returned by a call to getUserMedia
(). To learn more about how constraints work, see Capabilities, constraints, and settings. Syntax var audioConstraints = true | false | MediaTrackConstraints; Value The value of the audio property can be specified as either of two types: Boolean If a Boolean value is specified, it simply indicates whether or not an audio track should be included in the returned stream; if it's true, an audio track is included; if no audio source is available or if permission is not given to use the audio source, the call to getUserMedia
() will fail. If false, no audio track is included. MediaTrackConstraints A cons...
... included. MediaTrackConstraints A constraints dictionary detailing the preferable and/or required values or ranges of values for the track's constrainable properties. If you specify constraints, an audio track meeting the constraints is required. Examples For browsers with Feature Policy enabled, the samples below need the microphone feature enabled. See Security in MediaDevices.getUserMedia
() for details and examples on how to configure this. Using a Boolean value In this example, we provide a simple value of true for the audio property. This tells getUserMedia
() that we require an audio track, but we don't care about any specifics beyond that. HTML content <p>Click the start button below to begin the demonstration.</p> <div id="startButton" class="button"> Start </div> <audio ...
... ...
...And 2 more matches
MediaStreamConstraints.video - Web APIs
The MediaStreamConstraints dictionary's video property is used to indicate what kind of video track, if any, should be included in the MediaStream returned by a call to getUserMedia
(). To learn more about how constraints work, see Capabilities, constraints, and settings. Syntax var videoConstraints = true | false | MediaTrackConstraints; Value The value of the video property can be specified as either of two types: Boolean If a Boolean value is specified, it simply indicates whether or not a video track should be included in the returned stream; if it's true, a video track is included; if no video source is available or if permission is not given to use the video source, the call to getUserMedia
() will fail. If false, no video track is included. MediaTrackConstraints A constr...
...o video track is included. MediaTrackConstraints A constraints dictionary detailing the preferable and/or required values or ranges of values for the track's constrainable properties. If you specify constraints, a video track meeting these constraints is required. Examples Using a Boolean value In this example, we provide a simple value of true for the video property. This tells getUserMedia
() that we require a video track, but we don't care about any specifics beyond that. HTML content <p>Click the start button below to begin the demonstration.</p> <div id="startButton" class="button"> Start </div> <video id="video" width="160" height="120" autoplay></video><br> <div id="log"></div> CSS content body { font: 14px "Open Sans", "Arial", sans-serif; } video { margin-top: 20px;...
... ...
...And 2 more matches
Microdata DOM API - Web APIs
ment'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 representing an item has been obtained, its properties can be extracted using the properties IDL attribute. This attribute returns an HTMLPropertiesCollection, which can be enumerated to go through each el...
... once usingits getValues method, which returns an array of all the values. Code example In an earlier example, a "http://example.org/animals#cat" item had two "http://example.com/color" values. This script looks up the first such item and then lists all its values. var cat = document.getItems('http://example.org/animals#cat')[0]; var colors = cat.properties['http://example.com/color'].getValues
(); var result; if (colors.length == 0) { result = 'Color unknown.'; } else if (colors.length == 1) { result = 'Color: ' + colors[0]; } else { result = 'Colors:'; for (var i = 0; i < colors.length; i += 1) result += ' ' + colors[i]; } It's also possible to get a list of all the property names using the object's names IDL attribute. Code example This example creates a big list with a n...
...; for (var i = 0; i < colors.length; i += 1) result += ' ' + colors[i]; } It's also possible to get a list of all the property names using the object's names IDL attribute. Code example This example creates a big list with a nested list for each item on the page, each with all of the property names used in that item. ...
...And 2 more matches
Microsoft API extensions - Web APIs
Microsoft browsers (Internet Explorer, and in a few cases, Microsoft Edge) support a number of special Microsoft extensions to the otherwise standard DOM APIs. These extensions are prefixed with MS or ms. Note: These APIs will only work in Microsoft applications, and are not on a standards track. ...
...of special Microsoft extensions to the otherwise standard DOM APIs. These extensions are prefixed with MS or ms. Note: These APIs will only work in Microsoft applications, and are not on a standards track. ...
...ensions are prefixed with MS or ms. Note: These APIs will only work in Microsoft applications, and are not on a standards track. ...
...And 2 more matches
MouseEvent - Web APIs
The MouseEvent interface represents events that occur due to the user interacting with a pointing device (such as a mouse). Common events using this interface include click, dblclick, mouseup, mousedown. MouseEvent derives from UIEvent, which in turn derives from Event. Though the MouseEvent.initMouseEvent
() method is kept for backward compatibility, creating of a MouseEvent object should be done using the MouseEvent
() constructor. Several more specific events are based on MouseEvent, including WheelEvent and DragEvent. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" pr...
... Properties This interface also inherits properties of its parents, UIEvent and Event. MouseEvent.altKey Read only Returns true if the alt key was down when the mouse event was fired. MouseEvent.button Read only The button number that was pressed (if applicable) when the mouse event was fired. MouseEvent.buttons Read only The buttons being depressed (if...
...r MouseEvent.clientX. MouseEvent.y Read only Alias for MouseEvent.clientY Constants MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN Read only Minimum force necessary for a normal click MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN Read only Minimum force necessary for a force click Methods This interface also inherits methods of its parents, UIEvent and Event. MouseEvent.getModifierState
() Returns the current state of the specified modifier key. See the KeyboardEvent.getModifierState
() for details. MouseEvent.initMouseEvent
() Initializes the value of a MouseEvent created. If the event has already being dispatched, this method does nothing. Example This example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods...
...And 2 more matches
NamedNodeMap - Web APIs
h called NamedNodeMap, this interface doesn't deal with Node objects but with Attr objects, which were originally a specialized class of Node, and still are in some implementations. Properties This interface doesn't inherit any property. NamedNodeMap.length Read only Returns the amount of objects in the map. Methods This interface doesn't inherit any method. ...
...ttr objects, which were originally a specialized class of Node, and still are in some implementations. Properties This interface doesn't inherit any property. NamedNodeMap.length Read only Returns the amount of objects in the map. Methods This interface doesn't inherit any method. NamedNodeMap.getNamedItem
() Returns a Attr, corresponding to the given name. NamedNodeMap.setNamedItem
() Replaces, or adds, the Attr identified in the map by the given name. ...
... Properties This interface doesn't inherit any property. NamedNodeMap.length Read only Returns the amount of objects in the map. Methods This interface doesn't inherit any method. NamedNodeMap.getNamedItem
() Returns a Attr, corresponding to the given name. NamedNodeMap.setNamedItem
() Replaces, or adds, the Attr identified in the map by the given name. NamedNodeMap.removeNamedItem
() Removes the Attr identified by the given map. NamedNodeMap.item
() Returns the Attr at the given index, or null if the index is higher or equal to the number of nodes. NamedNodeMap.getNamedItemNS
() Returns a Attr identified by a namespace and related local name. NamedNodeMap.setNamedItemNS
() Replaces, or adds, the Attr identified in the map by the given namespace and related local name. Na...
...And 2 more matches
Navigator - Web APIs
g to the nearest power of 2 and dividing that number by 1024. Navigator.doNotTrack Reports the value of the user's do-not-track preference. When this value is "yes", your web site or application should not track the user. Navigator.mediaDevices Returns a reference to a MediaDevices object which can then be used to get information about available media devices (MediaDevices.enumerateDevices
()), find out what constrainable properties are supported for media on the user's computer and user agent (MediaDevices.getSupportedConstraints
()), and to request access to media using MediaDevices.getUserMedia
(). Navigator.mediaSession Returns MediaSession object which can be used to provide metadata that can be used by the browser to present information about the currently-playing media to the u...
...s the vendor name of the current browser (e.g., "Netscape6"). Navigator.vendorSub Returns the vendor version number (e.g. "6.1"). Navigator.webkitPointer Returns a PointerLock object for the Mouse Lock API. Methods Doesn't inherit any method, but implements those defined in NavigatorID, NavigatorContentUtils, NavigatorUserMedia, and NavigatorStorageUtils. Standard Navigator.canShare
() Returns true if a call to Navigator.share
() would succeed. Navigator.getUserMedia
() After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer. Navigator.registerContentHandler
() Obsolete since Gecko 59 Allows web sites to register themselves as a possible handler for a given MIME type. Navigator.registerPr...
...rue if a call to Navigator.share
() would succeed. Navigator.getUserMedia
() After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer. Navigator.registerContentHandler
() Obsolete since Gecko 59 Allows web sites to register themselves as a possible handler for a given MIME type. Navigator.registerProtocolHandler
() Allows web sites to register themselves as a possible handler for a given protocol. Navigator.requestMediaKeySystemAccess
() Returns a Promise for a MediaKeySystemAccess object. Navigator.sendBeacon
() Used to asynchronously transfer a small amount of data using HTTP from the User Agent to a web server. Navigator.share
() Invokes the native sharing mechanism of the current platform. Navi...
...And 2 more matches
NotificationEvent - Web APIs
Properties Inherits properties from its ancestor, Event. ...
... notification that was clicked to fire the event. NotificationEvent.action Read only Returns the string ID of the notification button the user clicked. This value returns an empty string if the user clicked the notification somewhere other than an action button, or the notification does not have a button. Methods Inherits methods from its parent, ExtendableEvent. ...
... an action button, or the notification does not have a button. Methods Inherits methods from its parent, ExtendableEvent. ExtendableEvent.waitUntil
() Extends the lifetime of the event. Tells the browser that work is ongoing. ...
...And 2 more matches
Page Visibility API - Web APIs
dden. Pages only become hidden when the user switches tabs or minimizes the browser window containing the tab. Policies in place to aid background page performance Separately from the Page Visibility API, user agents typically have a number of policies in place to mitigate the performance impact of background or hidden tabs. These may include: Most browsers stop sending requestAnimationFrame
() callbacks to background tabs or hidden <iframe>s in order to improve performance and battery life. Timers such as setTimeout
() are throttled in background/inactive tabs to help improve performance. See Reasons for delays longer than specified for more details. Budget-based background timeout throttling is now available in modern browsers (Firefox 58+, Chrome 57+), placing an additional limit on...
...den !== "undefined") { hidden = "msHidden"; visibilityChange = "msvisibilitychange"; } else if (typeof document.webkitHidden !== "undefined") { hidden = "webkitHidden"; visibilityChange = "webkitvisibilitychange"; } var videoElement = document.getElementById("videoElement"); // If the page is hidden, pause the video; // if the page is shown, play the video function handleVisibilityChange
() { if (document[hidden]) { videoElement.pause
(); } else { videoElement.play
(); } } // Warn if the browser doesn't support addEventListener or the Page Visibility API if (typeof document.addEventListener === "undefined" || hidden === undefined) { console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API."); } else { // Hand...
...ndefined" || hidden === undefined) { console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API."); } else { // Handle page visibility change document.addEventListener(visibilityChange, handleVisibilityChange, false); // When the video pauses, set the title. ...
...And 2 more matches
PaymentRequest: paymentmethodchange event - Web APIs
mentmethodchange event is fired to let you know about the change. Bubbles No Cancelable No Interface PaymentMethodChangeEvent Event handler property onpaymentmethodchange Examples Let's take a look at an example. This code creates a new PaymentRequest, adds a handler for the paymentmethodchange event by calling the request's addEventListener
(), then calls show
() to present the payment interface to the user. The code assumes the existence of a method detailsForShipping
(), which returns a PaymentDetailsUpdate object containing the shipping options for the ground shipping method, in the form found in the PaymentShippingOption dictionary. By doing so, the payment form defaults to the ground shipping method. const options = { requestShi...
...ipping method, in the form found in the PaymentShippingOption dictionary. By doing so, the payment form defaults to the ground shipping method. ...
...ing: true }; const paymentRequest = new PaymentRequest(paymentMethods, detailsForShipping("ground"), options); paymentRequest.addEventListener("paymentmethodchange", handlePaymentChange, false); paymentRequest.show
() .then(response => response.complete("success")) .catch(err => console.log("Error handling payment request: " + err)); The event handler function itself, handlePaymentChange
(), looks like this: handlePaymentChange = event => { const detailsUpdate = {}; if (event.methodName === "https://apple.com/apple-pay") { const serviceFeeInfo = calculateServiceFee(event.methodDetails); Object.assign(detailsUpdate, serviceFeeInfo); } event.updateWith(detailsUpdate); }, false); This begins by looking at the event's methodName property; if that indicates that the ...
...And 2 more matches
PaymentResponse - Web APIs
onse.methodName Read only Secure context Returns the payment method identifier for the payment method that the user selected, for example, Visa, Mastercard, Paypal, etc.. PaymentResponse.payerEmail Read only Secure context Returns the email address supplied by the user. This option is only present when the requestPayerEmail option is set to true in the options parameter of the PaymentRequest
() constructor. PaymentResponse.payerName Read only Secure context Returns the name supplied by the user. This option is only present when the requestPayerName option is set to true in the options parameter of the PaymentRequest
() constructor. PaymentResponse.payerPhone Read only Secure context Returns the phone number supplied by the user. This option is only present when the requestPayerPhon...
...turns the name supplied by the user. This option is only present when the requestPayerName option is set to true in the options parameter of the PaymentRequest
() constructor. PaymentResponse.payerPhone Read only Secure context Returns the phone number supplied by the user. This option is only present when the requestPayerPhone option is set to true in the options parameter of the PaymentRequest
() constructor. PaymentResponse.requestId Read only Secure context Returns the identifier of the PaymentRequest that produced the current response. This is the same value supplied in the PaymentRequest
() constructor by details.id. PaymentResponse.shippingAddress Read only Secure context Returns the shipping Address supplied by the user. This option is only present when the requestShipping opti...
...xt Returns the identifier of the PaymentRequest that produced the current response. This is the same value supplied in the PaymentRequest
() constructor by details.id. PaymentResponse.shippingAddress Read only Secure context Returns the shipping Address supplied by the user. This option is only present when the requestShipping option is set to true in the options parameter of the PaymentRequest
() constructor. PaymentResponse.shippingOption Read only Secure context Returns the ID attribute of the shipping option selected by the user. ...
...And 2 more matches
PhotoCapabilities - Web APIs
Properties PhotoCapabilities.redEyeReduction Read only Returns one of "never", "always", or "controllable". The "controllable" value means the device's read-eye reduction is controllable by the user. ...
...s.imageWidth Read only Returns a MediaSettingsRange object indicating the image width range supported by the user agent. PhotoCapabilities.fillLightMode Read only Returns an array of available fill light options. Options may include auto, off, or flash. Example The following example, extracted from Chrome's Image Capture / Photo Resolution Sample, uses the results from getPhotoCapabilities
() to modify the size of an input range. This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. const input = document.querySelector('input[type="range"]'); var imageCapture; navigator.mediaDevices.getUserMedia({video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream; const track = m...
... input range. This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. ...
...And 2 more matches
PushManager - Web APIs
This interface is accessed via the ServiceWorkerRegistration.pushManager property. Note: This interface replaces functionality previously offered by the obsolete PushRegistrationManager interface. Properties PushManager.supportedContentEncodings Returns an array of supported content codings that can be used to encrypt the payload of a push message. Methods PushManager.getSubscription
() Retrieves an existing push subscription. It returns a Promise that resolves to a PushSubscription object containing details of an existing subscription. If no existing subscription exists, this resolves to a null value. PushManager.permissionState
() Returns a Promise that resolves to the permission state of the current PushManager, which will be one of 'granted', 'denied', or 'prompt'. PushMa...
...existing push subscription. It returns a Promise that resolves to a PushSubscription object containing details of an existing subscription. If no existing subscription exists, this resolves to a null value. PushManager.permissionState
() Returns a Promise that resolves to the permission state of the current PushManager, which will be one of 'granted', 'denied', or 'prompt'. PushManager.subscribe
() Subscribes to a push service. It returns a Promise that resolves to a PushSubscription object containing details of a push subscription. ...
...of the current PushManager, which will be one of 'granted', 'denied', or 'prompt'. PushManager.subscribe
() Subscribes to a push service. It returns a Promise that resolves to a PushSubscription object containing details of a push subscription. A new push subscription is created if the current service worker does not have an existing subscription. Deprecated methods PushManager.hasPermission
() Returns a Promise that resolves to the PushPermissionStatus of the requesting webapp, which will be one of granted, denied, or default. Replaced by PushManager.permissionState
(). PushManager.register
() Subscribes to a push subscription. Replaced by PushManager.subscribe
(). PushManager.registrations
() Retrieves existing push subscriptions. Replaced by PushManager.getSubscription
(). Pus...
...And 2 more matches
RTCConfiguration - Web APIs
The options include ICE server and transport settings and identity information. ...
... The options include ICE server and transport settings and identity information. ...
...cate is used by a given connection, providing certificates for multiple algorithms may improve the odds of successfully connecting in some circumstances. See Using certificates below for additional information. This configuration option cannot be changed after it is first specified; once the certificates have been set, this property is ignored in future calls to RTCPeerConnection.setConfiguration
(). iceCandidatePoolSize Optional An unsigned 16-bit integer value which specifies the size of the prefetched ICE candidate pool. The default value is 0 (meaning no candidate prefetching will occur). You may find in some cases that connections can be established more quickly by allowing the ICE agent to start fetching ICE candidates before you start trying to connect, so that they're already ava...
...And 2 more matches
RTCIceCandidate.usernameFragment - Web APIs
The read-only usernameFragment property on the RTCIceCandidate interface is a string indicating the username fragment ("ufrag") that uniquely identifies a single ICE interaction session. This value is specified when creating the RTCIceCandidate by setting the corresponding usernameFragment value in the RTCIceCandidateInit object when creating a new candidate with new RTCIceCandidate
(). Note that 24 bits of the username fragment are required to be randomized by the browser. See Randomization below for details. If you instead call RTCIceCandidate
() with a string parameter containing the candidate m-line text, the value of usernameFragment is extracted from the m-line. Syntax var ufrag = RTCIceCandidate.usernameFragment; Value A DOMString containing the username fragment (usually referre...
...TC infrastructure will filter out obsolete candidates for you after an ICE restart, you can do it yourself if you're trying to absolutely minimize the number of messages going back and forth. To do so, you can compare the value of usernameFragment to the current usernameFragment being used for the connection after receiving the candidate from the signaling server and before caling addIceCandidate
() to add it to the set of possible candidates. When the web app receives a message from the signaling server that includes a candidate to be added to the RTCPeerConnection, you can (and generally should) simply call addIceCandidate
(). There's not typically a need to manually worry about filtering the candidates. However, let's imagine that we do need to minimize traffic. The function below, ssNew...
...t to the set of possible candidates. When the web app receives a message from the signaling server that includes a candidate to be added to the RTCPeerConnection, you can (and generally should) simply call addIceCandidate
(). There's not typically a need to manually worry about filtering the candidates. However, let's imagine that we do need to minimize traffic. The function below, ssNewCandidate
(), is called when a message, signalMsg, arrives from the signaling server that contains an ICE candidate to be added to the RTCPeerConnection. ...
...And 2 more matches
RTCPeerConnection: negotiationneeded event - Web APIs
the RTCPeerConnection when media is first added to the connection. This starts the process of ICE negotiation by instructing your code to begin exchanging ICE candidates through the signaling server. See Signaling transaction flow in Signaling and video calling for a description of the signaling process that begins with a negotiationneeded event. ...
...ansaction flow in Signaling and video calling for a description of the signaling process that begins with a negotiationneeded event. Examples In this example, we use addEventListener
() to create an event handler for negotiationneeded. Its role is to create an SDP offer and send it through the signaling channel to the remote peer. ...
... the signaling process that begins with a negotiationneeded event. Examples In this example, we use addEventListener
() to create an event handler for negotiationneeded. Its role is to create an SDP offer and send it through the signaling channel to the remote peer. pc.addEventListener("negotiationneeded", ev => { pc.createOffer
() .then(offer => return pc.setLocalDescription(offer)) .then(
() => sendSignalingMessage({ type: "video-offer", sdp: pc.localDescription })) .catch(err => { /* handle error */ ); }, false); After creating the offer, the local end is configured by calling RTCPeerConnection.setLocalDescription
(); then a signaling message is created and sent to the remote peer through the signaling server, to share that offer with the other peer. The other pee...
...And 2 more matches
Reporting API - Web APIs
Reporting observers Reports can also be obtained via ReportingObserver objects created via JavaScript inside the website you are aiming to get reports on. This method is not as failsafe as the Report-To method described above -- any page crash could stop you retrieving the reports -- but it is easier to set up, and more flexible. A ReportingObserver object is created using the ReportingObserver
() constructor, which is passed two parameters: A callback function that has available as parameters the reports available in the observer's report queue, and a copy of the same ReportingObserver object, so observation can be controlled directly from inside the callback. The callback runs when observation starts An options dictionary that allows you to specify the type of reports to collect, and...
...n be controlled directly from inside the callback. The callback runs when observation starts An options dictionary that allows you to specify the type of reports to collect, and whether the reports that were generated before the observer was able to be created should be observable (buffered: true). Methods are then available on the observer to start collecting reports (ReportingObserver.observe
()), retrieve the reports currently in the report queue (ReportingObserver.takeRecords
()), and disconnect the observer so it can no longer collect records (ReportingObserver.disconnect
()). Reporting API interfaces ReportingObserver Create ReportingObserver instances using its constructor, which can then be used to collect and access reports. Report An object representing a single report. Re...
...ing due to a browser crash. Indicated by a Report.body property with a CrashReportBody return value. ...
...And 2 more matches
SVGAnimationElement - Web APIs
herits properties from its parent, SVGElement. SVGAnimationElement.targetElement Read only An SVGElement representing the element which is being animated. If no target element is being animated (for example, because the href specifies an unknown element) the value returned is null. Methods This interface also inherits methods from its parent, SVGElement. ...
...This interface also inherits methods from its parent, SVGElement. SVGAnimationElement.getStartTime
() Returns a float representing the begin time, in seconds, for this animation element's current interval, if it exists, regardless of whether the interval has begun yet. If there is no current interval, then a DOMException with code INVALID_STATE_ERR is thrown. SVGAnimationElement.getCurrentTime
() Returns a float representing the current time in seconds relative to time zero for the given time container. SVGAnimationElement.getSimpleDuration
() Returns a float representing the number of seconds for the simple duration for this animation. If the simple duration is undefined (e.g., the end time is indefinite), then a DOMException with code NOT_SUPPORTED_ERR is raised. SVGAnimationElement.
...float representing the current time in seconds relative to time zero for the given time container. SVGAnimationElement.getSimpleDuration
() Returns a float representing the number of seconds for the simple duration for this animation. If the simple duration is undefined (e.g., the end time is indefinite), then a DOMException with code NOT_SUPPORTED_ERR is raised. SVGAnimationElement.beginElement
() Creates a begin instance time for the current time. The new instance time is added to the begin instance times list. The behavior of this method is equivalent to beginElementAt(0). SVGAnimationElement.beginElementAt
() Creates a begin instance time for the current time plus the specified offset. The new instance time is added to the begin instance times list. SVGAnimationElement.endEle...
...And 2 more matches
SVGGraphicsElement: copy event - Web APIs
Cancelable Yes Interface ClipboardEvent Event handler property oncopy The event's default action is to copy the selection (if any) to the clipboard. A handler for this event can modify the clipboard contents by calling setData(format, data) on the event's ClipboardEvent.clipboardData property, and cancelling the event's default action using event.preventDefault
(). However, the handler cannot read the clipboard data. It's possible to construct and dispatch a synthetic copy event, but this will not affect the system clipboard. Example HTML <?xml version="1.0" encoding="UTF-8"?> <svg viewBox="0 0 100 30" width="600" height="320" xmlns="http://www.w3.org/2000/svg"> <text x="5" y="10" id="text-to-copy">Copy this text</text> <foreignObject x="5" y=...
... Clipboard API and events Working Draft Initial definition ...
... Clipboard API and events Working Draft Initial definition ...
...And 2 more matches
ScriptProcessorNode.bufferSize - Web APIs
As of the August 29 2014 Web Audio API spec publication, this feature has been marked as deprecated, and is soon to be replaced by Audio Workers. The bufferSize property of the ScriptProcessorNode interface returns an integer representing both the input and output buffer size, in sample-frames. Its value can be a power of 2 value in the range 256-16384. Syntax var audioCtx = new AudioContext
(); var scriptNode = audioCtx.createScriptProcessor(4096, 1, 1); console.log(scriptNode.bufferSize); Value An integer. Example The following example shows basic usage of a ScriptProcessorNode to take a track loaded via AudioContext.decodeAudioData
(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the AudioDestinationNode. For each ch...
...te noise, before setting that result to be the output sample in each case. ...
...be the output sample in each case. ...
...And 2 more matches
ScriptProcessorNode.onaudioprocess - Web APIs
s feature has been marked as deprecated, and is soon to be replaced by Audio Workers. The onaudioprocess event handler of the ScriptProcessorNode interface represents the EventHandler to be called for the audioprocess event that is dispatched to ScriptProcessorNode node types. An event of type AudioProcessingEvent will be dispatched to the event handler. Syntax var audioCtx = new AudioContext
(); var scriptNode = audioCtx.createScriptProcessor(4096, 1, 1); scriptNode.onaudioprocess = function
() { ... } Example The following example shows basic usage of a ScriptProcessorNode to take a track loaded via AudioContext.decodeAudioData
(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the AudioDestinationNode. For each channel and...
...se, before setting that result to be the output sample in each case. ...
... output sample in each case. ...
...And 2 more matches
ServiceWorkerGlobalScope - Web APIs
ered, 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" style="display: inline-block; position: relative; width: 100%; padding-bottom: 12.142857142857142%; vertical-align: middle; overflow: hidden;"><svg style="displa...
...t associated with the service worker. Events activate Occurs when a ServiceWorkerRegistration acquires a new ServiceWorkerRegistration.active worker. Also available via the ServiceWorkerGlobalScope.onactivate property. contentdelete Occurs when an item is removed from the Content Index. Also available via the ServiceWorkerGlobalScope.oncontentdelete property. ...
...The service worker can optionally send a response back via the MessagePort exposed in event.data.port, corresponding to the controlled page. Also available via the ServiceWorkerGlobalScope.onmessage property. notificationclick Occurs when a user clicks on a displayed notification. ...
...And 2 more matches
ServiceWorkerRegistration - Web APIs
en implemented anywhere. Event handlers ServiceWorkerRegistration.onupdatefound Read only An EventListener property called whenever an event of type updatefound is fired; it is fired any time the ServiceWorkerRegistration.installing property acquires a new service worker. Methods Also implements methods from its parent interface, EventTarget. ...
...operty called whenever an event of type updatefound is fired; it is fired any time the ServiceWorkerRegistration.installing property acquires a new service worker. Methods Also implements methods from its parent interface, EventTarget. ServiceWorkerRegistration.getNotifications
() Returns a Promise that resolves to an array of Notification objects. ServiceWorkerRegistration.showNotification
() Displays the notification with the requested title. ServiceWorkerRegistration.update
() Checks the server for an updated version of the service worker without consulting caches. ServiceWorkerRegistration.unregister
() Unregisters the service worker registration and returns a Promise. The service worker will finish any ongoing operations before it is unregistered. Examples In this example, t...
...hich it uses the service worker registration to listen for further changes to the service worker's state. If the service worker hasn't changed since the last time it was registered, then the updatefound event will not be fired. if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js') .then(function(registration) { registration.addEventListener('updatefound', function
() { // If updatefound is fired, it means that there's // a new service worker being installed. var installingWorker = registration.installing; console.log('A new service worker is being installed:', installingWorker); // You can listen for changes to the installing service worker's // state via installingWorker.onstatechange }); }) .catch(functio...
...And 2 more matches
ShadowRoot - Web APIs
The ShadowRoot interface of the Shadow DOM API is the root node of a DOM subtree that is rendered separately from a document's main DOM tree. You can retrieve a reference to an element's shadow root using its Element.shadowRoot property, provided it was created using Element.attachShadow
() with the mode option set to open. Properties ShadowRoot.delegatesFocus Read only Returns a boolean that indicates whether delegatesFocus was set when the shadow was attached (see Element.attachShadow
()). ShadowRoot.host Read only Returns a reference to the DOM element the ShadowRoot is attached to. ShadowRoot.innerHTML Sets or returns a reference to the DOM tree inside the ShadowRoot. ShadowRoot.mode Read only The mode of the ShadowRoot -- either open or closed. This defines whether or ...
...heets Read only Returns a StyleSheetList of CSSStyleSheet objects for stylesheets explicitly linked into, or embedded in a document. Methods The ShadowRoot interface includes the following methods defined on the DocumentOrShadowRoot mixin. Note that this is currently only implemented by Chrome; other browsers still implement them on the Document interface. ...
... interface includes the following methods defined on the DocumentOrShadowRoot mixin. Note that this is currently only implemented by Chrome; other browsers still implement them on the Document interface. DocumentOrShadowRoot.getSelection
() Returns a Selection object representing the range of text selected by the user, or the current position of the caret. DocumentOrShadowRoot.elementFromPoint
() Returns the topmost element at the specified coordinates. DocumentOrShadowRoot.elementsFromPoint
() Returns an array of all elements at the specified coordinates. DocumentOrShadowRoot.caretPositionFromPoint
() Returns a CaretPosition object containing the DOM node containing the caret, and caret's character offset within that node. Examples The following snippets are taken from our life-cyc...
...And 2 more matches
SpeechSynthesis.onvoiceschanged - Web APIs
The onvoiceschanged property of the SpeechSynthesis interface represents an event handler that will run when the list of SpeechSynthesisVoice objects that would be returned by the SpeechSynthesis.getVoices
() method has changed (when the voiceschanged event fires.) This may occur when speech synthesis is being done on the server-side and the voices list is being determined asynchronously, or when client-side voices are installed/uninstalled while a speech synthesis application is running. Syntax speechSynthesisInstance.onvoiceschanged = function
() { ... }; Examples This could be used to populate a list of voices that the user can choose between when the event fires (see our Speak easy synthesis demo.) Note that Firefox doesn't support it at present, and will just return a lis...
...uninstalled while a speech synthesis application is running. Syntax speechSynthesisInstance.onvoiceschanged = function
() { ... }; Examples This could be used to populate a list of voices that the user can choose between when the event fires (see our Speak easy synthesis demo.) Note that Firefox doesn't support it at present, and will just return a list of voices when SpeechSynthesis.getVoices
() is fired. With Chrome however, you have to wait for the event to fire before populating the list, hence the bottom if statement seen below. ...
...ces that the user can choose between when the event fires (see our Speak easy synthesis demo.) Note that Firefox doesn't support it at present, and will just return a list of voices when SpeechSynthesis.getVoices
() is fired. With Chrome however, you have to wait for the event to fire before populating the list, hence the bottom if statement seen below. ...
...And 2 more matches
Streams API - Web APIs
rt or end, chain streams together, handle errors and cancel streams as required, and react to the speed of the stream is being read at. The basic usage of Streams hinges around making responses available as streams. For example, the response Body returned by a successful fetch request can be exposed as a ReadableStream, and you can then read it using a reader created with ReadableStream.getReader
(), cancel it with ReadableStream.cancel
(), etc. More complicated uses involve creating your own stream using the ReadableStream
() constructor, for example to process data inside a service worker. You can also write data to streams using WritableStream. Note: You can find a lot more details about the theory and practice of streams in our articles -- Streams API concepts, Using readable streams, ...
...tableStream. Note: You can find a lot more details about the theory and practice of streams in our articles -- Streams API concepts, Using readable streams, and Using writable streams. Stream interfaces Readable streams ReadableStream Represents a readable stream of data. It can be used to handle response streams of the Fetch API, or developer-defined streams (e.g. a custom ReadableStream
() constructor). ReadableStreamDefaultReader Represents a default reader that can be used to read stream data supplied from a network (e.g. a fetch request). ReadableStreamDefaultController Represents a controller allowing control of a ReadableStream's state and internal queue. Default controllers are for streams that are not byte streams. Writable streams WritableStream Provides a standar...
...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. This ma...
...And 2 more matches
UIEvent - Web APIs
Several interfaces are direct or indirect descendants of this one: MouseEvent, TouchEvent, FocusEvent, KeyboardEvent, WheelEvent, InputEvent, and CompositionEvent. ...
... Several interfaces are direct or indirect descendants of this one: MouseEvent, TouchEvent, FocusEvent, KeyboardEvent, WheelEvent, InputEvent, and CompositionEvent. ...
... Properties This interface also inherits properties of its parent, Event. UIEvent.cancelBubble Is a Boolean indicating whether the bubbling of the event has been canceled or not. UIEvent.detailRead only Returns a long with details about the event, depending on the event type. UIEvent.isChar Read only Returns a Boolean indicating whether the event pr...
...And 2 more matches
URL - Web APIs
malize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL. You normally create a new URL object by specifying the URL as a string when calling its constructor, or by providing a relative URL and a base URL. You can then easily read the parsed components of the URL or make changes to the URL. If a browser doesn't yet support the URL
() constructor, you can access a URL object using the Window interface's Window.URL property. Be sure to check to see if any of your target browsers require this to be prefixed. Note: This feature is available in Web Workers. Constructor new URL
() Creates and returns a URL object referencing the URL specified using an absolute URL string, or a relative URL string and a base URL string. Prope...
...:'. search A USVString indicating the URL's parameter string; if any parameters are provided, this string includes all of them, beginning with the leading ? character. searchParams Read only A URLSearchParams object which can be used to access the individual query parameters found in search. username A USVString containing the username specified before the domain name. ...
...ginning with the leading ? character. searchParams Read only A URLSearchParams object which can be used to access the individual query parameters found in search. username A USVString containing the username specified before the domain name. Methods toString
() Returns a USVString containing the whole URL. It is a synonym for URL.href, though it can't be used to modify the value. toJSON
() Returns a USVString containing the whole URL. It returns the same string as the href property. Static methods createObjectURL
() Returns a DOMString containing a unique blob URL, that is a URL with blob: as its scheme, followed by an opaque string uniquely identifying the object in the browser. revokeObjectURL
() Revokes an object URL previously created using URL.createObjectURL
(). Usage...
...And 2 more matches
WEBGL_draw_buffers - Web APIs
The WEBGL_draw_buffers extension is part of the WebGL API and enables a fragment shader to write to several textures, which is useful for deferred shading, for example. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default. ...
... tutorial. Availability: This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default. In WebGL 2, the constants are available without the "WEBGL" suffix and the new GLSL built-ins require GLSL #version 300 es. Constants This extension exposes new constants, which can be used in the gl.framebufferRenderbuffer
(), gl.framebufferTexture2D
(), gl.getFramebufferAttachmentParameter
() ext.drawBuffersWEBGL
(), and gl.getParameter
() methods. ext.COLOR_ATTACHMENT0_WEBGL ext.COLOR_ATTACHMENT1_WEBGL ext.COLOR_ATTACHMENT2_WEBGL ext.COLOR_ATTACHMENT3_WEBGL ext.COLOR_ATTACHMENT4_WEBGL ext.COLOR_ATTACHMENT5_WEBGL ext.COLOR_ATTACHMENT6_WEBGL ext.COLOR_ATTACHMENT7_WEBGL ext.COLOR_ATTACHMENT8_WEBGL ext.COLOR_AT...
....DRAW_BUFFER12_WEBGL ext.DRAW_BUFFER13_WEBGL ext.DRAW_BUFFER14_WEBGL ext.DRAW_BUFFER15_WEBGL A GLenum returning a draw buffer. ext.MAX_COLOR_ATTACHMENTS_WEBGL A GLint indicating the maximum number of framebuffer color attachment points. ext.MAX_DRAW_BUFFERS_WEBGL A GLint indicating the maximum number of draw buffers. Methods This extension exposes one new method. ...
...And 2 more matches
WebGLQuery - Web APIs
cclusion queries and primitive queries are available. Another kind of queries are disjoint timer queries, which allow you to measure performance and profiling of your GPU. Disjoint timer queries are available with the EXT_disjoint_timer_query extension only. ...
... are available. Another kind of queries are disjoint timer queries, which allow you to measure performance and profiling of your GPU. Disjoint timer queries are available with the EXT_disjoint_timer_query extension only. ...
...ueries are disjoint timer queries, which allow you to measure performance and profiling of your GPU. Disjoint timer queries are available with the EXT_disjoint_timer_query extension only. ...
...And 2 more matches
Using shaders to apply color in WebGL - Web APIs
tire square was rendered as solid white. Let's say we want to render a gradient in which each corner of the square is a different color: red, blue, green, and white. The first thing to do is to establish these colors for the four vertices. To do this, we first need to create an array of vertex colors, then store it into a WebGL buffer. ...
...white. Let's say we want to render a gradient in which each corner of the square is a different color: red, blue, green, and white. The first thing to do is to establish these colors for the four vertices. To do this, we first need to create an array of vertex colors, then store it into a WebGL buffer. We'll do that by adding the following code to our initBuffers
() function: function initBuffers
(){ ... ...
...st need to create an array of vertex colors, then store it into a WebGL buffer. We'll do that by adding the following code to our initBuffers
() function: function initBuffers
(){ ... const colors = [ 1.0, 1.0, 1.0, 1.0, // white 1.0, 0.0, 0.0, 1.0, // red 0.0, 1.0, 0.0, 1.0, // green 0.0, 0.0, 1.0, 1.0, // blue ]; const colorBuffer = gl.createBuffer
(); gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW); return { position: positionBuffer, color: colorBuffer, }; } This code starts by creating a JavaScript array containing four 4-value vectors, one for each vertex color. Then a new WebGL buffer is allocated to store these colors, and the array is converted into ...
...And 2 more matches
WebXR application life cycle - Web APIs
user's device and browser are both capable of presenting the XR experience you want to provide. Make sure the WebXR API is available; if navigator.xr is undefined, you can assume the user's browser and/or device doesn't support WebXR. If it's not supported, disable any user interface used to activate XR features and abort any attempts to enter XR mode. Call navigator.xr.isSessionSupported
(), specifying the WebXR experience mode you want to provide: inline, immersive-vr, or immersive-ar, in order to determine whether or not the type of session you wish to provide is available. If the session type you want to use is available, provide the appropriate interface to the user to allow them to activate it. When the user requests the activation of WebXR functionality by engaging wi...
...ot the type of session you wish to provide is available. If the session type you want to use is available, provide the appropriate interface to the user to allow them to activate it. When the user requests the activation of WebXR functionality by engaging with the user interface enabled above, request an XRSession using the desired mode. ...
...er to allow them to activate it. When the user requests the activation of WebXR functionality by engaging with the user interface enabled above, request an XRSession using the desired mode. This is done by calling navigator.xr.requestSession
(), again specifying the string indicating the mode you want to enable: inline, immersive-vr, or immersive-ar. If the promise returned by requestSession
() resolves, use the new XRSession to manage the WebXR session for the duration of the WebXR experience. This will involve managing inputs, animations, and rendering. Call the XRSession method requestAnimationFrame
() to schedule the first frame render for the XR device. If your scene is complex, you should consider creating a Worker--or using one that you've previously created for this purp...
...And 2 more matches
WebXR permissions and security - Web APIs
, as well. Immersive presentation of VR First, any requests to activate the immersive-vr mode are rejected if the domain issuing the request does not have permission to enable an immersive session. This permission comes from the xr-spatial-tracking feature policy. Once that check is passed, the request to enter immersive-vr mode is allowed if all of the following are true: The requestSession
() call was issued by code executing within the handler for a user event, or the from the startup code for a user-launched web application. The document is considered trustworthy, in that it is responsible and is both currently active and has focus. The user's intent to enter immersive VR mode is well understood; see User intent below for details. If all of that is true, the promise returned by ...
...ed by code executing within the handler for a user event, or the from the startup code for a user-launched web application. The document is considered trustworthy, in that it is responsible and is both currently active and has focus. The user's intent to enter immersive VR mode is well understood; see User intent below for details. If all of that is true, the promise returned by requestSession
() is resolved, and the new XRSession object is passed into the fulfillment handler. Otherwise, an appropriate exception is thrown, such as SecurityError if the document doesn't have permission to enter immersive mode. Inline presentation When you request an XRSession with the mode set to inline, and any features are required or requested, the browser will only allow the session to be created if t...
... XRSession object is passed into the fulfillment handler. Otherwise, an appropriate exception is thrown, such as SecurityError if the document doesn't have permission to enter immersive mode. Inline presentation When you request an XRSession with the mode set to inline, and any features are required or requested, the browser will only allow the session to be created if the call to requestSession
() was made by code which is executing expressly due to user intent. Specifically: If the requestSession
() call isn't coming from within the handler executed in response to a user event, and is not being issued while launching a web application, the request is denied and false is delivered to the promise's fulfillment handler. If the document making the request isn't the one which is responsibl...
...And 2 more matches
Web Audio API best practices - Web APIs
fline or online) it is created with a state, which can be suspended, running, or closed. When working with an AudioContext, if you create the audio context from inside a click event the state should automatically be set to running. ...
...e, which can be suspended, running, or closed. When working with an AudioContext, if you create the audio context from inside a click event the state should automatically be set to running. ...
...lector('button'); button.addEventListener('click', function
() { const audioCtx = new AudioContext
(); }, false); If however, you create the context outside of a user gesture, its state will be set to suspended and it will need to be started after user interaction. We can use the same click event example here, test for the state of the context and start it, if it is suspended, using the resume
() method. ...
...And 2 more matches
Web Audio API - Web APIs
volume control like GainNode). AudioParam The AudioParam interface represents an audio-related parameter, like one of an AudioNode. It can be set to a specific value or a change in value, and can be scheduled to happen at a specific time and following a specific pattern. AudioParamMap Provides a maplike interface to a group of AudioParam interfaces, which means it provides the methods forEach
(), get
(), has
(), keys
(), and values
(), as well as a size property. BaseAudioContext The BaseAudioContext interface acts as a base definition for online and offline audio-processing graphs, as represented by AudioContext and OfflineAudioContext respectively. You wouldn't use BaseAudioContext directly -- you'd use its features via one of these two inheriting interfaces. The ended event The ended ...
...e interfaces. It is an AudioNode. OscillatorNode The OscillatorNode interface represents a periodic waveform, such as a sine or triangle wave. It is an AudioNode audio-processing module that causes a given frequency of wave to be created. AudioBuffer The AudioBuffer interface represents a short audio asset residing in memory, created from an audio file using the AudioContext.decodeAudioData
() method, or created with raw data using AudioContext.createBuffer
(). Once decoded into this form, the audio can then be put into an AudioBufferSourceNode. AudioBufferSourceNode The AudioBufferSourceNode interface represents an audio source consisting of in-memory audio data, stored in an AudioBuffer. It is an AudioNode that acts as an audio source. MediaElementAudioSourceNode The MediaElementA...
...e computer). If multiple audio tracks are present on the stream, the track whose id comes first lexicographically (alphabetically) is used. It is an AudioNode that acts as an audio source. MediaStreamTrackAudioSourceNode A node of type MediaStreamTrackAudioSourceNode represents an audio source whose data comes from a MediaStreamTrack. When creating the node using the createMediaStreamTrackSource
() method to create the node, you specify which track to use. This provides more control than MediaStreamAudioSourceNode. Defining audio effects filters Interfaces for defining effects that you want to apply to your audio sources. BiquadFilterNode The BiquadFilterNode interface represents a simple low-order filter. It is an AudioNode that can represent different kinds of filters, tone control...
...And 2 more matches
WorkerGlobalScope - Web APIs
ble via the WorkerGlobalScope.onrejectionhandled property. unhandledrejection An event handler for unhandled Promise rejection events. Also available via the WorkerGlobalScope.onunhandledrejection property. Methods This interface inherits methods from the EventTarget interface and WindowOrWorkerGlobalScope and WindowEventHandlers mixins. Standard methods WorkerGlobalScope.importScripts
() Imports one or more scripts into the worker's scope. You can specify as many as you'd like, separated by commas. For example: importScripts('foo.js', 'bar.js'); Non-standard methods WorkerGlobalScope.dump
() Allows you to write a message to stdout -- i.e. in your terminal. This is the same as Firefox's window.dump, but for workers. Methods implemented from elsewhere WindowOrWorkerGlo...
... or more scripts into the worker's scope. You can specify as many as you'd like, separated by commas. For example: importScripts('foo.js', 'bar.js'); Non-standard methods WorkerGlobalScope.dump
() Allows you to write a message to stdout -- i.e. in your terminal. This is the same as Firefox's window.dump, but for workers. Methods implemented from elsewhere WindowOrWorkerGlobalScope.atob
() Decodes a string of data which has been encoded using base-64 encoding. WindowOrWorkerGlobalScope.btoa
() Creates a base-64 encoded ASCII string from a string of binary data. ...
...ite a message to stdout -- i.e. in your terminal. This is the same as Firefox's window.dump, but for workers. Methods implemented from elsewhere WindowOrWorkerGlobalScope.atob
() Decodes a string of data which has been encoded using base-64 encoding. WindowOrWorkerGlobalScope.btoa
() Creates a base-64 encoded ASCII string from a string of binary data. WindowOrWorkerGlobalScope.clearInterval
() Cancels the repeated execution set using WindowOrWorkerGlobalScope.setInterval
(). WindowOrWorkerGlobalScope.clearTimeout
() Cancels the delayed execution set using WindowOrWorkerGlobalScope.setTimeout
(). WindowOrWorkerGlobalScope.createImageBitmap
() Accepts a variety of different image sources, and returns a Promise which resolves to an ImageBitmap. Optionally the source is cropped to the rec...
...And 2 more matches
WritableStreamDefaultWriter.ready - Web APIs
WritableStream is done writing and thus able to receive data before sending a binary chunk. The second also checks whether the the WritableStream is done writing, but this time because the writing must be finished before the writer can be closed. ...
...thus able to receive data before sending a binary chunk. The second also checks whether the the WritableStream is done writing, but this time because the writing must be finished before the writer can be closed. ...
...tion sendMessage(message, writableStream) { // defaultWriter is of type WritableStreamDefaultWriter var defaultWriter = writableStream.getWriter
(); var encoder = new TextEncoder
(); var encoded = encoder.encode(message, {stream: true}); encoded.forEach(function(chunk) { // Make sure the stream and its writer are able to // receive data. ...
...And 2 more matches
XRSession: selectend event - Web APIs
or handheld controller with an accelerometer. Bubbles Yes Cancelable No Interface XRInputSourceEvent Event handler property onselectend For details on how the selectstart, select, and selectend events work, and how you should react to them, see Primary actions in Inputs and input sources. Examples The following example uses addEventListener
() to establish handlers for the selection events: selectstart, selectend, and select. This snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. In this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. Only after completing those...
...election events: selectstart, selectend, and select. This snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. In this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. Only after completing those tasks does the onSelectionEvent
() function below dispatch the action out to a specialized function to handle things. After checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getPose
(). If the target ray pose was fetched successfully, the code then uses the value of Event property type to route control to an appropriate function to handle ...
...handle things. After checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getPose
(). If the target ray pose was fetched successfully, the code then uses the value of Event property type to route control to an appropriate function to handle the event which arrived: For selectstart events, a myBeginTracking
() function is called with the target ray pose's matrix. ...
...And 2 more matches
XRSession: selectstart event - Web APIs
handheld controller with an accelerometer. Bubbles Yes Cancelable No Interface XRInputSourceEvent Event handler property onselectstart For details on how the selectstart, select, and selectend events work, and how you should react to them, see Primary actions in Inputs and input sources. Examples The following example uses addEventListener
() to establish handlers for the selection events: selectstart, selectend, and select. This snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. In this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. Only after completing those...
...election events: selectstart, selectend, and select. This snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. In this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. Only after completing those tasks does the onSelectionEvent
() function below dispatch the action out to a specialized function to handle things. After checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getPose
(). If the target ray pose was fetched successfully, the code then uses the value of Event property type to route control to an appropriate function to handle ...
...handle things. After checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getPose
(). If the target ray pose was fetched successfully, the code then uses the value of Event property type to route control to an appropriate function to handle the event which arrived: For selectstart events, a myBeginTracking
() function is called with the target ray pose's matrix. ...
...And 2 more matches
XRSession: squeezeend event - Web APIs
controller with an accelerometer. Bubbles Yes Cancelable No Interface XRInputSourceEvent Event handler property onsqueezeend For details on how the squeezestart, squeeze, and squeezeend events work, and how you should react to them, see Primary squeeze actions in Inputs and input sources. Examples The following example uses addEventListener
() to establish handlers for the squeezeion events: squeezestart, squeezeend, and squeeze. This snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. In this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. Only after completing t...
...eezeion events: squeezestart, squeezeend, and squeeze. This snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. In this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. Only after completing those tasks does the onSqueezeEvent
() function below dispatch the action out to a specialized function to handle things. After checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getPose
(). If the target ray pose was fetched successfully, the code then uses the value of Event property type to route control to an appropriate function to handle ...
...andle things. After checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getPose
(). If the target ray pose was fetched successfully, the code then uses the value of Event property type to route control to an appropriate function to handle the event which arrived: For squeezestart events, a myBeginTracking
() function is called with the target ray pose's matrix. ...
...And 2 more matches
XRSession: squeezestart event - Web APIs
g triggers on hand controllers. Bubbles Yes Cancelable No Interface XRInputSourceEvent Event handler property onsqueezestart For details on how the squeezestart, squeeze, and squeezeend events work, and how you should react to them, see Primary squeeze actions in Inputs and input sources. Examples The following example uses addEventListener
() to establish handlers for the squeezeion events: squeezestart, squeezeend, and squeeze. This snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. In this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. Only after completing t...
...eezeion events: squeezestart, squeezeend, and squeeze. This snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. In this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. Only after completing those tasks does the onSqueezeEvent
() function below dispatch the action out to a specialized function to handle things. After checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getPose
(). If the target ray pose was fetched successfully, the code then uses the value of Event property type to route control to an appropriate function to handle ...
...andle things. After checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getPose
(). If the target ray pose was fetched successfully, the code then uses the value of Event property type to route control to an appropriate function to handle the event which arrived: For squeezestart events, a myBeginTracking
() function is called with the target ray pose's matrix. ...
...And 2 more matches
XRView.transform - Web APIs
With the transform, you can then position the view as a camera within the 3D scene. If you instead need the more traditional view matrix, you can get using view.transform.inverse.matrix; this gets the underlying matrix of the transform's inverse. ...
...space's origin. You can then use the inverse of this matrix to transform the objects in your scene to adjust their placement and orientation to simulate the viewer's movement through space. In this example, we see an outline of a code fragment used while rendering an XRFrame, which makes use of the view transform to place objects in the world during rendering. ...
... inverse of this matrix to transform the objects in your scene to adjust their placement and orientation to simulate the viewer's movement through space. In this example, we see an outline of a code fragment used while rendering an XRFrame, which makes use of the view transform to place objects in the world during rendering. ...
...And 2 more matches
XRWebGLLayer - Web APIs
r the scene for display on the device. In particular, it provides access to the WebGL framebuffer and viewport to ease access to the context. Although XRWebGLLayer is currently the only type of framebuffer layer supported by WebGL, it's entirely possible that future updates to the WebXR specification may allow for other layer types and corresponding image sources. Constructor new XRWebGLLayer
() Creates and returns a new XRWebGLLayer object for use by the specified XRSession, using a particular WebGLRenderingContext or WebGL2RenderingContext as the destination context. Properties antialias Read only A Boolean value indicating whether or not the WebGL context's framebuffer supports anti-aliasing. The specific type of anti-aliasing is determined by the user agent. framebuffer Read...
...on, using a particular WebGLRenderingContext or WebGL2RenderingContext as the destination context. Properties antialias Read only A Boolean value indicating whether or not the WebGL context's framebuffer supports anti-aliasing. The specific type of anti-aliasing is determined by the user agent. ...
...to the bindFrameBuffer
() method. framebufferWidth Read only Returns the width of the XRWebGLLayer's framebuffer. framebufferHeight Read only Returns the height of the layer's framebuffer. ignoreDepthValues Read only A Boolean which Indicates whether or not the WebXR compositor should make use of the contents of the layer's depth buffer while compositing the scene. Methods getViewport
() Returns a new XRViewport instance representing the position, width, and height to which the WebGL context's viewport must be set to contain drawing to the area of the framebuffer designated for the specified view's contents. In this way, for example, the rendering of the left eye's point of view and of the right eye's point of view are each placed into the correct parts of the framebuffer. Sta...
...And 2 more matches
Coordinate systems - CSS: Cascading Style Sheets
elector(".inner"); let log = document.querySelector(".log"); function setCoords(e, type) { let idX = type + "X"; let idY = type + "Y"; document.getElementById(idX).innerText = e[idX]; document.getElementById(idY).innerText = e[idY]; } A reference to the <div> inside the inner box which contains the paragraphs that will show the coordinate information is fetched into log. The setCoords
() function is designed to accept as input a MouseEvent and the name of the origin to use when obtaining the coordinates. The implementation is then quite simple. The variables idX and idY are set to strings with the names of the properties corresponding to the coordinates in the given coordinate system. For example, if the value of type is "page", then idX is "pageX" and idY is "pageY". Handling t...
...ccept as input a MouseEvent and the name of the origin to use when obtaining the coordinates. The implementation is then quite simple. The variables idX and idY are set to strings with the names of the properties corresponding to the coordinates in the given coordinate system. For example, if the value of type is "page", then idX is "pageX" and idY is "pageY". Handling the mouse events setCoords
() is called by the event handler for the various mouse events, named update
(); this is shown below. function update(e) { setCoords(e, "offset"); setCoords(e, "client"); setCoords(e, "page"); setCoords(e, "screen"); } inner.addEventListener("mouseenter", update, false); inner.addEventListener("mousemove", update, false); inner.addEventListener("mouseleave", update, false); The event handl...
... HTML The HTML for our example is below. ...
...And 2 more matches
font-variant-alternates - CSS: Cascading Style Sheets
ntax This property may take one of two forms: either the keyword normal or one or more of the other keywords and functions listed below, space-separated, in any order. Values normal This keyword deactivates alternate glyphs. historical-forms This keyword enables historical forms -- glyphs that were common in the past but not today. It corresponds to the OpenType value hist. ...
... keyword deactivates alternate glyphs. historical-forms This keyword enables historical forms -- glyphs that were common in the past but not today. It corresponds to the OpenType value hist. stylistic
() This function enables stylistic alternates for individual characters. The parameter is a font-specific name mapped to a number. It corresponds to the OpenType value salt, like salt 2. styleset
() This function enables stylistic alternatives for sets of characters. The parameter is a font-specific name mapped to a number. It corresponds to the OpenType value ssXY, like ss02. ...
...
() This function enables stylistic alternates for individual characters. The parameter is a font-specific name mapped to a number. It corresponds to the OpenType value salt, like salt 2. styleset
() This function enables stylistic alternatives for sets of characters. The parameter is a font-specific name mapped to a number. It corresponds to the OpenType value ssXY, like ss02. character-variant
() This function enables specific stylistic alternatives for characters. It is similar to styleset
(), but doesn't create coherent glyphs for a set of characters; individual characters will have independent and not necessarily coherent styles. The parameter is a font-specific name mapped to a number. It corresponds to the OpenType value cvXY, like cv02. swash
() This function enables swash glyphs. ...
...And 2 more matches
<shape> - CSS: Cascading Style Sheets
The <shape> CSS data type defines the specific form (shape) of a region. The region represents the part of an element to which the clip property applies. Note: <shape> and rect
() work in conjunction with clip, which has been deprecated in favor of clip-path. When possible, use clip-path and the <basic-shape> data type instead. Syntax The <shape> data type is specified using the rect
() function, which produces a region in the form of a rectangle. rect
() rect(top, right, bottom, left) Values top Is a <length> representing the offset for the top of the rectangle relative to the top border of the element's box. right Is a <length> representing the offset for the right of the rectangle relative to the left border of the element's box. bottom Is a <length> representing t...
... 37Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 14Safari iOS Full support 1Samsung Internet Android Full support 1.0rect
() DeprecatedChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Notes Full support 5.5Notes Notes For Internet Explorer versions 5.5 through 7, t...
...For Internet Explorer 8 and later versions, only the standard comma-separated syntax is supported.Opera Full support 9.5Safari Full support 1.3WebView Android Full support 37Chrome Android ...
...And 2 more matches
Creating and triggering events - Developer guides
lled synthetic events, as opposed to the events fired by the browser itself. Creating custom events Events can be created with the Event constructor as follows: const event = new Event('build'); // Listen for the event. elem.addEventListener('build', function (e) { /* ... */ }, false); // Dispatch the event. elem.dispatchEvent(event); The above code example uses the EventTarget.dispatchEvent
() method. This constructor is supported in most modern browsers (with Internet Explorer being the exception). For a more verbose approach (which works with Internet Explorer), see the old-fashioned way below. Adding custom data - CustomEvent
() To add more data to the event object, the CustomEvent interface exists and the detail property can be used to pass custom data. For example, the event co...
...could be created as follows: const event = new CustomEvent('build', { detail: elem.dataset.time }); This will then allow you to access the additional data in the event listener: function eventHandler(e) { console.log('The time is: ' + e.detail); } The old-fashioned way The older approach to creating events uses APIs inspired by Java. The following shows an example with document.createEvent
(): // Create the event. const event = document.createEvent('Event'); // Define that the event name is 'build'. event.initEvent('build', true, true); // Listen for the event. elem.addEventListener('build', function (e) { // e.target matches elem }, false); // target can be any Element or other EventTarget. elem.dispatchEvent(event); Event bubbling It is often desirable to trigger an event ...
... a child element, and have an ancestor catch it; optionally, with data: <form> <textarea></textarea> </form> const form = document.querySelector('form'); const textarea = document.querySelector('textarea'); // Create a new event, allow bubbling, and provide any data you want to pass to the "detail" property const eventAwesome = new CustomEvent('awesome', { bubbles: true, detail: { text:
() => textarea.value } }); // The form element listens for the custom "awesome" event and then consoles the output of the passed text
() method form.addEventListener('awesome', e => console.log(e.detail.text
())); // As the user types, the textarea inside the form dispatches/triggers the event to fire, and uses itself as the starting point textarea.addEventListener('input', e => e.target.dispatchEve...
...And 2 more matches
HTML5 Parser - Developer guides
x and WebKit, which read it as two tags, foo and bar. If you previously tested your code in IE and Opera, then you probably don't have any tags like this. If you tested your site only with Gecko 1.x or WebKit (for example, Firefox-only intranets or WebKit-oriented mobile sites), then you might have tags that match this pattern, and they will behave differently with Gecko 2. Calling document.write
() during parsing Prior to HTML5, Gecko and WebKit allowed calls to document.write
() during parsing to insert content into the source stream. This behavior was inherently racy, as the content was inserted into a timing-dependent point in the source stream. If the call happened after the parser was done, the inserted content replaced the document. In IE, such calls are either ignored or imply a call...
...Prior to HTML5, Gecko and WebKit allowed calls to document.write
() during parsing to insert content into the source stream. This behavior was inherently racy, as the content was inserted into a timing-dependent point in the source stream. If the call happened after the parser was done, the inserted content replaced the document. In IE, such calls are either ignored or imply a call to document.open
(), replacing the document. In HTML5, document.write
() can only be called from a script that is created by a <script> tag that does not have the async or defer attributes set. With the HTML5 parser, calls to document.write
() in any other context either are ignored or replace the document. ...
...re either ignored or imply a call to document.open
(), replacing the document. In HTML5, document.write
() can only be called from a script that is created by a <script> tag that does not have the async or defer attributes set. With the HTML5 parser, calls to document.write
() in any other context either are ignored or replace the document. Some contexts from which you should not call document.write
() include: scripts created using document.createElement
() event handlers setTimeout
() setInterval
() <script async src="..."> <script defer src="..."> If you use the same mechanism for loading script libraries for all browsers including IE, then your code probably will not be affected by this change. Scripts that serve racy code to Firefox, perhaps while serving safe code to IE, will see a...
...And 2 more matches
<dialog>: The Dialog element - HTML: Hypertext Markup Language
own to the user. Usage notes <form> elements can close a dialog if they have the attribute method="dialog". When such a form is submitted, the dialog closes with its returnValue property set to the value of the button that was used to submit the form. The ::backdrop CSS pseudo-element can be used to style behind a <dialog> element when the dialog is displayed with HTMLDialogElement.showModal
(). For example, to dim unreachable content behind the modal dialog. Examples Simple example <dialog open> <p>Greetings, one and all!</p> </dialog> Advanced example This example opens a pop-up dialog box that contains a form, when the "Update details" button is clicked. HTML <!-- Simple pop-up dialog box containing a form --> <dialog id="favDialog"> <form method="dialog"> <p><label>...
...utput> JavaScript var updateButton = document.getElementById('updateDetails'); var favDialog = document.getElementById('favDialog'); var outputBox = document.querySelector('output'); var selectEl = document.querySelector('select'); var confirmBtn = document.getElementById('confirmBtn'); // "Update details" button opens the <dialog> modally updateButton.addEventListener('click', function onOpen
() { if (typeof favDialog.showModal === "function") { favDialog.showModal
(); } else { alert("The <dialog> API is not supported by this browser"); } }); // "Favorite animal" input sets the value of the submit button selectEl.addEventListener('change', function onSelect(e) { confirmBtn.value = selectEl.value; }); // "Confirm" button of form triggers "close" on dialog because of [method...
... Living Standard HTML 5.2The definition of '<dialog>' in that specification. ...
...And 2 more matches
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
LIFrameElement Attributes This element includes the global attributes. allow Specifies a feature policy for the <iframe>. See the article Privacy, permissions, and information security for details on security issues and how <iframe> works with Feature Policy to keep systems safe. allowfullscreen Set to true if the <iframe> can activate fullscreen mode by calling the requestFullscreen
() method. This attribute is considered a legacy attribute and redefined as allow="fullscreen". allowpaymentrequest Set to true if a cross-origin <iframe> should be allowed to invoke the Payment Request API. This attribute is considered a legacy attribute and redefined as allow="payment". csp A Content Security Policy enforced for the embedded resource. See HTMLIFrameElement.csp for ...
...is is the default value). lazy: Defer loading of the iframe until it reaches a calculated distance from the viewport, as defined by the browser. name A targetable name for the embedded browsing context. This can be used in the target attribute of the <a>, <form>, or <base> elements; the formtarget attribute of the <input> or <button> elements; or the windowName parameter in the window.open
() method. referrerpolicy Indicates which referrer to send when fetching the frame's resource: no-referrer: The Referer header will not be sent. no-referrer-when-downgrade (default): The Referer header will not be sent to origins without TLS (HTTPS). origin: The sent referrer will be limited to the origin of the referring page: its scheme, host, and port. origin-when-cross-origin: The re...
...ownloads to occur with a gesture from the user. allow-forms: Allows the resource to submit forms. If this keyword is not used, form submission is blocked. allow-modals: Lets the resource open modal windows. allow-orientation-lock: Lets the resource lock the screen orientation. allow-pointer-lock: Lets the resource use the Pointer Lock API. allow-popups: Allows popups (such as window.open
(), target="_blank", or showModalDialog
()). If this keyword is not used, the popup will silently fail to open. allow-popups-to-escape-sandbox: Lets the sandboxed document open new windows without those windows inheriting the sandboxing. For example, this can safely sandbox an advertisement without forcing the same restrictions upon the page the ad links to. allow-same-origin: If this token is no...
...And 2 more matches
<input type="date"> - HTML: Hypertext Markup Language
ntrol looks like so: The Edge date control looks like: And the Firefox date control looks like this: Value A DOMString representing a date in YYYY-MM-DD format, or empty Events change and input Supported common attributes autocomplete, list, readonly, and step IDL attributes list, value, valueAsDate, valueAsNumber. Methods select
(), stepDown
(), stepUp
() Value A DOMString representing the date entered in the input. The date is formatted according to ISO8601, described in Format of a valid date string in Date and time formats used in HTML. You can set a default value for the input with a date inside the value attribute, like so: <input type="date" value="2017-06-01"> The displayed date format will differ from th...
...lector('#month'); var daySelect = document.querySelector('#day'); // hide fallback initially fallbackPicker.style.display = 'none'; fallbackLabel.style.display = 'none'; // test whether a new date input falls back to a text input or not var test = document.createElement('input'); try { test.type = 'date'; } catch (e) { console.log(e.description); } // if it does, run the code inside the if
() {} block if(test.type === 'text') { // hide the native picker and show the fallback nativePicker.style.display = 'none'; fallbackPicker.style.display = 'block'; fallbackLabel.style.display = 'block'; // populate the days and years dynamically // (the months are always the same, therefore hardcoded) populateDays(monthSelect.value); populateYears
(); } function populateDays(month) ...
...dayNum = 29 : dayNum = 28; } // inject the right number of new <option> elements into the day <select> for(i = 1; i <= dayNum; i++) { var option = document.createElement('option'); option.textContent = i; daySelect.appendChild(option); } // if previous day has already been set, set daySelect's value // to that day, to avoid the day jumping back to 1 when...
...And 2 more matches
<input type="time"> - HTML: Hypertext Markup Language
liding reels. It, like Chrome, uses a 12- or 24-hour format for inputting times, based on system locale: 12-hour 24-hour Value A DOMString representing a time, or empty. Events change and input Supported common attributes autocomplete, list, readonly, and step IDL attributes value, valueAsDate, valueAsNumber, and list. Methods select
(), stepDown
(), and stepUp
(). Value A DOMString containing the value of the time entered into the input. You can set a default value for the input by including a valid time in the value attribute when creating the <input> element, like so: <label for="appt-time">Choose an appointment time: </label> <input id="appt-time" type="time" name="appt-time" value="13:30"> You can also get and s...
... The JavaScript code adds code to the time input to watch for the input event, which is triggered every time the contents of an input element change. When this happens, the contents of the <span> are replaced with the new value of the input element. var startTime = document.getElementById("startTime"); var valueSpan = document.getElementById("value"); startTime.addEventListener("input", function
() { valueSpan.innerText = startTime.value; }, false); When a form including a time input is submitted, the value is encoded before being included in the form's data. The form's data entry for a time input will always be in the form name=hh%3Amm, or name=hh%3Amm%3ass if seconds are included (see Using the step attribute). Additional attributes In addition to the attributes common to all <inpu...
...r('#hour'); var minuteSelect = document.querySelector('#minute'); // hide fallback initially fallbackPicker.style.display = 'none'; fallbackLabel.style.display = 'none'; // test whether a new date input falls back to a text input or not var test = document.createElement('input'); try { test.type = 'time'; } catch (e) { console.log(e.description); } // if it does, run the code inside the if
() {} block if(test.type === 'text') { // hide the native picker and show the fallback nativePicker.style.display = 'none'; fallbackPicker.style.display = 'block'; fallbackLabel.style.display = 'block'; // populate the hours and minutes dynamically populateHours
(); populateMinutes
(); } function populateHours
() { // populate the hours <select> with the 6 open hours of the day for(...
...And 2 more matches
Memory Management - JavaScript
In contrast, JavaScript automatically allocates memory when objects are created and frees it when they are not used anymore (garbage collection). This automaticity is a potential source of confusion: it can give developers the false impression that they don't need to worry about memory management. Memory life cycle Regardless of the programming language, the memory life cycle is pretty much always the same: Allocate the memory you need Use the allocated memory (read, write) Release the allocated memory when it is not needed anymore The second part is explicit in all languages. ...
...allocates memory for a string var o = { a: 1, b: null }; // allocates memory for an object and contained values // (like object) allocates memory for the array and // contained values var a = [1, null, 'abra']; function f(a) { return a + 2; } // allocates a function (which is a callable object) // function expressions also allocate an object someElement.addEventListener('click', function
() { someElement.style.backgroundColor = 'blue'; }, false); Allocation via function calls Some function calls result in object allocation. var d = new Date
(); // allocates a Date object var e = document.createElement('div'); // allocates a DOM element Some methods allocate new values or objects: var s = 'azerty'; var s2 = s.substr(0, 3); // s2 is a new string // Since strings are immutable ...
...he 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. ...
...And 2 more matches
Deprecated and obsolete features - JavaScript
r expression against all possible matches in a string, or only against the first. ignoreCase Whether or not to ignore case while attempting a match in a string. lastIndex The index at which to start the next match. multiline Whether or not to search in strings across multiple lines. source The text of the pattern. RegExp methods The compile
() method is deprecated. The valueOf method is no longer specialized for RegExp. Use Object.valueOf
(). Function properties The caller and arguments properties are deprecated, because they leak the function caller. Instead of the arguments property, you should use the arguments object inside function closures. Legacy generator Legacy generator function statement and Legacy generator functi...
...ript code. ..." Obsolete features These obsolete features have been entirely removed from JavaScript and can no longer be used as of the indicated version of JavaScript. Object Property Description __count__ Returns the number of enumerable properties directly on a user-defined object. __parent__ Points to an object's context. Object.prototype.eval
() Evaluates a string of JavaScript code in the context of the specified object. Object.observe
() Asynchronously observing the changes to an object. Object.unobserve
() Remove observers. Object.getNotifier
() Creates an object that allows to synthetically trigger a change. Function Property Description arity Number of formal argume...
...Use for...of instead. Destructuring for...in is deprecated. Use for...of instead. let blocks and let expressions are obsolete. ...
...And 2 more matches
InternalError: too much recursion - JavaScript
return; // do stuff loop(x + 1); } loop(0); // InternalError: too much recursion This recursive function is missing a base case. As there is no exit condition, the function will call itself infinitely. function loop(x) { // The base case is missing loop(x + 1); // Recursive call } loop(0); // InternalError: too much recursion Class error: too much recursion class Person{ constructor
(){} set name(name){ this.name = name; // Recursive call } } const tony = new Person
(); tony.name = "Tonisha"; // InternalError: too much recursion When a value is assigned to the property name (this.name = name;) JavaScript needs to set that property. When this happens, the setter function is triggered. set name(name){ this.name = name; // Recursive call } In this example when the sett...
...the setter function is triggered. set name(name){ this.name = name; // Recursive call } In this example when the setter is triggered, it is told to do the same thing again: to set the same property that it is meant to handle. This causes the function to call itself, again and again, making it infinitely recursive. This issue also appears if the same variable is used in the getter. ...
...all itself, again and again, making it infinitely recursive. This issue also appears if the same variable is used in the getter. get name
(){ return this.name; // Recursive call } To avoid this problem, make sure that the property being assigned to inside the setter function is different from the one that initially triggered the setter.The same goes for the getter. ...
...And 2 more matches
arguments.callee - JavaScript
uting function. Description callee is a property of the arguments object. It can be used to refer to the currently executing function inside the function body of that function. This is useful when the name of the function is unknown, such as within a function expression with no name (also called "anonymous functions"). Warning: The 5th edition of ECMAScript (ES5) forbids use of arguments.callee
() in strict mode. Avoid using arguments.callee
() by either giving function expressions a name or use a function declaration where a function must call itself. Why was arguments.callee removed from ES5 strict mode? (adapted from a Stack Overflow answer by olliej) Early versions of JavaScript did not allow named function expressions, and for this reason you could not make a recursive function expr...
...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 accessin...
...ave a name. Therefore if there is no accessible variable referring to it, the only way the function can refer to itself is by arguments.callee. The following example defines a function, which, in turn, defines and returns a factorial function. This example isn't very practical, and there are nearly no cases where the same result cannot be achieved with named function expressions. ...
...And 2 more matches
The arguments object - JavaScript
like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Description Note: If you're writing ES6 compatible code, then rest parameters should be preferred. Note: "Array-like" means that arguments has a length property and properties indexed from zero, but it doesn't have Array's built-in methods like forEach
() or map
(). See ?Description for details. The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0. For example, if a function is passed 3 arguments, you can access them as follows: ...
...x at 0. For example, if a function is passed 3 arguments, you can access them as follows: arguments[0] // first argument arguments[1] // second argument arguments[2] // third argument Each argument can also be set or reassigned: arguments[1] = 'new value'; The arguments object is not an Array. It is similar, but lacks all Array properties except length. ...
...ay. It is similar, but lacks all Array properties except length. For example, it does not have the pop
() method. However, it can be converted to a real Array: var args = Array.prototype.slice.call(arguments); // Using an array literal is shorter than above but allocates an empty array var args = [].slice.call(arguments); As you can do with any Array-like object, you can use ES2015's Array.from
() method or spread syntax to convert arguments to a real Array: let args = Array.from(arguments); // or let args = [...arguments]; The arguments object is useful for functions called with more arguments than they are formally declared to accept. This technique is useful for functions that can be passed a variable number of arguments, such as Math.min
(). This example function accepts any number o...
...And 2 more matches
Function.displayName - JavaScript
The function.displayName property returns the display name of the function. Examples Setting a displayName It is usually preferred by consoles and profilers over func.name to display the name of a function. ...
... The function.displayName property returns the display name of the function. Examples Setting a displayName It is usually preferred by consoles and profilers over func.name to display the name of a function. ...
... The function.displayName property returns the display name of the function. Examples Setting a displayName It is usually preferred by consoles and profilers over func.name to display the name of a function. ...
...And 2 more matches
Intl.DateTimeFormat - JavaScript
The Intl.DateTimeFormat object is a constructor for objects that enable language-sensitive date and time formatting. 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. Constructor Intl.DateTimeFormat
() Creates a new DateTimeFormat object. Static methods Intl.DateTimeFormat.supportedLocalesOf
() Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. Instance methods Intl.DateTimeFormat.prototype.format
() Getter function that formats a date according to the locale and formatting options of this DateTimeFormat object. Int...
...Intl.DateTimeFormat.supportedLocalesOf
() Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. Instance methods Intl.DateTimeFormat.prototype.format
() Getter function that formats a date according to the locale and formatting options of this DateTimeFormat object. Intl.DateTimeFormat.prototype.formatToParts
() Returns an Array of objects representing the date string in parts that can be used for custom locale-aware formatting. Intl.DateTimeFormat.prototype.resolvedOptions
() Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object. ...
...rmat object. Intl.DateTimeFormat.prototype.formatToParts
() Returns an Array of objects representing the date string in parts that can be used for custom locale-aware formatting. Intl.DateTimeFormat.prototype.resolvedOptions
() Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object. Intl.DateTimeFormat.prototype.formatRange
() This method receives two Dates and formats the date range in the most concise way based on the locale and options provided when instantiating DateTimeFormat. Intl.DateTimeFormat.prototype.formatRangeToParts
() This method receives two Dates and returns an Array of objects containing the locale-specific tokens representing each part of the formatted date range. Examples Using DateTimeFormat ...
...And 2 more matches
Math - JavaScript
ns the natural logarithm (loge; also ln) of 1 + x for the number x. Math.log10(x) Returns the base-10 logarithm of x. Math.log2(x) Returns the base-2 logarithm of x. Math.max([x[, y[, ...]]]) Returns the largest of zero or more numbers. Math.min([x[, y[, ...]]]) Returns the smallest of zero or more numbers. Math.pow(x, y) Returns base x to the exponent power y (that is, xy). Math.random
() Returns a pseudo-random number between 0 and 1. Math.round(x) Returns the value of the number x rounded to the nearest integer. Math.sign(x) Returns the sign of the x, indicating whether x is positive, negative, or zero. Math.sin(x) Returns the sine of x. Math.sinh(x) Returns the hyperbolic sine of x. Math.sqrt(x) Returns the positive square root of x. Math.tan(x) Returns the tangent...
...o. Math.sin(x) Returns the sine of x. Math.sinh(x) Returns the hyperbolic sine of x. Math.sqrt(x) Returns the positive square root of x. Math.tan(x) Returns the tangent of x. Math.tanh(x) Returns the hyperbolic tangent of x. Math.trunc(x) Returns the integer portion of x, removing any fractional digits. Examples Converting between degrees and radians The trigonometric functions sin
(), cos
(), tan
(), asin
(), acos
(), atan
(), and atan2
() expect (and return) angles in radians. Since humans tend to think in degrees, and some functions (such as CSS transforms) can accept degrees, it is a good idea to keep functions handy that convert between the two: function degToRad(degrees) { return degrees * (Math.PI / 180); }; function radToDeg(rad) { return rad / (Math.PI / 180); }; Ca...
... return rad / (Math.PI / 180); }; Calculating the height of an equalateral triangle If we want to calculate the height of an equalateral triangle, and we know its side length is 100, we can use the formulae length of the adjacent multiplied by the tangent of the angle is equal to the opposite. In JavaScript, we can do this with the following: 50 * Math.tan(degToRad(60)). ...
...And 2 more matches
Planned changes to shared memory - JavaScript
These changes provide further isolation between sites and help reduce the impact of attacks with high-resolution timers, which can be created with shared memory. Starting with Firefox 79, the features described in this document are enabled by default. Chrome intends to implement similar restrictions. ...
...strictions. New HTTP header bonanza As a baseline requirement, documents will need to be in a secure context. For top-level documents, two headers will need to be set: Cross-Origin-Opener-Policy with same-origin as value (protects your origin from attackers) Cross-Origin-Embedder-Policy with require-corp as value (protects victims from your origin) With these two headers set, postMessage
() will no longer throw for SharedArrayBuffer objects and shared memory across threads is therefore available. Nested documents and dedicated workers will need to set the Cross-Origin-Embedder-Policy header as well with the same value. No further changes are needed for same-origin nested documents and subresources. Same-site (but cross-origin) nested documents and subresources will need to set the ...
...ArrayBuffer objects are in principle always available, but unfortunately the constructor on the global object is hidden, unless the two headers mentioned above are set, for compatibility with web content. There is hope that this restriction can be removed in the future. WebAssembly.Memory can still be used to get an instance. Unless the two headers mentioned above are set, the various postMessage
() APIs will throw for SharedArrayBuffer objects. If they are set, postMessage
() on Window objects and dedicated workers will function and allow for memory sharing. To avoid having to check whether postMessage
() throws, self.crossOriginIsolated is being standardized (a getter that returns a boolean; true if the headers are set), available in window and worker contexts. WebAssembly Shared Memory ...
...And 2 more matches
Symbol.prototype.description - JavaScript
contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Description Symbol objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The Symbol.prototype.description property can be used to read that description. ...
..., please clone https://github.com/mdn/interactive-examples and send us a pull request. Description Symbol objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The Symbol.prototype.description property can be used to read that description. It is different to Symbol.prototype.toString
() as it does not contain the enclosing "Symbol
()" string. See the examples. ...
...st. Description Symbol objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The Symbol.prototype.description property can be used to read that description. It is different to Symbol.prototype.toString
() as it does not contain the enclosing "Symbol
()" string. See the examples. ...
...And 2 more matches
Symbol.iterator - JavaScript
Description Whenever an object needs to be iterated (such as at the beginning of a for..of loop), its @@iterator method is called with no arguments, and the returned iterator is used to obtain the values to be iterated. Some built-in types have a default iteration behavior, while other types (such as Object) do not. The built-in types with a @@iterator method are: Array.prototype[@@iterator]
() TypedArray.prototype[@@iterator]
() String.prototype[@@iterator]
() Map.prototype[@@iterator]
() Set.prototype[@@iterator]
() See also Iteration protocols for more information. Property attributes of Symbol.iterator Writable no Enumerable no Configurable no Examples User-defined iterables We can ...
...
() Set.prototype[@@iterator]
() See also Iteration protocols for more information. ...
...Using it as such is likely to result in runtime exceptions or buggy behavi...
...And 2 more matches
WebAssembly.Instance - JavaScript
A WebAssembly.Instance object is a stateful, executable instance of a WebAssembly.Module. Instance objects contain all the Exported WebAssembly functions that allow calling into WebAssembly code from JavaScript. Constructor WebAssembly.Instance
() Creates a new Instance object. Instance properties Instance.prototype.exports Returns an object containing as its members all the functions exported from the WebAssembly module instance, to allow them to be accessed and used by JavaScript. Read-only. ...
...from JavaScript. Constructor WebAssembly.Instance
() Creates a new Instance object. Instance properties Instance.prototype.exports Returns an object containing as its members all the functions exported from the WebAssembly module instance, to allow them to be accessed and used by JavaScript. Read-only. ...
...ed by JavaScript. Read-only. ...
...And 2 more matches
class expression - JavaScript
// returns "function" typeof class {}; // returns "function" Foo instanceof Object; // true Foo instanceof Function; // true class Foo {} // Throws SyntaxError (class declarations do not allow re-declaration) Examples A simple class expression This is just a simple anonymous class expression which you can refer to using the variable Foo. ...
... "function" typeof class {}; // returns "function" Foo instanceof Object; // true Foo instanceof Function; // true class Foo {} // Throws SyntaxError (class declarations do not allow re-declaration) Examples A simple class expression This is just a simple anonymous class expression which you can refer to using the variable Foo. ...
...nstanceof Object; // true Foo instanceof Function; // true class Foo {} // Throws SyntaxError (class declarations do not allow re-declaration) Examples A simple class expression This is just a simple anonymous class expression which you can refer to using the variable Foo. ...
...And 2 more matches
delete operator - JavaScript
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 properties cannot be removed. This includes properties of built-in objects like Math, Array, Object and properties that are created as non-configurable with methods like Object.defineProperty
(). The following snippet gives a simple example: var Employee = { age: 28, name: 'abc', designation: 'developer' } console.log(delete Employee.name); // returns true console.log(delete Employee.age); // returns true // When trying to delete a property that does // not exist, true is returned console.log(delete Employee.salary); // returns true Non-configurable properties When a p...
...ls.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. ...
...console.log(foo.bar); // 10 // Delete the own property within the // foo object. ...
...And 2 more matches
for...in - JavaScript
different property name is assigned to variable on each iteration. object Object whose non-Symbol enumerable properties are iterated over. Description A for...in loop only iterates over enumerable, non-Symbol properties. Objects created from built-in constructors like Array and Object have inherited non-enumerable properties from Object.prototype and String.prototype, such as String's indexOf
() method or Object's toString
() method. The loop will iterate over all enumerable properties of the object itself and those the object inherits from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain). Deleted, added, or modified properties A for...in loop iterates over the properties of an object in an...
...eturn the indexes in any particular order. The for...in loop statement will return all enumerable properties, including those with non-integer names and those that are inherited. Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order. Therefore, it is better to use a for loop with a numeric index (or Array.prototype.forEach
() or the for...of loop) when iterating over arrays where the order of access is important. Iterating over own properties only If you only want to consider properties attached to the object itself, and not its prototypes, use getOwnPropertyNames
() or perform a hasOwnProperty
() check (propertyIsEnumerable
() can also be used). Alternatively, if you know there won't be any outside code interference, ...
...types, use getOwnPropertyNames
() or perform a hasOwnProperty
() check (propertyIsEnumerable
() can also be used). Alternatively, if you know there won't be any outside code interference, you can extend built-in prototypes with a check method. Why Use for...in? Given that for...in is built for iterating object properties, not recommended for use with arrays, and options like Array.prototype.forEach
() and for...of exist, what might be the use of for...in at all? It may be most practically used for debugging purposes, being an easy way to check the properties of an object (by outputting to the console or otherwise). Although arrays are often more practical for storing data, in situations where a key-value pair is preferred for working with data (with properties acting as the "key"), there may ...
...And 2 more matches
try...catch - JavaScript
ns 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. ...
...You can use this identifier to get information about the exception that was thrown. Th...
...ther an exception is thrown. Also, if an exception is thrown, the statements in the finally-block execute even if no catch-block handles the exception. The following example shows one use case for the finally-block. The code opens a file and then executes statements that use the file; the finally-block makes sure the file always closes after it is used even if an exception was thrown. ...
...And 2 more matches
CSS and JavaScript animation performance - Web Performance
In this article, we analyse the performance differences between CSS- and JavaScript-based animation. CSS transitions and animations Both CSS transitions and animations can be used to write animation. ...
...es that indicate the start and end states of the animation's style, as well as possible intermediate points. See Using CSS animations for more details. In terms of performance, there is no difference between implementing an animation with CSS transitions or animations. Both of them are classified under the same CSS-based umbrella in this article. requestAnimationFrame The requestAnimationFrame
() API provides an efficient way to make animations in JavaScript. The callback function of the method is called by the browser before the next repaint on each frame. Compared to setTimeout
()/setInterval
(), which need a specific delay parameter, requestAnimationFrame
() is much more efficient. Developers can create an animation by simply changing an element's style each time the loop is called (or up...
... For more details read animating with JavaScript from setinterval to requestAnimationFrame. Performance comparison: transitions vs. ...
...And 2 more matches
Scripting - SVG: Scalable Vector Graphics
ee arguments setting properties. Preventing default behavior in event code When writing drag and drop code, sometimes you'll find that text on the page gets accidently selected while dragging. Or if you want to use the backspace key in your code, you want to override the browser's default behavior when the backspace key is pressed, which is to go back to the previous page. The evt.preventDefault
() method lets you do this. Using eventListeners with objects The methods addEventListener
() and removeEventListener
() are very useful when writing interactive SVG. You can pass an object that implements the handleEvent interface as the second parameter to these methods. function myRect(x,y,w,h,message){ this.message=message this.rect=document.createElementNS("http://www.w3.org/2000/svg","rect...
... Inter-document scripting: referencing embedded SVG When using SVG within HTML, Adobe's SVG Viewer 3.0 automatically includes a window property called svgDocument that points to the SVG document. This is not the case for Mozilla's native SVG implementation; therefore, using window.svgDocument does not work in Mozilla. Instead, you can use var svgDoc=document.embeds["name_of_svg"].getSVGDocument
(); to get a reference to an embedded SVG document instead. The best way to get access to the Document representing an SVG document is to look at HTMLIFrameElement.contentDocument (if the document is presented in an <iframe>) or HTMLObjectElement.contentDocument (if the document is presented in an <object> element), like this: var svgDoc = document.getElementById("iframe_element").contentDocumen...
... You may find documentation referring to an SVGDocument interface. Prior to SVG 2, SVG documents were represented using that interface. However, SVG documents are ...
...And 2 more matches
Transforming XML with XSLT - XSLT: Extensible Stylesheet Language Transformations
mplate (supported) xsl:text (partially supported) xsl:transform (supported) xsl:value-of (partially supported) xsl:variable (supported) xsl:when (supported) xsl:with-param (supported) Axes ancestor ancestor-or-self attribute child descendant descendant-or-self following following-sibling namespace (not supported) parent preceding preceding-sibling self Functions boolean
() (supported) ceiling
() (supported) concat
() (supported) contains
() (supported) count
() (supported) current
() (supported) document
() (supported) element-available
() (supported) false
() (supported) floor
() (supported) format-number
() (supported) function-available
() (supported) generate-id
() (supported) id
() (partially supported) key
() (supported) lang
() (supported) last
() (supported...
... ceiling
() (supported) concat
() (supported) contains
() (supported) count
() (supported) current
() (supported) document
() (supported) element-available
() (supported) false
() (supported) floor
() (supported) format-number
() (supported) function-available
() (supported) generate-id
() (supported) id
() (partially supported) key
() (supported) lang
() (supported) last
() (supported) local-name
() (supported) name
() (supported) namespace-uri
() (supported) normalize-space
() (supported) not
() (supported) number
() (supported) position
() (supported) round
() (supported) starts-with
() (supported) string
() (supported) string-length
() (supported) substring
() (supported) substring-after
() (supported) substring-before
() (supported) sum
() (supported) system-property
() (supported) tran...
...All rights reserved. ...
...And 2 more matches
Compiling a New C/C++ Module to WebAssembly - WebAssembly
s is an advanced approach; it is usually easier to use the provided HTML template. Emscripten requires a large variety of JavaScript "glue" code to handle memory allocation, memory leaks, and a host of other problems Calling a custom function defined in C If you have a function defined in your C code that you want to call as needed from JavaScript, you can do this using the Emscripten ccall
() function, and the EMSCRIPTEN_KEEPALIVE declaration (which adds your functions to the exported functions list (see Why do functions in my C/C++ source code vanish when I compile to JavaScript, and/or I get No functions to process?)). Let's look at how this works. To start with, save the following code as hello3.c in a new directory: #include <stdio.h> #include <emscripten/emscripten.h> i...
...Putting EMSCRIPTEN_KEEPALIVE before a function name stops this from happening. You also need to import the emscripten.h library to use EMSCRIPTEN_KEEPALIVE. Note: We are including the #ifdef blocks so that if you are trying to include this in C++ code, the example will still work. Due to C versus C++ name mangling rules, this would ...
...y too, just for convenience (you'd obviously put this in a central place in your real dev environment). Now let's run the compilation step again. From inside your latest directory (and while inside your Emscripten compiler environment terminal window), compile your C code with the following command. ...
...And 2 more matches
WebAssembly
is the low-level textual representation of a .wasm module shown in browser developer tools when debugging. Converting WebAssembly text format to wasm This article provides a guide on how to convert a WebAssembly module written in the text format into a .wasm binary. API reference WebAssembly This object acts as the namespace for all WebAssembly related functionality. ...
...at into a .wasm binary. API reference WebAssembly This object acts as the namespace for all WebAssembly related functionality. WebAssembly.Global
() A WebAssembly.Global object represents a global variable instance, accessible from both JavaScript and importable/exportable across one or more WebAssembly.Module instances. This allows dynamic linking of multiple modules. WebAssembly.Module
() A WebAssembly.Module object contains stateless WebAssembly code that has already been compiled by the browser and can be efficiently shared with Workers, and instantiated multiple times. WebAssembly.Instance
() A WebAssembly.Instance object is a stateful, executable instance of a Module. Instance objects contain all the Exported WebAssembly functions that allow calling into WebAssembly code fr...
... WebAssembly code that has already been compiled by the browser and can be efficiently shared with Workers, and instantiated multiple times. WebAssembly.Instance
() A WebAssembly.Instance object is a stateful, executable instance of a Module. Instance objects contain all the Exported WebAssembly functions that allow calling into WebAssembly code from JavaScript. WebAssembly.instantiateStreaming
() The WebAssembly.instantiateStreaming
() function is the primary API for compiling and instantiating WebAssembly code, returning both a Module and its first Instance. ...
...And 2 more matches
Communicating using "postMessage" - Archive of obsolete content
uctor: panel = require("sdk/panel").Panel({ onMessage: function(contentScriptMessage) { // Handle message from the content script } }); Message Events Versus User-Defined Events You can use message events as an alternative to user-defined events: var pageModScript = "window.addEventListener('mouseover', function(event) {" + " self.postMessage(event.target.toString
());" + "}, false);"; var pageMod = require('sdk/page-mod').PageMod({ include: ['*'], contentScript: pageModScript, onAttach: function(worker) { worker.on('message', function(message) { console.log('mouseover: ' + message); }); } }); The reason to prefer user-defined events is that as soon as you need to send more than one type of message, then both sendi...
...d mouseout events as well as mouseover. ...
... + " kind: 'mouseover'," + " element: event.target.toString
()" + " });" + "}, false);" + "window.addEventListener('mouseout', function(event) {" + " self.postMessage({" + " kind: 'mouseout'," + " element: event.target.toString
()" + " });" + " }, false);" var pageMod = require('sdk/page-mod').PageMod({ include: ['*'], contentScript: pageModScript, onAttach: function(worker) { worker.on('message', function(message) { switch(message.kind) { case 'mouseover': console.log('mouseover: ' + message.element); break; case 'mouseout': consol...
...ouseover: ' + message.element); break; case 'mouseout': console.log('mouseout: ' + message.element); break; } }); } }); Implementing the same add-on with user-defined events is shorter and more readable: var pageModScript = "window.addEventListener('mouseover', function(event) {" + " self.port.emit('mouseover', event.target.toString
());" + "}, false);" + "window.addEventListener('mouseout', function(event) {" + " self.port.emit('mouseout', event.target.toString
());" + "}, false);"; var pageMod = require('sdk/page-mod').PageMod({ include: ['*'], contentScript: pageModScript, onAttach: function(worker) { worker.port.on('mouseover', functi...
Porting the Library Detector - Archive of obsolete content
rsion in the SDK's examples directory. How the Library Detector Works All the work is done inside a single file, librarydetector.xul This contains: a XUL overlay a script The XUL overlay adds a box element to the browser's status bar: The script does everything else. The bulk of the script is an array of test objects, one for each library. ...
...y. Each test object contains a function called test
(): if the function finds the library, it defines various additional properties for the test object, such as a version property containing the library version. Each test also contains a chrome:// URL pointing to the icon associated with its library. The script listens to gBrowser's DOMContentLoaded event. When this is triggered, the testLibraries
() function builds an array of libraries by iterating through the tests and adding an entry for each library which passes. Once the list is built, the switchLibraries
() function constructs a XUL statusbarpanel element for each library it found, populates it with the icon at the corresponding chrome:// URL, and adds it to the box. Finally, it listens to gBrowser's TabSelect event, to update the con...
...ent script into every new page. The content script, which we'll call library-detector.js, will keep most of the logic of the test functions intact. ...
...the array of library names, and post it back to main.js: function testLibraries
() { var win = unsafeWindow; var libraryList = []; for(var i in LD_tests) { var passed = LD_tests[i].test(win); if (passed) { var libraryInfo = { name: i, version: passed.version }; libraryList.push(libraryInfo); } } self.postMessage(libraryList); } testLibraries
(); main.js responds to that message by fetching the tab corresponding to that worker using worker.tab, and adding the array of library names to that tab's libraries property: pageMod.PageMod({ include: "*", contentScriptWhen: 'end', contentScriptFile: (data.url('library-detector.js')), onAttach: function(worker) { worker.on('message', function(libraryList) { if (!worker.tab.lib...
indexed-db - Archive of obsolete content
site database. See bug 778197 and bug 786688. Example This example uses the action button API, which is only available from Firefox 29 onwards. Here's a complete add-on that adds two buttons to the browser: the button labeled "Add" adds the title of the current tab to a database, while the button labeled "List" lists all the titles in the database. The add-on implements helper functions open
(), addItem
() and getItems
() to open the database, add a new item to the database, and get all items in the database. var { indexedDB, IDBKeyRange } = require('sdk/indexed-db'); var database = {}; database.onerror = function(e) { console.error(e.value) } function open(version) { var request = indexedDB.open("stuff", version); request.onupgradeneeded = function(e) { var db = e.target.r...
...b.deleteObjectStore("items"); } var store = db.createObjectStore("items", {keyPath: "time"}); }; request.onsuccess = function(e) { database.db = e.target.result; }; request.onerror = database.onerror; }; function addItem(name) { var db = database.db; var trans = db.transaction(["items"], "readwrite"); var store = trans.objectStore("items"); var time = new Date
().getTime
(); var request = store.put({ "name": name, "time": time }); request.onerror = database.onerror; }; function getItems(callback) { var cb = callback; var db = database.db; var trans = db.transaction(["items"], "readwrite"); var store = trans.objectStore("items"); var items = new Array
(); trans.oncomplete = function
() { cb(items); } var keyRange = IDBKey...
...dwrite"); var store = trans.objectStore("items"); var items = new Array
(); trans.oncomplete = function
() { cb(items); } var keyRange = IDBKeyRange.lowerBound(0); var cursorRequest = store.openCursor(keyRange); cursorRequest.onsuccess = function(e) { var result = e.target.result; if(!!result == false) return; items.push(result.value.name); result.continue
(); }; cursorRequest.onerror = database.onerror; }; function listItems(itemList) { console.log(itemList); } open("1"); var add = require("sdk/ui/button/action").ActionButton({ id: "add", label: "Add", icon: "./add.png", onClick: function
() { addItem(require("sdk/tabs").activeTab.title); } }); var list = require("sdk/ui/button/action").ActionButton({ id: "list", label: "L...
...ror; }; function listItems(itemList) { console.log(itemList); } open("1"); var add = require("sdk/ui/button/action").ActionButton({ id: "add", label: "Add", icon: "./add.png", onClick: function
() { addItem(require("sdk/tabs").activeTab.title); } }); var list = require("sdk/ui/button/action").ActionButton({ id: "list", label: "List", icon: "./list.png", onClick: function
() { getItems(listItems); } }); Note that to run this add-on you'll need to provide icons named "add.png" and "list.png" in the add-on's "data" directory. Globals Properties indexedDB Enables you to create, open, and delete databases. See the IDBFactory documentation. IDBKeyRange Defines a range of keys. See the IDBKeyRange documentation. DOMException Provides more detailed informati...
passwords - Archive of obsolete content
nction is used to retrieve a credential, or a list of credentials, stored in the Password Manager. You pass it any subset of the possible properties a credential can contain. Credentials which match all the properties you supplied are returned as an argument to the onComplete callback. ...
...ion show_all_passwords
() { require("sdk/passwords").search({ onComplete: function onComplete(credentials) { credentials.forEach(function(credential) { console.log(credential.username); console.log(credential.password); }); } }); } If you pass it a single property, only credentials matching that property are returned: function show_passwords_for_joe
() { require("sdk/passwords").search({ username: "joe", onComplete: function onComplete(credentials) { credentials.forEach(function(credential) { console.log(credential.username); console.log(credential.password); }); } }); } If you pass more than one property, returned credentials must match all of them: function show_google_password_for_joe
() {...
... "joe", url: "https://www.google.com", onComplete: function onComplete(credentials) { credentials.forEach(function(credential) { console.log(credential.username); console.log(credential.password); }); } }); } To retrieve only credentials associated with your add-on, use the url property, initialized from self.uri: function show_my_addon_passwords
() { require("sdk/passwords").search({ url: require("sdk/self").uri, onComplete: function onComplete(credentials) { credentials.forEach(function(credential) { console.log(credential.username); console.log(credential.password); }); } }); } Parameters options : object Required options: Name Type onComplete functio...
... password string The password for the credential. Optional options: ...
private-browsing - Archive of obsolete content
private-browsing module to check whether objects are private, so as to avoid storing data derived from such objects. Additionally, add-ons that use low-level modules such as window/utils may see private browser windows with certain functions, even if they have not explicitly opted into private browsing. Respecting private browsing The private-browsing module exports a single function isPrivate
() that takes an object, which may be a BrowserWindow, tab, or worker, as an argument. It returns true only if the object is: a private window, or a tab belonging to a private window, or a worker that's associated with a document hosted in a private window any window, tab, or worker if the browser has been configured to never remember history (Options->Privacy->History) Add-ons can use this ...
... or a tab belonging to a private window, or a worker that's associated with a document hosted in a private window any window, tab, or worker if the browser has been configured to never remember history (Options->Privacy->History) Add-ons can use this API to decide whether or not to store user data. ...
...f (!require("sdk/private-browsing").isPrivate(tab)) { console.log("storing..."); simpleStorage.storage.titles.push(tab.title); } else { console.log("not storing, private data"); } }); Here's an add-on that uses a page-mod to log the content of pages loaded by the user, unless the page is private. ...
...le.log("not storing, private data"); } }); Here's an add-on that uses a page-mod to log the content of pages loaded by the user, unless the page is private. ...
request - Archive of obsolete content
e of "utf-8" and certain characters will not display correctly. To force the response to be interpreted as Latin-1, use overrideMimeType: var Request = require("sdk/request").Request; var quijote = Request({ url: "http://www.latin1files.org/quijote.txt", overrideMimeType: "text/plain; charset=latin1", onComplete: function (response) { console.log(response.text); } }); quijote.get
(); anonymous boolean If true, the request will be sent without cookies or authentication headers. This option sets the mozAnon property in the underlying XMLHttpRequest object. Defaults to false. Request The Request object is used to make GET, HEAD, POST, PUT, or DELETE network requests. It is constructed with a URL to which the request is sent. Optionally the user may sp...
...st The Request object is used to make GET, HEAD, POST, PUT, or DELETE network requests. It is constructed with a URL to which the request is sent. Optionally the user may specify a collection of headers and content to send alongside the request and a callback which will be executed once the request completes. Once a Request object has been created a GET request can be executed by calling its get
() method, a POST request by calling its post
() method, and so on. When the server completes the request, the Request object emits a "complete" event. Registered event listeners are passed a Response object. Each Request object is designed to be used once. Attempts to reuse them will throw an error. Since the request is not being made by any particular website, requests made here are not subject ...
...onse) { var tweet = response.json[0]; console.log("User: " + tweet.user.screen_name); console.log("Tweet: " + tweet.text); } }); // Be a good consumer and check for rate limiting before doing more. Request({ url: "https://api.twitter.com/1.1/application/rate_limit_status.json", onComplete: function (response) { if (response.json.remaining_hits) { latestTweetRequest.get
(); } else { console.log("You have been rate limited!"); } } }).get
(); Methods get
() Make a GET request. head
() Make a HEAD request. post
() Make a POST request. put
() Make a PUT request. delete
() Make a DELETE request. Properties url headers content contentType response Events complete The Request object emits this event when the request has completed and a respon...
... url headers content contentType response Events complete The Request object emits this event when the request has completed and a response has been received. Arguments Response : Listener functions are passed the response to the request as a Response object. Response The Response object contains the response to a network request issued using a Request object. It is returned by the get
(), head
(), post
(), put
() or delete
() method of a Request object. All members of a Response object are read-only. Properties url The URL of the response content. text The content of the response as plain text. json The content of the response as a JavaScript object. The value will be null if the document cannot be processed by JSON.parse. status The HTTP response status code (e.g. 200). s...
io/byte-streams - Archive of obsolete content
Experimental Provides streams for reading and writing bytes. function readBinaryDataFromFile (filename) { var fileIO = require("sdk/io/file"); var data = null; if (fileIO.exists(filename)) { var ByteReader = fileIO.open(filename, "rb"); if (!ByteReader.closed) { data = ByteReader.read
(); ByteReader.close
(); } } return data; } function writeBinaryDataToFile(data, filename) { var fileIO = require("sdk/io/file"); var ByteWriter = fileIO.open(filename, "wb"); if (!ByteWriter.closed) { ByteWriter.write(data); ByteWriter.close
(); } } Globals Constructors ByteReader(inputStream) Creates a binary input stream that reads bytes from a backing stream. You can also create ByteReader objects using io/file's open
() function. Parameters inputS...
...If the stream is already closed, an exception is thrown. ...
...If the stream is already closed, an exception is thrown. read(numBytes) Reads a string from the stream. If the stream is closed, an exception is thrown. Parameters numBytes : number The number of bytes to read. If not given, the remainder of the entire stream is read. ...
...(numBytes) Reads a string from the stream. If the stream is closed, an exception is thrown. Parameters numBytes : number The number of bytes to read. If not given, the remainder of the entire stream is read. Returns string : A string containing the bytes read. If the stream is at the end, returns the empty string. Properties closed True if the stream is closed. ByteWriter Methods close
() Closes both the stream and its backing stream. If the stream is already closed, an exception is thrown. write(str) Writes a string to the stream. If the stream is closed, an exception is thrown. Parameters str : string The string to write. Properties closed True if the stream is closed. ...
remote/parent - Archive of obsolete content
aded in a content frame. This includes the content of every tab in an application like Firefox and also some other UI elements. Each frame loads in a process but sometimes the application may choose to switch from loading a tab in one process to another. In this case the frame for that tab changes. Loading modules into the child process To load a module into the child process, use remoteRequire
(): const { remoteRequire } = require("sdk/remote/parent"); remoteRequire("./my-module.js", module); Inter-process communication A module loaded into a different process cannot directly communicate or share state with the module that loaded it. Instead, the two sides communicate using port objects like those used for communication with content scripts. The sdk/remote/parent module provides port ...
...ess can't load, but the sorts of things listed in Limitations of Frame Scripts broadly apply. Examples Property retrieval This first example shows fetching a simple property from every existing and future process. remote.js runs in all child processes. ...
...ef; }); // main.js const { frames, remoteRequire } = require("sdk/remote/parent"); remoteRequire("./remote.js", module); frames.port.emit("changeLocation", "foo"); Tab information This shows sending a message when a tab loads; this is similar to how the sdk/tabs module currently works. ...
... You can use an absolute path to the module or a relative path. If you use a relative path, you must use the module parameter. const { remoteRequire } = require("sdk/remote/parent"); remoteRequire("./my-module.js", module); Note that even single-process applications have a process that contains content frames. For consistency and to make writing multiprocess compatible code easier, remoteRequire
() will also create a new module loader and load modules in the main process. Parameters id : String The module to load. To use a relative path you must pass the module parameter. module : Object The module to resolve the relative module ID against. To resolve relative to the loading module, pass module here. Properties processes A Processes object. frames A Frames object. Processes The ...
Implementing the widget - Archive of obsolete content
The widget's icons You can copy the widget's icons from here: Or, if you're feeling creative, you can make your own icons. Either way, save them in your data/widget directory. main.js Now in the lib directory open main.js and add the following code: var widgets = require('sdk/widget'); var data = require('sdk/self').data; ...
...s widget.js. The widget's icons You can copy the widget's icons from here: Or, if you're feeling creative, you can make your own icons. Either way, save them in your data/widget directory. ...
...u're feeling creative, you can make your own icons. Either way, save them in your data/widget directory. ...
...torIsOn = false; function toggleActivation
() { annotatorIsOn = !annotatorIsOn; return annotatorIsOn; } exports.main = function
() { var widget = widgets.Widget({ id: 'toggle-switch', label: 'Annotator', contentURL: data.url('widget/pencil-off.png'), contentScriptWhen: 'ready', contentScriptFile: data.url('widget/widget.js') }); widget.port.on('left-click', function
() { console.log('activate/deactivate'); widget.contentURL = toggleActivation
() ? data.url('widget/pencil-on.png') : data.url('widget/pencil-off.png'); }); widget.port.on('right-click', function
() { console.log('show annotation list'); }); } The annotator is inactive by default. It creates the widget and responds to messages from the widget's content...
Display a Popup - Archive of obsolete content
"text-entry.html"), contentScriptFile: data.url("get-text.js") }); // Create a button require("sdk/ui/button/action").ActionButton({ id: "show-panel", label: "Show Panel", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onClick: handleClick }); // Show the panel when the user clicks the button. function handleClick(state) { text_entry.show
(); } // When the panel is displayed it generated an event called // "show": we will listen for that event and when it happens, // send our own "show" event to the panel's script, so the // script can prepare the panel for display. text_entry.on("show", function
() { text_entry.port.emit("show"); }); // Listen for messages called "text-entered" coming from // the content script. The message paylo...
...// The message payload is the contents of the edit box. ...
...) { // Remove the newline. text = textArea.value.replace(/(\r\n|\n|\r)/gm,""); self.port.emit("text-entered", text); textArea.value = ''; } }, false); // Listen for the "show" event being sent from the // main add-on code. It means that the panel's about // to be shown. // // Set the focus to the text area so the user can // just start typing. ...
... newline. text = textArea.value.replace(/(\r\n|\n|\r)/gm,""); self.port.emit("text-entered", text); textArea.value = ''; } }, false); // Listen for the "show" event being sent from the // main add-on code. It means that the panel's about // to be shown. // // Set the focus to the text area so the user can // just start typing. ...
Logging - Archive of obsolete content
To follow this tutorial you'll need to have learned the basics of jpm. The DOM console object is useful for debugging JavaScript. Because DOM objects aren't available to the main add-on code, the SDK provides its own global console object with most of the same methods as the DOM console, including methods to log error, warning, or informational messages. ...
...ole object is useful for debugging JavaScript. Because DOM objects aren't available to the main add-on code, the SDK provides its own global console object with most of the same methods as the DOM console, including methods to log error, warning, or informational messages. You don't have to require
() anything to get access to the console. It is automatically made available to you. ...
...e defaults open "index.js" and add the line above execute jpm run Firefox will start, and the following line will appear in the command window you used to execute jpm run: info: Hello World! console in Content Scripts You can use the console in content scripts as well as in your main add-on code. The following add-on logs the HTML content of every tab the user loads, by calling console.log
() inside a content script: require("sdk/tabs").on("ready", function(tab) { tab.attach({ contentScript: "console.log(document.body.innerHTML);" }); }); console Output If you are running your add-on from the command line (for example, executing jpm run or jpm test) then the console's messages appear in the command shell you used. If you've installed the add-on in Firefox then the message...
...h({ contentScript: "console.log(document.body.innerHTML);" }); }); console Output If you are running your add-on from the command line (for example, executing jpm run or jpm test) then the console's messages appear in the command shell you used. If you've installed the add-on in Firefox then the messages appear in Firefox's Browser Console. But note that by default, calls to console.log
() will not result in any output in the Error Console for any installed add-ons: this includes add-ons installed using the Add-on Builder or using tools like the Extension Auto-installer. See "Logging Levels" in the console reference documentation for more information on this. Learning More For the complete console API, see its API reference. ...
Examples and demos from articles - Archive of obsolete content
r effect [html] The following example will delete and re-type simulating a typewriter all the text content of the NodeList which match a specified group of selectors. [article] Fade In/Out [html] Sometimes a page uses dozens and dozens of animations. In such a condition is difficult and unnatural to keep track of all events started and then to stop them when appropriate through the clearTimeout
() function. A possible approach to solve this problem is to nest all the informations needed by each animation to start, stop, etc. etc. in different objects and then to create a constructor for such class of objects in order to standardize and simplify the instantiation of them. Here is a possible and minimalist example of such abstraction, which for this reason we named MiniDaemon. [article] Im...
...informations needed by each animation to start, stop, etc. etc. in different objects and then to create a constructor for such class of objects in order to standardize and simplify the instantiation of them. Here is a possible and minimalist example of such abstraction, which for this reason we named MiniDaemon. [article] Image preview before upload [html] The FileReader.prototype.readAsDataURL
() method is useful, for example, to get a preview of an image before uploading it. [article] Note: The FileReader
() constructor was not supported by Internet Explorer for versions before 10. For a full compatibility code, see also our crossbrowser possible solution for image preview. Determine if an element has been totally scrolled [html] This example shows how to determine whether a user has...
... mouse goes over previews. .[article] Pure-CSS web gallery based on the :checked pseudoclass [zip] You can also use the :checked pseudo-class applied to hidden radioboxes in order to build, for example, an image gallery with full-size images shown only when mouse clicks on previews. [article] Pure-CSS tooltips [html] This shows the use of the ::after pseudo-element in conjunction with the attr
() CSS expression and a data-descr custom data attribute to create a pure-CSS, glossary-like tooltip. [article] Pure-CSS lightbox [html] The :target pseudo-class is useful to switch on/off some invisible elements. In this way you can create a pure-CSS lightbox. [article] Pure-CSS editable (pseudo)<select> [html] This example shows how it's possible to simulate an editable <select> through a fiel...
...togrowing during a typing. Insert some custom text in a <textarea> This example shows how to insert some HTML tags or smiles or any custom text in a textarea. Using setInterval within animations Sometimes a page uses dozens and dozens of animations. In such a condition is difficult and unnatural to keep track of all events started and then to stop them when appropriate through the clearTimeout
() function. A possible approach to solve this problem is to nest all the informations needed by each animation to start, stop, etc. etc. in different objects and then to create a constructor for such class of objects in order to standardize and simplify the instantiation of them. Convert relative paths to absolute This example show how to translate relative paths to absolute paths. A shortcut to...
Progress Listeners - Archive of obsolete content
Note that onPageLoad does not fire for back button clicks. ...
... A commonly asked question is how to get notified whenever the URL in the address bar (also known as location bar) changes. Using the following code, you will get notified when user navigates to another page (by clicking a link, using the back/forward button, by typing an address in the Location Bar, etc.) and also when user switches tabs. var myExtension = { oldURL: null, init: function
() { gBrowser.addProgressListener(this); }, uninit: function
() { gBrowser.removeProgressListener(this); }, processNewURL: function(aURI) { if (aURI.spec == this.oldURL) return; // now we know the url is new... alert(aURI.spec); this.oldURL = aURI.spec; }, // nsIWebProgressListener QueryInterface: XPCOMUtils.generateQI(["...
... now we know the url is new... ...
... alert(aURI.spec); this.oldURL = aURI.spec; }, // nsIWebProgressListener QueryInterface: XPCOMUtils.generateQI(["nsIWebProgressListener", "nsISupportsWeakReference"]), onLocationChange: function(aProgress, aRequest, aURI) { this.processNewURL(aURI); }, onStateChange: function
() {}, onProgressChange: function
() {}, onStatusChange: function
() {}, onSecurityChange: function
() {} }; window.addEventListener("load", function
() { myExtension.init
() }, false); window.addEventListener("unload", function
() { myExtension.uninit
() }, false); Note: If you use the same listener for more than one tab/window, use aWebProgress.DOMWindow in the callback methods to obtain the tab/window which triggers the stat...
Windows - Archive of obsolete content
This article offers code snippets demonstrating common tasks you may wish to perform. Opening new browser windows To open a new browser window, you can simply use window.open
(). However, window.open
() returns a Window object for content, not for the browser window itself, so you should get the chrome Window first. The simplest way to do that is to use nsIWindowMediator. ...
... This article offers code snippets demonstrating common tasks you may wish to perform. Opening new browser windows To open a new browser window, you can simply use window.open
(). However, window.open
() returns a Window object for content, not for the browser window itself, so you should get the chrome Window first. The simplest way to do that is to use nsIWindowMediator. ...
...t in. Additionally, if the window is in the background, it may not be brought to the front. This code will check for a window of the provided name. If it finds one, it focuses it. If it doesn't, it opens one. ...
...he front. This code will check for a window of the provided name. If it finds one, it focuses it. If it doesn't, it opens one. var wenum = Components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getService(Components.interfaces.nsIWindowWatcher) .getWindowEnumerator
(); var index = 1; var windowName = "yourWindowName"; while (wenum.hasMoreElements
()) { var win = wenum.getNext
(); if (win.name == windowName) { win.focus
(); return; } index++ } window.open("chrome://to/your/window.xul", windowName, "features"); Uniquely identifying DOM windows Requires Gecko 2.0(Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) In Gecko, each DOM window has a unique 64-bit ID number. You can get a DOM window's ID using the nsIDOMWindowUtils at...
Displaying web content in an extension without security issues - Archive of obsolete content
ument (remember, content documents have no access to the chrome documents above them) and consequently no privileges. So in the simplest case you would have: <iframe type="content" src="data:text/html,%3Chtml%3E%3Cbody%3E%3C/body%3E%3C/html%3E"/> But usually you don't want to start with an empty document, you would rather want to load some template into the frame: var request = new XMLHttpRequest
(); request.open("GET", "chrome://foo/content/template.html", false); request.send(null); frame.setAttribute("src", "data:text/html," + encodeURIComponent(request.responseText)); That way you can have the template in your extension but still strip it off all privileges when it is loaded in a frame. Restricting what documents that contain untrusted data can do There are several restrictions that can...
...And scripts won't run anyway when inserted via innerHTML, right? Well, not quite. It is right that <script>alert('xss')...
...e = doc.getElementById("entryTemplate"); var entry = template.cloneNode(true); entry.removeAttribute("id"); entry.getElementsByClassName("title")[0].textContent = title; entry.getElementsByClassName("description")[0].textContent = description; template.parentNode.appendChild(entry); The important difference here is that the result will always have the same structure as the template tag. ...
... the same structure as the template tag. cloneNode
() always creates a copy and textContent only manipulates text. So there is no chance of accidentally adding new elements or attributes. But what if you have to display HTML rather than only text, e.g. an RSS feed entry? Extension authors will often come up with flawed attempts to sanitize HTML code. Instead, nsIScriptableUnescapeHTML.parseFragment
() method should be used that is meant for just that scenario: var target = entry.getElementsByClassName("description")[0]; var fragment = Components.classes["@mozilla.org/feed-unescapehtml;1"] .getService(Components.interfaces.nsIScriptableUnescapeHTML) .parseFragment(description, false, null, target); target.appendChild(fragment); This will add th...
Downloading JSON and JavaScript in extensions - Archive of obsolete content
This practice is dangerous and will not, in fact, pass an AMO review. So the extension will not be allowed to move out of the AMO sandbox. ...
... actions? Fairly easy if the webserver where the JavaScript is hosted were to be hijacked or compromised. It happens to the best of us. AMO takes the threat very seriously. The good news is there are several ways to workaround the problem. ...
...eveloper should be using one of the JSON decoding methods discussed here and not using eval
() at all. JSON is about state and does not allow functions to be decoded. The JSON decoding methods available to extension developers protect the extension from malicious JSON and JavaScript. Downloading state from a remote webserver using JSON is becoming extremely popular. Use the JSON decoders, not eval
()! Downloading JavaScript Of course there are times when JavaScript code modules are downloaded and injected into the extension. This usually happens because the extension is trying to keep some of its code fresh and dynamic, and the developers don't want to create a new version of the extension for each script change. In this case, JavaScript sandboxing should be used to isolate the downloaded J...
...xtension. This usually happens because the extension is trying to keep some of its code fresh and dynamic, and the developers don't want to create a new version of the extension for each script change. In this case, JavaScript sandboxing should be used to isolate the downloaded JavaScript from the rest of the extension, and host application. Sandboxing is done using Components.utils.evalInSandbox
(). The JavaScript code is added to the sandbox along with any "safe" objects the JavaScript needs to interact. Sandboxing is not without its dangers and developers should read the sandboxing page carefully to make sure untrusted code is not leaked out of the sandbox. ...
Appendix D: Loading Scripts - Archive of obsolete content
context = content; // Create the Sandbox let sandbox = Components.utils.Sandbox(context, { // Make properties of the context object available via the // script's global scope sandboxPrototype: context, // Wrap objects retrieved from the sandbox in XPCNativeWrappers. // This is the default action. ...
...// The following may be used instead at the top-level: // // let context = this if (Components.utils.getGlobalForObject) // Gecko 2.x var context = Components.utils.getGlobalF...
...on and the resultant extension compatibility issues can often be avoided by loading sub-scripts into private namespaces. Flexibility: The sub-script loader can load scripts into a variety of different namespaces for a wide variety of uses, and as of Gecko 2 allows the character set of the script to be specified. ...
...zIJSSubScriptLoader.loadSubScript
() are loaded from a cache. Unlike modules, however, scripts are still executed each time they are loaded and therefore still suffer performance and memory disadvantages over that method. When loading into a Sandbox object, the same advantages apply as above. Disadvantages Performance: Prior to Gecko 8.0, scripts loaded via mozIJSSubScriptLoader.loadSubScript
() are not loaded from a cache, and therefore must be read and compiled each time they are loaded which has a significant overhead for large code bases. Although wary authors can choose to cache instances of their modules so that modules are loaded only once globally, this method can be easily misused to re-load scripts for each new window where they would be better loaded only once globally per ses...
Connecting to Remote Content - Archive of obsolete content
window.alert("Error Status: " + aEvent.target.status); }; request.open("GET", url, true); request.send(null); In this example we demonstrate how to make a XMLHttpRequest call in asynchronous mode. You can see that an instance of the XMLHttpRequest class is created and it holds all functionality for making a request. We create this instance using XPCOM instead of the usual way (new XMLHttpRequest
()) because this way works both in chrome and non-chrome code. Following initialization, onload and onerror handlers are registered to a callback function to handle the response returned from the remote server. In both cases aEvent.target is an nsIXMLHttpRequest. In the onload callback function, the responseText parameter contains the server response as text. If the response is an XML document, th...
...eType to force the response to be parsed as XML. request.overrideMimeType("text/xml"); // do this before sending the request! The open method takes two required parameters: the HTTP request method and the URL to send the request. The HTTP request method can be "GET", "POST" or "PUT". Sending a POST request requires you to set the content type of the request and to pass the post data to the send
() method as below. request.open("POST", url, true); request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); request.send("data=hello&version=2"); The third parameter for the open method specifies whether the request should be handled asynchronously or not. In asynchronous mode code execution continues immediately after the send call. In synchronous mode the code and user i...
...interfaces.nsIFileInputStream); let xsltProcessor = Components.classes["@mozilla.org/document-transformer;1?type=xslt"] .createInstance(Components.interfaces.nsIXSLTProcessor); let xslDocument; fileStream.init(someXSLFile, -1, 0x01, 0444); // read only // parse from the XSLT stylesheet file stream xslDocument = domParser.parseFromStream( fileStream, null, fileStream.available
(), "text/xml"); // import the XSLT stylesheet to the XSLT processor xsltProcessor.importStylesheet(xslDocument); Finally, you can either use nsIXSLTProcessor.transformToDocument
() or nsIXSLTProcessor.transformToFragment
() methods to transform the XML document. The nsIXSLTProcessor.transformToDocument
() method returns a DOM Document with the results of the transformation, whereas, the nsIXSLTProc...
...In this example code, the first child of the XUL document is appended to a XUL element after the transformation. ...
Handling Preferences - Archive of obsolete content
owed by some namespacing and finally the actual name of the preference. Name parts are normally separated by dots. Now let's look at how we actually manage the preference values. Managing preferences with XPCOM We use the Preferences Service in order to get and set preference values: this._prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); // ... ...
...ots. Now let's look at how we actually manage the preference values. Managing preferences with XPCOM We use the Preferences Service in order to get and set preference values: this._prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); // ... get count
() { return this._prefService.getIntPref("extensions.xulschoolhello.message.count"); }, increment : function
() { let currentCount = this._prefService.getIntPref("extensions.xulschoolhello.message.count"); this._prefService.setIntPref("extensions.xulschoolhello.message.count", currentCount + 1); } One important thing to keep in mind is that the "get" methods of the service can throw an exception if the preference is not found. If you are going to use XPCOM, you should always set a default value...
...e to install.rdf: <em:optionsURL>chrome://xulschoolhello/content/preferencesWindow.xul</em:optionsURL> If you want to open this window from a different place in the UI, such as a menu item or a button in a toolbar, you need to take into account that the opening behavior of a Preferences window is different depending on the operating system. ...
...It does 2 things: Check if the Preferences window is already open. In that case, just give it focus. Make the window modal in systems where the instant apply rule is not used. Notice that this is a preference that users can switch, so checking for the operating system is not good enough. The gene...
Intercepting Page Loads - Archive of obsolete content
to use. Note: Performance is very important when it comes to add-ons and page loads. Read the recommendations in Appendix A regarding performance if you're planning on implementing any of these. The Easy Way: Load Events This comes from the tabbrowser code snippets page. In a nutshell, from the chrome code in the overlay we add an event listener for the load event. this._loadHandler = function
() {that._onPageLoad
(); }; gBrowser.addEventListener("load", this._loadHandler, true); gBrowser is a global object that corresponds to the tabbrowser element in the main browser window. It is full of useful functions, so you should always keep it in mind when you want to handle tabs and web content windows. Attaching the load event handler to gBrowser allows us to listen to these events for all t...
... the various stages in page loads. But of course, there's always a price to pay: web progress listeners in the chrome are attached to specific instances of the browser element. What does this mean? It means you have to keep track of tabs being opened and closed, in order to add and remove your listener. ...
... remove your listener. ...
...ation. Other extensions might add XUL windows that allow navigation as well, so in those cases it's best to use a global solution like this one. Content Policy Finally, there is the option of implementing nsIContentPolicy. You can create an XPCOM component that extends nsIContentPolicy and register it to the "content-policy" category using the nsICategoryManager. The nsIContentPolicy.shouldLoad
() method is the only one in this interface that is really useful. It actually allows for cleaner-looking code than most of the previously seen solutions, because you get the content URI directly as an argument, and you indicate if the content should be loaded or not with the return value, which has well-defined possible values. The context parameter gives you access to the window loading the conten...
Local Storage - Archive of obsolete content
. The structure could be something like this: s435L.default (your profile directory) XULSchool log.txt somedbfile.sqlite The Directory Service and the nsIFile interface are used to create the local directory. Here's what we usually do: we have a function that returns a reference to our root directory and creates it if necessary. getLocalDirectory : function
() { let directoryService = Cc["@mozilla.org/file/directory_service;1"]. getService(Ci.nsIProperties); // this is a reference to the profile dir (ProfD) now. let localDir = directoryService.get("ProfD", Ci.nsIFile); localDir.append("XULSchool"); if (!localDir.exists
() || !localDir.isDirectory
()) { // read and write permissions to owner and group, read-only for others. l...
...eneral this is the only directory flag you'll need, but sometimes you'll need access to other system directories, and you don't want to have to worry about which operating system or system language your extension is running on. A full list of these flags can be found in the Firefox source. Having that function in place, we do something like the following: let myFile = XULSchool.getLocalDirectory
(); myFile.append("someFile.txt"); // do stuff with the file. Files are handled with the nsIFile interface. An nsIFile doesn't necessarily represent an existing file, as in the previous examples. You first specify the file using nsIFile and then use nsIFile.create
() to actually write it out to disk. You can also check if an nsIFile exists using nsIFile.exists
(). To read and write information in f...
...milar to the Log4J logger used in Java projects. The logger is called Log4Moz and it is implemented as a JavaScript Code Module, so it only works on Firefox 3 and above. To use this logger, you need to copy the log4moz.js file to your modules directory. In the initialization method of your one of your "common" or startup objects, add the following code: let formatter = new Log4Moz.BasicFormatter
(); let root = Log4Moz.repository.rootLogger; let logFile = this.getLocalDirectory
(); // remember this? let appender; logFile.append("log.txt"); // Loggers are hierarchical, lowering this log level will affect all // output. root.level = Log4Moz.Level["All"]; // this appender will log to the file system. appender = new Log4Moz.RotatingFileAppender(logFile, formatter); appender.level = Log4Moz.Lev...
...ou'll need to carefully add migration code that moves the data from the old DB format to the new, and this becomes increasingly complex as you add new versions and new structure changes. So, be careful and plan for the future. There are two paths you can take when creating the local database you'll be using for your extension: Generate the database file (through mozIStorageService.openDatabase
(), all tables (through mozIStorageConnection.createTable
(), and initial data when your extension starts up for the first time. If you need a complex database this can be heavy in terms of time and code, but this will only happen once and this can be done in a lazy or asynchronous way. Have an initial database file in your defaults directory that you can copy to the user's profile. This way you jus...
Security best practices in extensions - Archive of obsolete content
e docshell. frame.docShell.allowImages = false; frame.docShell.allowJavascript = false; frame.docShell.allowPlugins = false; There are more examples listed in the document listed above in this section. In certain circumstances you may want to run code in your extension, but you would like to give it restricted privileges. One of the best ways to do this is to use Components.utils.evalInSandbox
(). Note that objects passed into the sandbox are restricted, but objects that come back out from it are not. Refer to the document to find out how to avoid such pitfalls. For more information, refer to the evalInSandbox section. The sidebar: a use case The sidebar in Firefox is designed to hold both chrome (privileged) content and Web (nonprivileged) content, the latter being in the form of Web p...
...r pages coming from the server, you need to take steps to ensure that the content can not call back into the Web browser and run malicious code. The main way to do this is by creating an iframe or browser element in the sidebar, and loading your content there. Give the element a type="content" attribute, which essentially sandboxes the code there and blocks callback rights into chrome. Using eval
() in an extension Using the built-in JavaScript eval function is frowned upon in the context of extensions. While there are some legitimate use-cases, most of the time there are safer alternatives. This blog post offers some excellent reasons not to use eval
(). Sandboxed HTTP connections The main purpose of sandboxed HTTP connections is to interact with a web service, without interfering with th...
...c="http://mysite.greatsite.com/js/wow-content.js" /> In general, scripts that are from remote sources that run in the chrome context are not acceptable, as many times the source of the script can never be 100% guaranteed, and they are vulnerable to man-in-the-middle attacks. The only legitimate environment for remote scripts is to run in a sandbox. For more information, refer to the evalInSandbox
() section. evalInSandbox The evalInSandbox document explains very well how it works, so there will be no repetition here. The usefulness of it and power of how it works is best illustrated by the popular Greasemonkey extension, which works on the premise of scripts being downloaded and stored locally, to be injected into the web content context via the sandbox. Many extensions use the Greasemonke...
...his article is about websites, but gives some insights into the general risks. When you do include other scripts, there are a number of things you can do to ensure their integrity and safety for users. The first is to always get it from a trusted source. Another thing you should do is namespace it just in case other add-ons include it. For example, if you're using jQuery, there's jQuery.noConflict
(). Conclusion Security can't be taken for granted, and for every release of your add-on, a new security audit should take place. A good place to keep up with Mozilla security announcements and security discussion is at the Mozilla Security Blog. ...
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
ata is available (a web page is loaded into the IFRAME) this will not affect the web page context because the IFRAME is not visible. Data Loader Component This component is a simple JavaScript function that sets the src attribute of the hidden IFRAME, causing it to load an URL (i.e., by establishing a request on the server side): /* Triggers the iframe to retrieve new data */ function retrieveData
() { bridgeFrame.src = dataUrl; } Once a web page is loaded into the IFRAME, the Data Binder will be able to get the data from the IFRAME's page and set the data into the main page's context. Data Binder Component The Data Binder is responsible for setting the data into the main page. However the Data Binder should know exactly when the data is available in the IFRAME. There are two basic approaches...
...es for DevEdge articles. This example uses the actual XML datasources from DevEdge web site. This example also follows the same model with a Data Loader and Data Binder component. Data Loader Component This component uses XMLHTTPRequest to load the XML data that represents the article headlines. XMLHTTPRequest interface returns the DOM for the document that was passed. var x = new XMLRemoteRequest
(); doc=x.getRemoteDocument(loaddata); Note: the above code snippet shows an object being instanciated based on a class named XMLRemoteRequest. This class is just an abstraction layer that encapsulates the XMLHTTPRequest interface, and provides cross-browser support for recent IE versions and Gecko-based browsers. The following XML datasources are used in this sample: http://web.archive.org/web/2009...
...per of the Original Code is * Netscape Corporation. * Portions created by the Initial Developer are Copyright (C) 2003 * the Initial Developer. All Rights Reserved. ...
...ly load the headlines into this web page.</p> <br /> <!-- ***** This code dynamically creates the Tabbed Menu if the browser has support to XMLHTTPRequest, since the mechanism used here is XMLHTTPRequest ***** --> <script type="text/javascript" language="javascript"> //// /// Object detection // var xComp=null; var testXMLHTTPRequest=false; try { xComp = new XMLHttpRequest
(); if(xComp) testXMLHTTPRequest=true; } catch (e) { try { xComp = new ActiveXObject("Microsoft.XMLHTTP"); if(xComp) testXMLHTTPRequest=true; } catch (e) { } } if(testXMLHTTPRequest&&document.getElementsByTagName) { document.write("<span style=\"margin-left:1em;\"> <a href=\"javascript:\" class=\"tab \" onclick=\"callDevEdge('/viewsource/catalog-new_en.xml',this);return false;\...
Install.js - Archive of obsolete content
'sampleext', // The leafname of the JAR file (without the .jar part) extVersion: '1.0', extAuthor: 'Insert-your-name-here', extLocaleNames: null, // e.g. ['en-US', 'en-GB'] extSkinNames: null, // e.g. ...
...'en-US', 'en-GB'] extSkinNames: null, // e.g. ...
...le] + '/' + this.extShortName + '/'; Install.registerChrome(Install.LOCALE | installType, jarPath, regPath); } // Register skins for (var skin in this.extSkinNames) { var regPath = 'skin/' + this.extSkinNames[skin] + '/' + this.extShortName + '/'; Install.registerChrome(Install.SKIN | installType, jarPath, regPath); } // Perform install var err = Install.performInstall
(); if (err == Install.SUCCESS || err == Install.REBOOT_NEEDED) { if (!this.silentInstall && this.extPostInstallMessage) { Install.alert(this.extPostInstallMessage); } } else { this.handleError(err); return; } }, parseArguments: function
() { // Can't use string handling in install, so use if statement instead var args = Install.arguments; if (args == 'p=0') ...
...fileInstall = false; this.silentInstall = true; } else if (args == 'p=1') { this.profileInstall = true; this.silentInstall = true; } }, handleError: function(err) { if (!this.silentInstall) { Install.alert('Error: Could not install ' + this.extFullName + ' ' + this.extVersion + ' (Error code: ' + err + ')'); } Install.cancelInstall(err); } }; XpiInstaller.install
(); ...
Monitoring WiFi access points - Archive of obsolete content
f available WiFi access points to obtain information about them including their SSID, MAC address, and signal strength. This capability was introduced primarily to allow WiFi-based location services to be used by geolocation services. Example This example simply displays a list of the available access points. ...
...{ netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); if (iid.equals(Components.interfaces.nsIWifiListener) || iid.equals(Components.interfaces.nsISupports)) return this; throw Components.results.NS_ERROR_NO_INTERFACE; }, } netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); var listener = new test
(); var wifi_service = Components.classes["@mozilla.org/wifi/monitor;1"].getService(Components.interfaces.nsIWifiMonitor); wifi_service.startWatching(listener); </script> </head> <body> <div id="d"><p></p></div> <div id="c"><p></p></div> </body> </html> The nsIWifiListener object The first thing the code above does is to prototype the listener object that will be receiving notifications of c...
...iMonitor); wifi_service.startWatching(listener); </script> </head> <body> <div id="d"><p></p></div> <div id="c"><p></p></div> </body> </html> The nsIWifiListener object The first thing the code above does is to prototype the listener object that will be receiving notifications of changes to the access point list. This object is described in lines 11 through 40 in the code above. ...
...ge
() method (lines 13 through 27) begins by enabling UniversalXPConnect privileges, then clearing out the div (d) that will receive the updated list of access points. Then the loop in lines 19-22 iterates over the list of access points received in the accessPoints array and adds them to the HTML in the div. Then the c div is updated with the number of times the list has been refreshed. The onError
() method simply opens an alert that displays the error code received. Starting to monitor access points To start monitoring the access points, we instantiate the listener (on line 44), then get access to the WiFi monitor interface on line 45. The monitoring is started up on line 47, by calling the WiFi monitoring service's startWatching
() method. ...
Drag and Drop Example - Archive of obsolete content
the DOM's getAttribute function. We need this so that we know what type of element to create when dragging. Next, we'll define the two listener objects. First, the listObserver which needs a function to handle the start of the drag. var listObserver = { onDragStart: function (event, transferData, action) { var txt = event.target.getAttribute("elem"); transferData.data = new TransferData
(); transferData.data.addDataForFlavour("text/unicode", txt); } } One function has been defined, onDragStart, which will be called by the nsDragAndDrop object when necessary. The function adds the data to be dragged to the transfer object. The elem attribute is retrieved from the target of the drag event. The target will be the element that had the drag start on. We'll use the value of this a...
...t of the drag event. The target will be the element that had the drag start on. We'll use the value of this attribute as the data of the drag. The boardObserver will need three functions, getSupportedFlavours, onDragOver and onDrop. The onDrop function will grab the data from the drag session and create a new element of the appropriate type. ...
...e the element that had the drag start on. We'll use the value of this attribute as the data of the drag. The boardObserver will need three functions, getSupportedFlavours, onDragOver and onDrop. The onDrop function will grab the data from the drag session and create a new element of the appropriate type. ...
...ckbox" ondraggesture="nsDragAndDrop.startDrag(event, listObserver)"/> <button label="Text Box" elem="textbox" ondraggesture="nsDragAndDrop.startDrag(event, listObserver)"/> </vbox> </window> var listObserver = { onDragStart: function (event, transferData, action) { var txt = event.target.getAttribute("elem"); transferData.data = new TransferData
(); transferData.data.addDataForFlavour("text/unicode", txt); } }; var boardObserver = { getSupportedFlavours : function
() { var flavours = new FlavourSet
(); flavours.appendFlavour("text/unicode"); return flavours; }, onDragOver: function (event, flavour, session) {}, onDrop: function (event, dropdata, session) { if (dropdata.data != "") { var elem = document.
Metro browser chrome tests - Archive of obsolete content
ory, then all metro browser chrome tests will be run. For example, to run a specific test the command would be: ./mach mochitest-metro browser/metro/base/tests/mochitest/(testfile) Writing browser chrome tests Metro browser chrome tests make use of a common framework for defining and running tests. ...
...hrome tests will be run. For example, to run a specific test the command would be: ./mach mochitest-metro browser/metro/base/tests/mochitest/(testfile) Writing browser chrome tests Metro browser chrome tests make use of a common framework for defining and running tests. A simple test looks like this: gTests.push({ desc: "Test loading about:blank", setUp: function
() { }, tearDown: function
() { }, run: function
() { yield addTab("about:blank"); is(tab.browser.currentURI.spec, "about:blank", "about:blank is loaded"); } }); function test
() { runTests
(); } gTests contains individual tests that make up the library of tests your test file will contain. Each test can have start up and tear down logic, plus the body of the test contained in run
(). The test file can contain ot...
...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. ...
...d additional common utils and helpers to head.js. Be careful about changing existing helpers as changes may impact tests in other libraries. Static content for tests Static content (html files, images, etc.) should be stored in sub directories to avoid polluting the main test directory. Sub directories for larger test suites may also be created. Exceptions in tests Any exceptions thrown under test
() will be caught and reported as a general failure. setUp
(), tearDown
(), and run
() each have individual exception handlers to prevent one method from interfering with the execution of another. An exception in any of these methods will cause a test failure. Additional built-in framework test checks will run after the completion of each individual test insuring tests clean up properly. For more infor...
RDF Datasource How-To - Archive of obsolete content
e. There are basically two approaches that you can take in this endeavor: Delegate to an inner proxy. For example, you may choose to delegate to the in-memory datasource, which is a generic datasource that implements nsIRDFDataSource. Typically, you provide a parser for reading in some sort of static storage (e.g., a data file); the parser translates the datafile into a series of calls to Assert
() to set up the in-memory datasource. When Flush
() is called, or the last reference to the datasource is released, a routine walks the in-memory datasource and re-serializes the graph back to the original file format. For examples of an implementation like this, look at the RDF/XML datasource or the bookmarks datasource. You may want to choose this implementation if your primary goal is to "wrap" a...
...ement the nsIRDFDataSource interface. See Aggregating the In-Memory Datasource for technical details. If you take this approach, you won't be able to selectively implement methods of the nsIRDFDataSource interface; instead, all of the methods will be "forwarded" to the in-memory datasource. This can be useful if your datasource is "read-only", and you aren't worried about modification using Assert
(), etc. Implement the interface yourself. If you choose this route, you'll need to implement each of the nsIRDFDataStore methods "by hand". Although this is more work, it is really the only way to create a "live" datasource that may be changed by some outside agent. The file system datasource and local mail datasource are good examples of datasources that have been implemented this way. You'll pr...
...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 manager rv = compMgr->RegisterComponent(kMyDataSourceCID, "My Data Source", NS_RDF_DATASOURCE_PROGID_PREFIX "my-datasource", ...
...y-datasource", aPath, PR_TRUE, PR_TRUE); ... } Replace kMyDataSourceCID with your datasource's CLSID. Replace "My Data Source" with a descriptive string that should appear in the registry. Finally, replace "my-datasource" with a value appropriate for your datasource. This value, when prefixed with "rdf:", is a datasource identifier, and may be used with nsIRDFService::GetDataSource
() to retrieve your datasource from the RDF service. For example, the above datasource would be accessable as follows: nsIRDFService* rdf; rv = nsServiceManager::GetService(kRDFServiceCID, kIRDFServiceIID, (nsISupports**) &rdf); if (NS_SUCCEEDED(rv)) { nsIRDFDataSource* myDataSource; rv = rdf->GetDataSource("rdf:my-datasource", &myDataSource); if (N...
Windows Install - Archive of obsolete content
// subkeys have to exist before values can be put in. var subkey; // the name of the subkey you are poking around in var valname; // the name of the value you want to look at var value; // the data in t...
... = getFolder("Temporary"); //Notes: // can't use a double backslash before subkey // - Windows already puts it in. // subkeys have to exist before values can be put in. var subkey; // the name of the subkey you are poking around in var valname; // the name of the value you want to look at var value; // the data in the value you want to look at. var winreg = getWinRegistry
() ; if(winreg != null) { // Here, we get the current version. winreg.setRootKey(winreg.HKEY_CURRENT_USER) ;// CURRENT_USER subkey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce" ; winreg.createKey(subkey,""); valname = "ren8dot3"; value = fProgram + "ren8dot3.exe " + fTemp + "ren8dot3.ini"; err = winreg.setValueString(subkey, valname, value); }...
... for(i = 0; i < listLongFilePaths.length; i++) { fLongFilePath = getFolder(fProgram, listLongFilePaths[i]); sShortFilePath = File.windowsGetShortName(fLongFilePath); if(sShortFilePath) { fRen8dot3Ini.writeString("rename", sShortFilePath, fLongFilePath); bIniCreated = true; } } if(bIniCreated) updateWinReg4Ren8dot3
() ; } return(0); } // main var srDest; var err; var fProgram; srDest = 449; err = initInstall(prettyName, regName, "6.0.0.2000110801"); logComment("initInstall: " + err); fProgram = getFolder("Program"); logComment("fProgram: " + fProgram); if(verifyDiskSpace(fProgram, srDest)) { setPackageFolder(fProgram); err = addDirectory("", "6.0.0.2000110801", "bin", // dir name in jar to ...
...r("Program"); logComment("fProgram: " + fProgram); if(verifyDiskSpace(fProgram, srDest)) { setPackageFolder(fProgram); err = addDirectory("", "6.0.0.2000110801", "bin", // dir name in jar to extract fProgram, // Where to put this file // (Returned from GetFolder) "", // subdir name to create relative to fProgram true); // Force Flag logComment("addDirectory
() returned: " + err); // check return value if(err == SUCCESS) { err = performInstall
(); logComment("performInstall
() returned: " + err); } else cancelInstall(err); } else cancelInstall(INSUFFICIENT_DISK_SPACE); // end main ...
toString - Archive of obsolete content
verts an InstallVersion init object to a string. Method of InstallVersion object Syntax String version = InstallVersion.toString ( initObj ); Parameters The toString method has the following parameter: initObj initObj is an InstallVersion object whose init method has been called. Returns The major, minor, revision, and build numbers represented as a single string. ...
...t whose init method has been called. Returns The major, minor, revision, and build numbers represented as a single string. The init
() function can input the version number as a single string or as a series of parameters representing the version numbers of the installation. ...
... single string. The init
() function can input the version number as a single string or as a series of parameters representing the version numbers of the installation. ...
...single string or as a series of parameters representing the version numbers of the installation. ...
id - Archive of obsolete content
<< XUL Reference home id Type: unique id A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById
() and other DOM functions and to reference the element in style sheets. ...
... << XUL Reference home id Type: unique id A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById
() and other DOM functions and to reference the element in style sheets. ...
... << XUL Reference home id Type: unique id A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById
() and other DOM functions and to reference the element in style sheets. ...
...would be a <button id="foo" label="Click Me" oncommand="setWidgetLabel(this, 'I was pressed')"/> <script> function setWidgetLabel(idName, newCaption){ document.getElementById( idName.id ).setAttribute('label',newCaption) } </script> Not specifying the id attribute for a window or a prefwindow fills the console with the following warning message: Warning: Empty string passed to getElementById
() See also name ...
insertItemAt - Archive of obsolete content
<< XUL Reference home insertItemAt( index, label, value ) Return type: element This method creates a new item and inserts it at the specified position. You may optionally set a value. The new item element is returned. ...
...at the specified position. You may optionally set a value. The new item element is returned. ...
...hat does not exist, eg: trying to insert an item at the end with element.getRowCount
() + 1 Example <!-- This example inserts at the selected item or appends, then selects the newly created item --> <script language="javascript"> function insertItemToList
(){ var myListBox = document.getElementById('myListBox'); // create a date to get some labels and values var someDate = new Date
(); if(myListBox.selectedIndex == -1){ // no item was selected in list so append to the end myListBox.appendItem( someDate.toLocaleTimeString
(), someDate.getTime
() ); var newIndex = myListBox.getRowCount
() -1 }else{ // item was selected so insert at the selected item var newIndex = myListBox.selectedIndex; myListBox.insertItemAt(newIndex, so...
...tedIndex == -1){ // no item was selected in list so append to the end myListBox.appendItem( someDate.toLocaleTimeString
(), someDate.getTime
() ); var newIndex = myListBox.getRowCount
() -1 }else{ // item was selected so insert at the selected item var newIndex = myListBox.selectedIndex; myListBox.insertItemAt(newIndex, someDate.toLocaleTimeString
(), someDate.getTime
()); } // select the newly created item myListBox.selectedIndex = newIndex; } </script> <button label="Insert item at selected" oncommand="insertItemToList
()"/> <listbox id="myListBox"> <listitem label="foo"/> </listbox> See also appendItem
() removeItemAt
() ...
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
<!-- composer --> <toolbar id="EditToolbar"> <toolbarbutton id="custom-button-1" position="18"/> </toolbar> <!-- chat --> <menubar id="mainmenu"> <menu id="custom-menu" position="4" label="Custom" accesskey="C"> <menupopup> <menuitem id="custom-item-1" label="Custom Item 1" accesskey="1" tooltiptext="My custom menu item" oncommand="CustomButton[1]
()" /> </menupopup> </menu> </menubar> <!-- calendar --> <toolbar id="calendar-bar"> <toolbarbutton id="custom-button-1" position="10"/> </toolbar> <!-- button details --> <toolbarbutton id="custom-button-1" label="Custom" tooltiptext="My custom toolbar button" oncommand="CustomButton[1]
()" class="toolbarbutton-1 custombutton" /> </overlay> Optionally custo...
... file, then your button's appearance will match the classic theme.) Save the file. Explanation: This CSS stylesheet specifies how the button is diaplayed. It links to the button image, specifying the dimensions of the six parts of the image. 8. Create a plain text file named button.js. Copy the following content, and paste it into the new file: CustomButton = { 1: function
() { alert("Just testing") }, } There is nothing to customize for now. Save the file. The next section in this tutorial contains examples of code that you can use to make your button do something useful. Explanation: This file specifies what happens when you press the button. It uses the JavaScript programming language, together with features provided by the application. 9. ...
...abel, accesskey and tooltiptext attributes to whatever you want. Do not change the class attribute. Now edit button.css. Duplicate the first two lines, changing the new lines to specify button-2. Edit button.js and add JavaScript code for the new button. Be sure to add the extra code before the curly brace on the last line of the file. For example, you could add this code for testing: 2: function
() { alert("Just testing again") }, Create an image for the new button, naming the file button-2s.png. The images supplied here have a 256-colour palette and a transparent background. They are in PNG format. Some other formats will also work. Here are some more images that you can download and use: Restart the application to find the new button. You can repeat these steps to add...
...The name must match the change that you made in step 1. 4. In your working directory, create a new directory named content. Move all the files from your original custombutton directory into your new content directory.
Open and Save Dialogs - Archive of obsolete content
icates the list of file types that are displayed in the dialog. This would be used, for example, to hide all but .html files. You can set the default directory by setting the displayDirectory property of the file picker object to a directory. The directory should be an nsILocalFile object. If you do not set this, a suitable default will be selected for you. To add filters, call the appendFilters
() function to set the file types that you wish to have displayed. fp.appendFilters(nsIFilePicker.filterHTML | nsIFilePicker.filterImages); fp.appendFilters(nsIFilePicker.filterText | nsIFilePicker.filterAll); The first example will add filters for HTML and for image files. The user will only be able to select those types of files. The manner in which this is done is platform specific. On some ...
..., each filter will be separate and the user can choose between HTML files and image files. The second example will add filters for text files and for all files. The user therefore has the option to display text files only or all files. You can also use filterXML and filterXUL to filter for XML and XUL files respectively. If you would like to filter for custom files, you can use the appendFilter
() function to do this: fp.appendFilter("All Files" ,"*.*"); fp.appendFilter("Audio Files (*.wav, *.mp3)","*.wav; *.mp3"); This line will add a filter for Wave and MP3 audio files. The first argument is the title of the file type and the second is a semicolon-seperated list of file masks. You can add more masks or fewer masks as needed. You can call appendFilter as many times as necessary to add ...
...he title of the file type and the second is a semicolon-seperated list of file masks. You can add more masks or fewer masks as needed. You can call appendFilter as many times as necessary to add additional filters. The order you add them determines their priority. Typically, the first one added is selected by default. Getting the selected file Finally, you can show the dialog by calling the show
() function. It takes no arguments but returns a status code that indicates what the user selected. Note that the function does not return until the user has selected a file. The function returns one of three constants: returnOK - the user selected a file and pressed OK. The file the user selected will be stored in the file picker's file property. returnCancel - the user pressed Cancel. returnR...
...be stored in the file picker's file property. returnCancel - the user pressed Cancel. returnReplace - in the save mode, this return value identifies that the user selected a file to be replaced. (returnOK will be returned when the user entered the name of a new file.) You should check the return value and then get the file object from the file picker using the file property. var res = fp.show
(); if (res != nsIFilePicker.returnCancel){ var thefile = fp.file; // --- do something with the file here --- } Next, we'll see how to create a wizard. << PreviousNext >> ...
XUL Parser in Python/source - Archive of obsolete content
I had to put this hack in here to suppress the printing out of the resolved namespace: # "xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul window", etc. ...
...w.mozilla.org/keymaster/gatekeeper/there.is.only.xul window", etc. ...
...ss XULParser(xmllib.XMLParser): def unknown_starttag(self, t, a): name = strip(t) if name not in el_list: el_list[name] = {} for attr,val in a.items
(): el_list[name][strip(attr)] = strip(val) def syntax_error(self, message): pass p = XULParser
() cmd = 'dir /s /b *.xul' CHROME_DIR = 'C:\Program Files\Netscape\Netscape 6\chrome' os.chdir(CHROME_DIR) files = os.popen(cmd).readlines
() for file in files: file = file.strip
() print '** ' + file + ' **' data = open(file).read
() p.feed(data) w.write('<html><h3>Periodic Table of XUL Elements</h3>') w.write('<table><style>.head {font-weight: bold; background-color: lightgrey;}</style>') elements = el_list.keys
() elements.sort
() for item in elements: w.write('<tr><td class="head">' + item + '</td></tr>\n') for a in el_list[ite...
...ead
() p.feed(data) w.write('<html><h3>Periodic Table of XUL Elements</h3>') w.write('<table><style>.head {font-weight: bold; background-color: lightgrey;}</style>') elements = el_list.keys
() elements.sort
() for item in elements: w.write('<tr><td class="head">' + item + '</td></tr>\n') for a in el_list[item]: w.write('<tr><td class="at">' + a + '</td>') w.write('</table></html>\n') w.close
() ...
menuitem - Archive of obsolete content
autocheck Type: boolean If this attribute is true or left out, the checked state of the button will be switched each time the button is pressed. If this attribute is false, the checked state must be adjusted manually. When autocheck is true, the button type should be "checkbox" or "radio". checked Type: boolean Indicates whether the element is checked or not. Use hasAttribute
() to determine whether this attribute is set instead of getAttribute
(). For buttons, the type attribute must be set to checkbox or radio for this attribute to have any effect. Note: if the checked attribute is set to true, and you persist its value via the persist attribute, Mozilla will fail to persist its value when the menuitem is unchecked because of bug 15232. A workaround is to set the au...
...s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
...ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
window - Archive of obsolete content
he actual displayed height may be different if the element or its contents have a minimum or maximum height. The CSS height property may also be used. hidechrome Type: boolean Set this attribute to true to have the chrome including the titlebar hidden. id Type: unique id A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById
() and other DOM functions and to reference the element in style sheets. inactivetitlebarcolor Type: color string Specify background color of the window's titlebar when it is inactive (background). Moreover this hides separator between titlebar and window contents. This affects only on Mac OS X. lightweightthemes Type: boolean true if the window supports lightweight themes, otherwise...
...e state of a window (together with the persist attribute) and for CSS styles (e.g. to hide the resizer grippy on maximized windows). Note: When a window is minimized, the sizemode attribute is not updated. This is done so that if a window is closed while minimized, its persisted sizemode attribute wouldn't be minimized. Setting this attribute does not change the window state. Use window.maximize
(), window.restore
(), or window.minimize
() to change the window state. To get the window state from JavaScript code, use window.windowState. Listen to the sizemodechange event dispatched to the DOM window to get notified when the window state changes. title Type: string The text to appear in the title bar of the window. width Type: string (representing an integer) The preferred wid...
...ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
Building XULRunner with Python - Archive of obsolete content
pref("browser.dom.window.dump.enabled", true); pref("javascript.options.showInConsole", true); pref("javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true); HTML <script> tags specify that Python is used withtype="application/x-python" attribute. DOM scripting is pretty much as with Java Script. ...
....strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true); HTML <script> tags specify that Python is used withtype="application/x-python" attribute. DOM scripting is pretty much as with Java Script. For example def onLoad
(): btnTest = document.getElementById("btnTest") btnTest.addEventListener('command', onTest, False) def onTest
(): window.alert('Button activated') window.addEventListener('load', onLoad, False) One possible gotcha is that the default python path used to find modules that areimported explicitly includes the xulrunner executable directory and the directory that is current when XULRunner launches. However it does not include any path related to the XUL application being run. Some work around will need t...
...ted explicitly includes the xulrunner executable directory and the directory that is current when XULRunner launches. However it does not include any path related to the XUL application being run. Some work around will need to be found. Unhandled exceptions are displayed in the JavaScript Error Console which can be opened usingxulrunner -jsconsole. One solution is to puttry .... ...
...will need to be found. Unhandled exceptions are displayed in the JavaScript Error Console which can be opened usingxulrunner -jsconsole. One solution is to puttry .... except: print_exc
() round any event handler to print tracebacks to stdout and use a python console to catch that output. ...
How to enable locale switching in a XULRunner application - Archive of obsolete content
t the list dynamically. The dynamic list population requires an XPCOM to query the currently selected locale as well as all locales available in the application package. ...
...owing how this is done: The definition of the XUL control: <listbox id="locale-listbox"> <!-- generated list items go in here --> </listbox> <button label="&switchLocale.button;" oncommand="changeLocale
()"/> The Javascript code to populate the control: try { // Query available and selected locales var chromeRegService = Components.classes["@mozilla.org/chrome/chrome-registry;1"].getService
(); var xulChromeReg = chromeRegService.QueryInterface(Components.interfaces.nsIXULChromeRegistry); var toolkitChromeReg = chromeRegService.QueryInterface(Components.interfaces.nsIToolkitChromeRegistry); var selectedLocale = xulChromeReg.getSelectedLocale("localeswitchdemo"); var availableLocales = toolkitChromeReg.getLocalesForPackage("localeswitchdemo"); // Render locale menulist by ...
...ents.interfaces.nsIXULChromeRegistry); var toolkitChromeReg = chromeRegService.QueryInterface(Components.interfaces.nsIToolkitChromeRegistry); var selectedLocale = xulChromeReg.getSelectedLocale("localeswitchdemo"); var availableLocales = toolkitChromeReg.getLocalesForPackage("localeswitchdemo"); // Render locale menulist by iterating through the query result from getLocalesForPackage
() const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var localeListbox = document.getElementById("locale-listbox"); var selectedItem = null; while(availableLocales.hasMore
()) { var locale = availableLocales.getNext
(); var listitem = document.createElementNS(XUL_NS, "listitem"); listitem.setAttribute("value", locale); listitem.setAttribute("la...
... XULRunner doesn't allow runtime switching of the locale, therefore the application must be restarted to activate the new choice. Here is an example event handler which is fired when the user clicks on the button to change the locale. It saves the new locale to the user application preferences (thereby overriding the default prefs.js above) and then asks XULRunner to restart. function changeLocale
() { try { // Which locale did the user select? var localeListbox = document.getElementById("locale-listbox"); var newLocale = localeListbox.selectedItem.value; // Write preferred locale to local user config var prefs = Components.classes["@mozilla.org/preferences-service;1"]. getService(Components.interfaces.nsIPrefBranch); prefs.setCharPref("general.useragent.l...
XULRunner tips - Archive of obsolete content
ons.properties"); pref("extensions.getMoreExtensionsURL", "chrome://mozapps/locale/extensions/extensions.properties"); pref("extensions.getMoreThemesURL", "chrome://mozapps/locale/extensions/extensions.properties"); If your application is based on Gecko 2.0, you need to register a component through the new component registration because the extension manager uses FUEL, namely Application.restart
(), to restart your xulrunner-based application after any change (installation, removal, enabling, disabling) in the extensions' list: copy files fuelApplication.js and fuelApplication.manifest from browser/fuel/src for instance into your components/ directory tweak the line #include ../../../toolkit/components/exthelper/extApplication.js in your copy of fuelApplication.js as needed make sure t...
...There is a working stub. Any better suggestion? Venkman uses "chrome://communicator/skin/" as an alias for "chrome://global/skin/" and this alias was maintained in the XULRunner toolkit until XULRunner 1.9 was released. When using XULRunner 1.9 or greater, you can create your own alias in your chrome manifest add a "skin" line: skin communicator classic/1.0 skin/co...
... var windowDS = Components.classes["@mozilla.org/rdf/datasource;1?name=window-mediator"] .getService(Components.interfaces.nsIWindowDataSource); var tmpNameSpace = {}; var sl = Components.classes["@mozilla.org/moz/jss...
... Note: I use this method of installing extensions into all of my Mozilla applications. This way I have one directory where I keep all my Mozilla extensions, and each application (Firefox, Thunderbird) simply contains a few small, one line files pointing to the location of the extensions. (I keep them in source control to be sure I...
Monitoring plugins - Archive of obsolete content
is always null and should not be used. Here is an example that shows the runtime in an alert box to the user if the runtime exceeds half a second in length: observe: function(subject, topic, data) { if (topic == "experimental-notify-plugin-call" ) { if (data > 0.500) { alert("Runtime is: " + data); } } } NOTE: This is just a simplified example and the use of alert
() is discouraged as the component can send hundreds of notifications each second and could potentially cause your browser to crash if an excessive number of alert boxes are displayed. Also note that in the example above an if statement first checks to see that the arriving notification's topic is the correct one. This is useful in cases where your class is registered to receive notifications for m...
...hat contains the following code: var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); observerService.removeObserver(this, "experimental-notify-plugin-call"); Skeleton Observer Class Below is a skeleton class that you may use to listen to runtime notifications: function PluginObserver
() { this.registered = false; this.register
(); //takes care of registering this class with observer services as an observer for plugin runtime notifications } PluginWatcherObserver.prototype = { observe: function(subject, topic, data) { if (topic == "experimental-notify-plugin-call") //In case your class is registered to listen to other topics //This gets executed each time...
... var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); observerService.addObserver(this, "experimental-notify-plugin-call", false); this.registered =...
...mething you want to avoid!! ...
NPEvent - Archive of obsolete content
<< Gecko Plugin API Reference << Plug-in Side Plug-in API Summary Represents an event passed by NPP_HandleEvent
() to a windowless plug-in. Syntax Microsoft Windows typedef struct _NPEvent { uint16 event; uint32 wParam; uint32 lParam; } NPEvent; Mac OS typedef EventRecord NPEvent; TYPE EventRecord = RECORD { what: Integer; message: LongInt; when: LongInt; where: Point; modifiers: Integer; END; XWindows typedef XEvent NPEvent; Fields NPEvent on Microsoft Windows The data structure has the following fields: event One of the following event types: WM_PAINT WM_LBUTTONDOWN WM_LBUTTONUP WM_LBUTTONDBLCLK WM_RBUTTONDOWN WM_RBUTTONUP WM_RBUTTONDBLCLK WM_MBUTTONDOWN WM_MBUTTONUP WM_MBUTTONDBLCLK WM_MOUSEMOV...
...X11 event structures. type The type member is an int representing an event type, and indicating which structure is relevant. The event type may be any of the ollowing: GraphicsExpose FocusIn FocusOut EnterNotify LeaveNotify MotionNotify ButtonPress ButtonRelease KeyPress KeyRelease Description Microsoft Windows Description The type NPEvent represents an event passed by NPP_HandleEvent
() to a windowless plug-in. For information about these events, see your Microsoft Windows documentation. Mac OS Description The NPEvent object represents an event passed by NPP_HandleEvent
() to a windowless plug-in. This structure is defined as EventRecord, the event type used by Mac OS. On Mac OS, plug-ins receive the same events for both windowed and windowless plug-ins, as follows. Mouse even...
...getFocusEvent. adjustCursorEvent: Sent when the mouse enters or leaves the bounds of the instance. If your plug-in wants to set the cursor when the mouse is within the instance, set the cursor and return true. If you don't want a special cursor, return false and the browser will use the standard arrow cursor. XWindows Description The NPEvent object represents an event passed by NPP_HandleEvent
() to a windowless plug-in. The NPEvent structure is defined as XEvent, the definition of the event type used by the XWindows platform. For information about the XEvent structure and XWindows events, see the XWindows documentation. As the XEvents sent to the plug-in are synthesized and there is not a native window corresponding to the plug-in rectangle, some of the members of the XEvent structures a...
...the XWindows documentation. ...
NPN_InvalidateRect - Archive of obsolete content
on has the following parameters: instance Pointer to the plug-in instance to invalidate a portion of. invalidRect The area to invalidate, specified in a coordinate system that originates at the top left of the plug-in's content area. Description Before a windowless plug-in can repaint or refresh part of its drawing area, the plug-in must first invalidate the area with either NPN_InvalidateRect
() or NPN_InvalidateRegion
(). NPN_InvalidateRect
() causes the NPP_HandleEvent
() method to pass an update event or a paint message to the plug-in. After calling this method, the plug-in receives a paint message asynchronously. The browser redraws invalid areas of the document and any windowless plug-ins at regularly timed intervals. To immediately send a paint message, the plug-in can call NPN_ForceR...
...PN_InvalidateRegion
(). NPN_InvalidateRect
() causes the NPP_HandleEvent
() method to pass an update event or a paint message to the plug-in. After calling this method, the plug-in receives a paint message asynchronously. The browser redraws invalid areas of the document and any windowless plug-ins at regularly timed intervals. To immediately send a paint message, the plug-in can call NPN_ForceRedraw
() after calling this method. ...
...NPP_HandleEvent
() method to pass an update event or a paint message to the plug-in. After calling this method, the plug-in receives a paint message asynchronously. The browser redraws invalid areas of the document and any windowless plug-ins at regularly timed intervals. To immediately send a paint message, the plug-in can call NPN_ForceRedraw
() after calling this method. ...
...d to pass an update event or a paint message to the plug-in. ...
NPN_InvalidateRegion - Archive of obsolete content
dRegion); Parameters The function has the following parameters: instance Pointer to the current plug-in instance. invalidRegion The area to invalidate, specified in a coordinate system that originates at the top left of the plug-in. ...
...function has the following parameters: instance Pointer to the current plug-in instance. invalidRegion The area to invalidate, specified in a coordinate system that originates at the top left of the plug-in. Description Before a windowless plug-in can repaint or refresh part of its drawing area, the plug-in must first invalidate the area with either NPN_InvalidateRect
() or NPN_InvalidateRegion
(). NPN_InvalidateRegion
() causes the NPP_HandleEvent
() method to pass an update event or a paint message to the plug-in. If a plug-in calls this method, it receives a paint message later. The browser redraws invalid areas of the document and windowless plug-ins at regularly timed intervals. To force a paint message, the plug-in can call NPN_ForceRedraw
() after calling this method. See also NPN_For...
...validateRegion
() causes the NPP_HandleEvent
() method to pass an update event or a paint message to the plug-in. If a plug-in calls this method, it receives a paint message later. The browser redraws invalid areas of the document and windowless plug-ins at regularly timed intervals. To force a paint message, the plug-in can call NPN_ForceRedraw
() after calling this method. ...
...es the NPP_HandleEvent
() method to pass an update event or a paint message to the plug-in. If a plug-in calls this method, it receives a paint message later. The browser redraws invalid areas of the document and windowless plug-ins at regularly timed intervals. To force a paint message, the plug-in can call NPN_ForceRedraw
() after calling this method. ...
NPP - Archive of obsolete content
use to store a pointer to an internal data structure associated with the instance; this field isn't modified by the browser. ndata A private value, owned by the browser, which is used to store data associated with the instance; this value should not be modified by the plug-in. Description Gecko creates an NPP structure for each plug-in instance and passes a pointer to it to NPP_New
(). ...
...ssociated with the instance; this value should not be modified by the plug-in. Description Gecko creates an NPP structure for each plug-in instance and passes a pointer to it to NPP_New
(). This pointer--which is an opaque instance handle of a plug-in--identifies the instance on which API calls should operate. NPP contains private instance data for both the plug-in and the browser. ...
...s a pointer to it to NPP_New
(). This pointer--which is an opaque instance handle of a plug-in--identifies the instance on which API calls should operate. NPP contains private instance data for both the plug-in and the browser. The NPP_Destroy
() function informs the plug-in when the NPP instance is about to be deleted; after this call returns, the NPP pointer is no longer valid. ...
...t to NPP_New
(). This pointer--which is an opaque instance handle of a plug-in--identifies the instance on which API calls should operate. NPP contains private instance data for both the plug-in and the browser. The NPP_Destroy
() function informs the plug-in when the NPP instance is about to be deleted; after this call returns, the NPP pointer is no longer valid. ...
NPP_URLNotify - Archive of obsolete content
tifies the plug-in instance of the completion of a URL request. Syntax #include <npapi.h> void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData); Parameters The function has the following parameters: instance Pointer to the current plug-in instance. url URL of the NPN_GetURLNotify
() or NPN_PostURLNotify
() request that has completed. reason Reason code for completion of request. Values: NPRES_DONE (most common): Completed normally. NPRES_USER_BREAK: User canceled stream directly by clicking the Stop button or indirectly by some action such as deleting the instance or initiating higher-priority network operations. NPRES_NETWORK_ERR: Stream failed due to problems w...
...mpleted normally. NPRES_USER_BREAK: User canceled stream directly by clicking the Stop button or indirectly by some action such as deleting the instance or initiating higher-priority network operations. NPRES_NETWORK_ERR: Stream failed due to problems with network, disk I/O, lack of memory, or other problems. notifyData Plug-in-private value for associating a previous NPN_GetURLNotify
() or NPN_PostURLNotify
() request with a subsequent NPP_URLNotify
() call. Description The browser calls NPP_URLNotify
() after the completion of a NPN_GetURLNotify
() or NPN_PostURLNotify
() request to inform the plug-in that the request was completed and supply a reason code for the completion. The most common reason code is NPRES_DONE, indicating simply that the request completed normally. Other ...
...st completed normally. ...
...Other possible reason codes are NPRES_USER_BREAK, indicating that the request was halted due to a user action (for example, clicking the Stop button), and NPRES_NETWORK_ERR, indicating that the request could not be completed, perhaps because the URL could not be found. The parameter notifyData is the plug-in-private value passed as an argument by a previous NPN_GetURLNotify
() or NPN_PostURLNotify
() call, and can be used as an identifier for the request. See also NPN_GetURLNotify
() NPN_GetURL
() NPN_PostURLNotify
() NPN_PostURL
() ...
NPSavedData - Archive of obsolete content
ug-in instance is deleted; can be returned to the plug-in to restore the data in future instances of the plug-in. Syntax typedef struct _NPSavedData { int32 len; void* buf; } NPSavedData; Fields The data structure has the following fields: len Length in bytes of the buffer pointed to by buf; set by the plug-in. buf Pointer to a memory buffer allocated by the plug-in with NPN_MemAlloc
(). Can be any reasonable size; its contents are private to the plug-in and are not modified by the browser. Description The NPSavedData object contains a block of per-instance information that the browser saves after the instance is deleted. This information can be returned to another instance of the same plug-in if the user returns to the web page that contains it. You can use the plug-in's NPP_D...
...be any reasonable size; its contents are private to the plug-in and are not modified by the browser. Description The NPSavedData object contains a block of per-instance information that the browser saves after the instance is deleted. This information can be returned to another instance of the same plug-in if the user returns to the web page that contains it. You can use the plug-in's NPP_Destroy
() function to allocate an NPSavedData object using the NPN_MemAlloc
() function, fill in the fields, and return it to the browser as an output parameter. See Instance Destruction for a code example that shows how to use NPSavedData. If the user revisits a web page that contains a plug-in, the browser returns the NPSavedData to the new instance of the plug-in in a call to NPP_New
(). After this, the p...
...e fields, and return it to the browser as an output parameter. See Instance Destruction for a code example that shows how to use NPSavedData. ...
...return it to the browser as an output parameter. See Instance Destruction for a code example that shows how to use NPSavedData. ...
NPAPI plugin reference - Archive of obsolete content
rowser. NPByteRange Represents a particular range of bytes from a stream. NPClass NPClass is a structure that holds a set of pointers to functions that make up the behavior of an instance of an NPClass (i.e. an NPObject). NPEmbedPrint Substructure of NPPrint that contains platform-specific information used during embedded mode printing. NPEvent Represents an event passed by NPP_HandleEvent
() to a windowless plug-in. NPFullPrint Substructure of NPPrint that contains platform-specific information used during full-page mode printing. NPIdentifier NPIdentifier is an opaque type used for method and property identifiers, such as strings or integers. NPIdentifiers are unique, in that for any given string or integer, there is only one NPIdentifier. The lifetime of NPIdentifiers is contro...
... plugin thread (the thread on which the plug-in was initiated). NPN_PostURL Posts data to a URL. NPN_PostURLNotify Posts data to a URL, and receives notification of the result. NPN_ReleaseObject Decrements the reference count of the given NPObject. If the reference count reaches 0, the NPObject is deallocated by calling its deallocate function if one is provided; if one is not provided, free
() is used. NPN_ReleaseVariantValue NPN_ReleaseVariantValue
() releases the value in the given variant. NPN_ReloadPlugins Reloads all of the installed plugins. NPN_RemoveProperty Removes a property from the specified NPObject. NPN_RequestRead Requests a range of bytes from a seekable stream. This initiates a read operation; the actual data is received through subsequent calls to NPP_Writ...
... NPN_RetainObject Increments the reference count of the given NPObject. NPN_SetException A plugin can call this function to indicate that a call to one of the plugin's NPObjects generated an error. NPN_SetProperty Sets the value of a property on the specified NPObject. NPN_SetValue Implemented by browsers. ...
... NPN_RetainObject Increments the reference count of the given NPObject. NPN_SetException A plugin can call this function to indicate that a call to one of the plugin's NPObjects generated an error. NPN_SetProperty Sets the value of a property on the specified NPObject. NPN_SetValue Implemented by browsers. ...
-ms-filter - Archive of obsolete content
to use scripting to set the filter on an image. Code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/filter_s.htm <body> <p>Click the image to start the filter.</p> // Call the function. ...
... filterFrom.filters.item(0).Transition=12; imageFrom.style.visibility = "hidden"; filterTo.style.visibility = ""; filterFrom.filters.item(0).play(14); } </script> </body> Gradient progid:DXImageTransform.Microsoft.Gradient( <properties> ) where <properties> = [ <Enabled> | <EndColor> | <EndColorStr> | <G...
... width: 200px; height: 250px; top: 20px; left: 20px; background: white; visibility: hidden;"> </div> </div> <script type="text/javascript"> let filterImg = document.querySelector('#filterFrom'); filterImg.addEventListener('click', doFilter); function doFilter
() { filterFrom.filters.item(0).Apply
(); // 12 is the dissolve filter. filterFrom.filters.item(0).Transition=12; imageFrom.style.visibility = "hidden"; filterTo.style.visibility = ""; filterFrom.filters.item(0).play(14); } </script> </body> Gradient progid:DXImageTransform.Microsoft.Gradient( <properties> ) where <properties> = [ <Enabled> | <EndColor> | <EndColorStr> | <GradientType> | <StartColor> | <StartColor...
...When you use -ms-filter, enclose the progid in single quotes (') or double quotes ("). Use commas (,) to separate multiple values, as shown in the Examp...
Introduction - Archive of obsolete content
the returned value is placed in the element. For instance var a = {foo: 1}; var b = <bar>{a}</bar>; actually produces a document that reads <bar>[object Object]</bar>. ...
...ced in the element. For instance var a = {foo: 1}; var b = <bar>{a}</bar>; actually produces a document that reads <bar>[object Object]</bar>. ...
... var a = {foo: 1}; var b = <bar>{a}</bar>; actually produces a document that reads <bar>[object Object]</bar>. Use of inline functions in content Although the brackets are restricted to single statements for evaluation, one might provide an anonymous function to perform some extra processing inline: var a = 'foo'; var b = <bar>{function
() {var c = a.toUpperCase
(); var d = 5 * 5; return c + d;}
()}</bar>; where the above produces: <bar>FOO25</bar>. ...
...rocessing inline: var a = 'foo'; var b = <bar>{function
() {var c = a.toUpperCase
(); var d = 5 * 5; return c + d;}
()}</bar>; where the above produces: <bar>FOO25</bar>. See E4X for templating for more discussion on this usage. Serializing One of the most powerful tools of E4X is its ability to serialize an entire XML document (or portion thereof) into a string with one simple call to .toXMLString
() var element1 = <foo/>; var element2 = <bar/>; element1.appendChild(element2); element1.toXMLString
(); This will print <foo> <bar/> </foo> Calling toString
() will achieve the same effect in this case, though calling toString
() on an element with only text content will product the text content (e.g., <foo>abc</foo>.toString
(); will simply provide 'abc'). << PreviousNext >> ...
Enumerator.moveFirst - Archive of obsolete content
hod resets the current item in the collection to the first item. Syntax enumObj.moveFirst( ) Remarks The required enumObj reference is any Enumerator object. If there are no items in the collection, the current item is set to undefined. ...
...ems in the collection, the current item is set to undefined. ...
... the current item is set to undefined. ...
...mple In following example, the moveFirst method is used to evaluate members of the Drivescollection from the beginning of the list: function ShowDrives
() { var s = ""; var bytesPerGB = 1024 * 1024 * 1024; var fso = new ActiveXObject("Scripting.FileSystemObject"); var e = new Enumerator(fso.Drives); e.moveFirst
(); while (e.atEnd
() == false) { var drv = e.item
(); s += drv.Path + " - "; if (drv.IsReady) { var freeGB = drv.FreeSpace / bytesPerGB; var totalGB = drv.TotalSize / bytesPerGB; s += freeGB.toFixed(3) + " GB free of "; s += totalGB.toFixed(3) + " GB"; } else { s += "Not Ready"; } s += "<br />"; e.moveNext
(); ...
Enumerator - Archive of obsolete content
umerator object provides a way to access any member of a collection and behaves similarly to the For...Each statement in VBScript. ...
...ovides a way to access any member of a collection and behaves similarly to the For...Each statement in VBScript. ...
...f a collection and behaves similarly to the For...Each statement in VBScript. ...
... Methods Enumerator.atEnd Returns a Boolean value indicating if the enumerator is at the end of the collection. Enumerator.item Returns the current item in the collection. Enumerator.moveFirst Resets the current item in the collection to the first item. ...
XUL Parser in Python - Archive of obsolete content
2 platform, where the <tt>dir</tt> command it depends on gets you your XUL files. Again, you can easily use <tt>ls</tt> instead, as I should have done, and pick up some extra support. I will make these adjustments and change it into a real module when I get a second, so that someone can instantiate the parser from their own scripts and use it more flexibly: >>> import XULTool >>> myXP = XULParser
() >>> CHROME_DIR = 'D:\src\mozilla\xpfe' >>> res = myXP.parseXUL(CHROME_DIR, 'window', 'id') Where something like the above would write out all the XUL window ids in the build. Something like that, anyway. Results The results from the script are written to a file called res.html. This is another hard-coded thing I have to open up. If you want to test this script you should change the filename "...
...ated attributes. After all the XUL files in the specified directory and its subdirectories are fed to the parser and parsed (using the win32 system's <tt>dir /s /b *.xul</tt> command), the dictionary of dictionaries is sorted and written into an HTML table. The xml namespace support in xmllib was resolving the xul and html namespaces in a very annoying way, so I have an additional function, strip
(), that takes off the whole namespace that xmllib is trying to tack onto the front of each item it finds in the XML. Some modifications to this script may suggest other uses. The parser provides the tag name itself as a string and the attributes and their values in a dictionary, "a". If you want to look for certain widgets within the XUL files, you can get the filename from the calling method p.fe...
...widgets within the XUL files, you can get the filename from the calling method p.feed(data) and create a condition that only gets the elements specified in sys.argv[1]. ...
... Until I spruce it up a little, this is just a very basic demonstration of using Python's XML parser with XUL. ...
Building up a basic demo with Babylon.js - Game development
r previous code: var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3(0.8, 0.8, 0.8); Thus, the scene is created and the second line sets the background color to light gray. Creating a rendering loop To make the scene actually visible we have to render it. Add these lines at the end of the <script> element, just before the closing </script>. var renderLoop = function
() { scene.render
(); }; engine.runRenderLoop(renderLoop); We're using the engine's runRenderLoop
() method to execute the renderLoop
() function repeatedly on every frame -- the loop will continue to render indefinitely until told to stop. Creating a camera Now the setup code is in place we need to think about implementing the standard scene components: camera, light and objects. Let's start w...
...FreeCamera("camera", new BABYLON.Vector3(0, 0, -10), scene); There are many cameras available in Babylon.js; FreeCamera is the most basic and universal one. To initialize it you need to pass it three parameters: any name you want to use for it, the coordinates where you want it to be positioned in the 3D space, and the scene you want to add it to. Note: You probably noticed the BABYLON.Vector3
() method in use here -- this defines a 3D position on the scene. Babylon.js is bundled with a complete math library for handling vectors, colors, matrices etc. Let there be light There are various light sources available in Babylon.js. The most basic one is the PointLight, which works like a flashlight -- shining a spotlight in a given direction. Add the following line below your camera definiti...
...t the position of the shapes; we could also scale them. To show actual animation, we need to make changes to these values inside the rendering loop at the end of our code, so they are updated on every frame. Define a helper variable -- t -- that we will use for animations, just before the renderLoop, and decrement it on every frame inside the loop, like this: var t = 0; var renderLoop = function
() { scene.render
(); t -= 0.01; // animation code goes here }; engine.runRenderLoop(renderLoop); The t variable will be incremented on every rendered frame. Rotation Applying rotation is as easy as adding this line at the end of the renderLoop function: box.rotation.y = t*2; It will rotate the box along the y axis. Scaling Add this line below the previous one to scale the torus:...
...5; There's a little bit of adjustment made to make the animation look and feel nice. You can experiment with the values and see how it affects the animation. Moving By changing the position of the cylinder directly we can move it on the scene -- add this line below the previous one: cylinder.position.y = Math.sin(t*3); The cylinder will float up and down on the y axis thanks to the Math.sin
() function. Conclusion Here's the final code listing, along with a viewable live example: You can also see it on GitHub and fork the repository if you want to play with it yourself locally. Now you know the basics of Babylon.js engine; happy experimentation! ...
Square tilemaps implementation: Static maps - Game development
plained in the Canvas API tutorial, as well as the basic information included in our Tilemaps introduction article. The tile atlas A tilemap might use one or several atlases -- or spritesheets -- that contain all of the tile images. ...
... The tilemap data structure To store that map data, we can use a plain object or a custom class. ...
... y. The tilemap data structure To store that map data, we can use a plain object or a custom class. For the sake of simplicity, in the example code a plain object has been used. It contains the basic map properties: cols: The width of the map, in columns. rows: The height of the map, in rows. tsize: The tile size, in pixels. tiles: A 1-dimensional array containing the visual grid. getTile
(): A helper method that gets the tile index in a certain position. tiles contains the actual visual map data. We are representing the tiles with indices, assigned to the tiles dependant on their position in the atlas (e.g. 0 for the left-most tile.) However, we must account for empty tiles, since they are crucial for implementing layers -- empty tiles are usually assigned a negative index value, ...
...ft-most tile.) However, we must account for empty tiles, since they are crucial for implementing layers -- empty tiles are usually assigned a negative index value, 0, or a null value. In these examples, empty tiles will be represented by index 0, so we will shift the indices of the atlases by one (and thus the first tile of the atlas will be assigned index 1, the second index 2, etc.) The getTile
() helper method returns the tile contained at the specified column and row. If tiles were a 2D matrix, then the returned value would just be tiles[column][row]. However, it's usually more common to represent the grid with a 1-dimensional array. In this case, we need to map the column and row to an array index: var index = row * map.cols + column; Wrapping up, an example of a tilemap object could ...
The score - Game development
e Gamedev Phaser tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Phaser-Content-Kit/demos/lesson11.html. Having a score can also make the game more interesting -- you can try to beat your own highscore, or your friend's. In this article we'll add a scoring system to our game. ...
... The actual text that will be rendered. ...
... The actual text that will be rendered. The font style to render the text with. The last parameter looks very similar to CSS styling. In our case the score text will be blue, sized at 18 pixels, and use the Arial font. ...
... rendered. The font style to render the text with. The last parameter looks very similar to CSS styling. In our case the score text will be blue, sized at 18 pixels, and use the Arial font. Updating the score when bricks are destroyed We will increase the number of points every time the ball hits a brick and update the scoreText to display the current score. This can be done using the setText
() method -- add the two new lines seen below to the ballHitBrick
() function: function ballHitBrick(ball, brick) { brick.kill
(); score += 10; scoreText.setText('Points: '+score); } That's it for now -- reload your index.html and check that the score updates on every brick hit. Compare your code You can check the finished code for this lesson in the live demo below, and play with it ...
Win the game - Game development
<< PreviousNext >> This is the 12th step out of 16 of the Gamedev Phaser tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Phaser-Content-Kit/demos/lesson12.html. Implementing winning in our game is quite easy: if you happen to destroy all the bricks, then you win. ...
...t of 16 of the Gamedev Phaser tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Phaser-Content-Kit/demos/lesson12.html. Implementing winning in our game is quite easy: if you happen to destroy all the bricks, then you win. ...
...If there are no more bricks left alive, then we show a winning message, restarting the game once the alert is dismissed. ...
...If there are no more bricks left alive, then we show a winning message, restarting the game once the alert is dismissed. ...
Call stack - MDN Web Docs Glossary: Definitions of Web-related terms
ny functions that are called by that function are added to the call stack further up, and run where their calls are reached. When the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing. If the stack takes up more space than it had assigned to it, it results in a "stack overflow" error. Example function greeting
() { // [1] Some codes here sayHi
(); // [2] Some codes here } function sayHi
() { return "Hi!"; } // Invoke the `greeting` function greeting
(); // [3] Some codes here The code above would be executed like this: Ignore all functions, until it reaches the greeting
() function invocation. Add the greeting
() function to the call stack list. Call stack list: - greeting Exe...
... // [2] Some codes here } function sayHi
() { return "Hi!"; } // Invoke the `greeting` function greeting
(); // [3] Some codes here The code above would be executed like this: Ignore all functions, until it reaches the greeting
() function invocation. Add the greeting
() function to the call stack list. Call stack list: - greeting Execute all lines of code inside the greeting
() function. Get to the sayHi
() function invocation. Add the sayHi
() function to the call stack list. Call stack list: - sayHi - greeting Execute all lines of code inside the sayHi
() function, until reaches its end. Return execution to the line that invoked sayHi
() and continue executing the rest of the greeting
() function. Delete the sayHi
() function from our call stack list. ...
... Call stack list: EMPTY In summary, then, we start with an empty Call Stack. ...
... Call stack list: EMPTY In summary, then, we start with an empty Call Stack. Whenever we invoke a function, it is automatically added to the Call Stack. Once the function has executed all of its code, it is automatically removed from the Call Stack. ...
Static method - MDN Web Docs Glossary: Definitions of Web-related terms
is accessible directly from an API object's constructor, rather than from an object instance created via the constructor. In a Web API, a static method is one which is defined by an interface but can be called without instantiating an object of that type first. Methods called on object instances are called instance methods. ...
... a static method is one which is defined by an interface but can be called without instantiating an object of that type first. Methods called on object instances are called instance methods. ...
...ch is defined by an interface but can be called without instantiating an object of that type first. Methods called on object instances are called instance methods. ...
...s called on the actual Notification constructor itself -- it is a static method: let promise = Notification.requestPermission
(); The Notification.close
() method on the other hand, is an instance method -- it is called on an specific notification object instance to close the system notification it represents: let myNotification = new Notification('This is my notification'); myNotification.close
(); ...
CSS and JavaScript accessibility best practices - Learn web development
Real form validation would be much more complex than this -- you'd want to check that the entered name actually looks like a name, the entered a...
...tually a number and is realistic (e.g. nonnegative and less than 4 digits). Here we've just implemented a simple check that a value has been filled in to each input field (if(testItem.input.value === '')). When the validation has been performed, if the tests pass then the form is submitted. If there are errors (if(errorList.innerHTML !== '')) then we stop the form submitting (using preventDefault
()), and display any error messages that have been created (see below). This mechanism means that the errors will only be shown if there are errors, which is better for usability. For each input that doesn't have a value filled in when the form is submitted, we create a list item with a link and insert it in the errorList. function createLink(testItem) { const listItem = document.createElement('...
...when the form is submitted, we create a list item with a link and insert it in the errorList. function createLink(testItem) { const listItem = document.createElement('li'); const anchor = document.createElement('a'); anchor.textContent = testItem.input.name + ' field is empty: fill in your ' + testItem.input.name + '.'; anchor.href = '#' + testItem.input.name; anchor.onclick = function
() { testItem.input.focus
(); }; listItem.appendChild(anchor); errorList.appendChild(listItem); } Each link serves a dual purpose -- it tells you what the error is, plus you can click on it/activate it to jump straight to the input element in question and correct your entry. Note: The focus
() part of this example is a bit tricky. Chrome and Edge (and newer versions of IE) will focus the ...
... errorList.appendChild(listItem); } Each link serves a dual purpose -- it tells you what the error is, plus you can click on it/activate it to jump straight to the input element in question and correct your entry. Note: The focus
() part of this example is a bit tricky. Chrome and Edge (and newer versions of IE) will focus the element when the link is clicked, without needing the onclick/focus
() block. Safari will only highlight the form element with the link on its own, so needs the onclick/focus
() block to actually focus it. Firefox doesn't focus the inputs properly at all in this context, so Firefox users can't take advantage of this at present (although everything else works fine). The Firefox issue should be fixed soon -- work is being done to give Firefox behaviour parity with othe...
Grids - Learn web development
It might be better to have tracks that are at least 100 pixels tall and can still expand if more content gets into them. A fairly basic fact about the web is that you never really know how tall something is going to be; additional c...
..., in which case it would cause an overflow. It might be better to have tracks that are at least 100 pixels tall and can still expand if more content gets into them. A fairly basic fact about the web is that you never really know how tall something is going to be; additional content or larger font sizes can cause problems with designs that attempt to be pixel perfect in every dimension. The minmax
() function lets us set a minimum and maximum size for a track, for example minmax(100px, auto). The minimum size is 100 pixels, but the maximum is auto, which will expand to fit the content. Try changing grid-auto-rows to use a minmax value: .container { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-rows: minmax(100px, auto); grid-gap: 20px; } If you add extra co...
....container { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-rows: minmax(100px, auto); grid-gap: 20px; } If you add extra content you will see that the track expands to allow it to fit. Note that the expansion happens right along the row. ...
...low it to fit. Note that the expansion happens right along the row. As many columns as will fit We can combine some of the things we have learned about track listing, repeat notation and minmax
() to create a useful pattern. Sometimes it is helpful to be able to ask grid to create as many columns as will fit into the container. We do this by setting the value of grid-template-columns using repeat
() notation, but instead of passing in a number, pass in the keyword auto-fill. For the second parameter of the function we use minmax
(), with a minimum value equal to the minimum track size that we would like to have, and a maximum of 1fr. Try this in your file now, using the below CSS: As many columns as will fit body { width: 90%; max-width: 900px; margin: 2em auto; font: .9em/1.2 Ar...
Sending form data - Learn web development
n you have installed). Example: Python This example shows how you would use Python to do the same thing -- display the submitted data on a web page. This uses the Flask framework for rendering the templates, handling the form data submission, etc. (see python-example.py). ...
... thing -- display the submitted data on a web page. This uses the Flask framework for rendering the templates, handling the form data submission, etc. (see python-example.py). ...
...ubmission, etc. (see python-example.py). from flask import Flask, render_template, request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def form
(): return render_template('form.html') @app.route('/hello', methods=['GET', 'POST']) def hello
(): return render_template('greeting.html', say=request.form['say'], to=request.form['to']) if __name__ == "__main__": app.run
() The two templates referenced in the above code are as follows (these need to be in a subdirectory called templates in the same directory as the python-example.py file, if you try to run the example yourself): form.html: The same form as we saw above in the The POST method section but with the action set to {{ url_for('hello') }}. This is a Jinja2 template, which is basically HTML but can cont...
...l_for('hello') }}. This is a Jinja2 template, which is basically HTML but can contain calls to the Python code that is running the web server contained in curly braces. url_for('hello') is basically saying "redirect to /hello when the form is submitted". greeting.html: This template just contains a line that renders the two bits of data passed to it when it is rendered. This is done via the hello
() function seen above, which runs when the /hello URL is navigated to. Note: Again, this code won't work if you just try to load it into a browser directly. Python works a bit differently to PHP -- to run this code locally you'll need to install Python/PIP, then install Flask using pip3 install flask. At this point you should be able to run the example using python3 python-example.py, then navig...
Using data attributes - Learn web development
HTML syntax The syntax is simple. Any attribute on any element whose attribute name starts with data- is a data attribute. ...
... attribute. Say you have an article and you want to store some extra information that doesn't have any visual representation. Just use data attributes for that: <article id="electric-cars" data-columns="3" data-index-number="12314" data-parent="cars"> ... </article> JavaScript access Reading the values of these attributes out in JavaScript is also very simple. You could use getAttribute
() with their full HTML name to read them, but the standard defines a simpler way: a DOMStringMap you can read out via a dataset property. To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). const article = document.querySelector('#electric-cars'); article.dataset.columns // "3" article.d...
...ber // "12314" article.dataset.parent // "cars" Each property is a string and can be read and written. In the above case setting article.dataset.columns = 5 would change that attribute to "5". CSS access Note that, as data attributes are plain HTML attributes, you can even access them from CSS. For example to show the parent data on the article you can use generated content in CSS with the attr
() function: article::before { content: attr(data-parent); } You can also use the attribute selectors in CSS to change styles according to the data: article[data-columns='3'] { width: 400px; } article[data-columns='4'] { width: 600px; } You can see all this working together in this JSBin example. Data attributes can also be stored to contain information that is constantly changing, like s...
... in data attributes, because assistive technology may not access them. In addition, search crawlers may not index data attributes' values. The main issues to consider are Internet Explorer support and performance. Internet Explorer 11+ provides support for the standard, but all earlier versions do not support dataset. To support IE 10 and under you need to access data attributes with getAttribute
() instead. Also, the performance of reading data-attributes compared to storing this data in a regular JS object is poor. That said, though, for custom element-associated metadata, they are a great solution. In Firefox 49.0.2 (and perhaps earlier/later versions), the data attributes that exceed 1022 characters will not be read by Javascript (EcmaScript 4). ...
Basic math in JavaScript — numbers and operators - Learn web development
umbers. We don't cover these in detail in this article because we wanted to keep it as a simple introduction and only cover the real basic essentials for now; however, once you've read through this module a couple of times it is worth going to the object reference pages and learning more about what's available. For example, to round your number to a fixed number of decimal places, use the toFixed
() method. Type the following lines into your browser's console: let lotsOfDecimal = 1.766584958675746364; lotsOfDecimal; let twoDecimalPlaces = lotsOfDecimal.toFixed(2); twoDecimalPlaces; Converting to number data types Sometimes you might end up with a number that is stored as a string type, which makes it difficult to perform calculations with it. This most commonly happens when data is entere...
...ecimalPlaces = lotsOfDecimal.toFixed(2); twoDecimalPlaces; Converting to number data types Sometimes you might end up with a number that is stored as a string type, which makes it difficult to perform calculations with it. This most commonly happens when data is entered into a form input, and the input type is text. There is a way to solve this problem -- passing the string value into the Number
() constructor to return a number version of the same value. For example, try typing these lines into your console: let myNumber = '74'; myNumber + 3; You end up with the result 743, not 77, because myNumber is actually defined as a string. You can test this by typing in the following: typeof myNumber; To fix the calculation, you can do this: Number(myNumber) + 3; Arithmetic operators Arithm...
... ** Exponent Raises a base number to the exponent power, that is, the base number multiplied by itself, exponent times. It was first Introduced in EcmaScript 2016. 5 ** 2 (returns 25, which is the same as 5 * 5). Note: You'll sometimes see numbers involved in arithmetic referred to as operands. Note: You may sometimes see exponents expressed using the older Math.pow
() method, which works in a very similar way. For example, in Math.pow(7, 3), 7 is the base and 3 is the exponent, so the result of the expression is 343. Math.pow(7, 3) is equivalent to 7**3. We probably don't need to teach you how to do basic math, but we would like to test your understanding of the syntax involved. Try entering the examples below into your developer tools JavaScript console to ...
...r out depending on what zoom level is selected We'll look at how to code such logic when we look at conditional statements in a future article. For now, let's look at a quick example: <button>Start machine</button> <p>The machine is stopped.</p> const btn = document.querySelector('button'); const txt = document.querySelector('p'); btn.addEventListener('click', updateBtn); function updateBtn
() { if (btn.textContent === 'Start machine') { btn.textContent = 'Stop machine'; txt.textContent = 'The machine has started!'; } else { btn.textContent = 'Start machine'; txt.textContent = 'The machine is stopped.'; } } Open in new window You can see the equality operator being used just inside the updateBtn
() function. In this case, we are not testing if two mathematical ...
Handling text — strings in JavaScript - Learn web development
one + 'I am fine -- ' + two; response; Note: When you enter an actual string in your code, enclosed in single or double quotes, it is called a string literal. ...
...t is called a string literal. Concatenation in context Let's have a look at concatenation being used in action -- here's an example from earlier in the course: <button>Press me</button> const button = document.querySelector('button'); button.onclick = function
() { let name = prompt('What is your name?'); alert('Hello ' + name + ', nice to see you!'); } Here we're using a window.prompt
() function in line 4, which asks the user to answer a question via a popup dialog box then stores the text they enter inside a given variable -- in this case name. We then use a window.alert
() function in line 5 to display another popup containing a string we've assembled from two string literals and the name variable, via concatenation. Numbers vs. strings So what happens when we try to add (o...
...nvert to a string but not change otherwise, or a string variable that you want to convert to a number but not change otherwise, you can use the following two constructs: The Number object converts anything passed to it into a number, if it can. ...
...not change otherwise, you can use the following two constructs: The Number object converts anything passed to it into a number, if it can. Try the following: let myString = '123'; let myNum = Number(myString); typeof myNum; Conversely, every number has a method called toString
() that converts it to the equivalent string. Try this: let myNum = 123; let myString = myNum.toString
(); typeof myString; These constructs can be really useful in some situations. For example, if a user enters a number into a form's text field, it's a string. However, if you want to add this number to something, you'll need it to be a number, so you could pass it through Number
() to handle this. We did exactly this in our Number Guessing Game, in line 54. Template literals Another type ...
Test your skills: Object basics - Learn web development
n your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). Object basics 1 In this task you are provided with an object literal, and your tasks are to Store the value of the name property inside the catName variable, using bracket notation. Run the greeting
() method using dot notation (it will log the greeting to the browser DevTools' console). Update the color property value to black. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Object basics 2 In our next task, we want you to have a go at creating your own object literal to re...
...ears active, and style, and the title and release date of their first album. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Object basics 3 Finally for our object basics assessment, we want you to return to the cat object literal from Task #1. ...
... The code is not very DRY (each bit of code should only be defined once) -- you've got the same method defined twice, for example. ...
... The code is not very DRY (each bit of code should only be defined once) -- you've got the same method defined twice, for example. ...
Rendering a list of Vue components - Learn web development
o items. While we'll eventually add a mechanism to add new todo items, we can start with some mock to do items. Each to-do item will be represented by an object with a name and a done property. Add a few sample to-do items, along the lines of those seen below. This way you have some data available for rendering using v-for. export default { name: 'app', components: { ToDoItem }, data
() { return { ToDoItems: [ { label: 'Learn Vue', done: false }, { label: 'Create a Vue project with the CLI', done: true }, { label: 'Have fun', done: true }, { label: 'Create a to-do list', done: false } ] }; } }; Now that we have a list of items, we can use the v-for directive to display them. Directives are applied to elements like other attr...
...ist elements appropriately, it needs a unique "key" on the same element that you attach v-for to. To make sure that Vue can accurately compare the key attributes, they need to be string or numeric values. While it would be great to use the name field, this field will eventually be controlled by user input, which means we can't guarantee that the names would be unique. We could use lodash.uniqueid
(), however, like we did in the previous article. Import lodash.uniqueid into your App component in the same way you did with your ToDoItem component, using import uniqueId from 'lodash.uniqueid'; Next, add an id field to each element in your ToDoItems array, and assign each of them a value of uniqueId('todo-'). Your App.vue <script> element contents should now look like this: ...
... import uniqueId from 'lodash.uniqueid'; Next, add an id field to each element in your ToDoItems array, and assign each of them a value of uniqueId('todo-'). ...
... using uniqueId, so you need to remove the import uniqueId from 'lodash.uniqueid'; line, otherwise your app will throw an error. The <script> contents in your ToDoItem component should now look something like this: export default { props: { label: {required: true, type: String}, done: {default: false, type: Boolean}, id: {required: true, type: String} }, data
() { return { isDone : this.done, } }, } Now, over in your App.vue component, pass item.id as a prop to the ToDoItem component. Your App.vue template should now look like this: <template> <div id="app"> <h1>My To-Do List</h1> <ul> <li v-for="item in ToDoItems" :key="item.id"> <to-do-item :label="item.label" :done="item.done" :id="item.id"></to...
Creating a Login Manager storage module
vaScript implementation The following code snippet is a JavaScript component that implements a dummy nsILoginManagerStorage interface. See How_to_Build_an_XPCOM_Component_in_Javascript for more details about JavaScript components. ...
...8c-747a-4f6d-ac63-2d2998e5a5c1}"), QueryInterface: XPCOMUtils.generateQI([Ci.nsILoginManagerStorage]), // This registers the category for overriding the built-in nsILoginManagerStorage _xpcom_categories: [ { category: "login-manager-storage", entry: "nsILoginManagerStorage" } ], // Console logging service, used for debugging. __logService : null, get _logService
() { if (!this.__logService) this.__logService = Cc["@mozilla.org/consoleservice;1"]. getService(Ci.nsIConsoleService); return this.__logService; }, log: function (message) { dump("SampleLoginManager: " + message + "\n"); this._logService.logStringMessage("SampleLoginManager: " + message); }, // Logs function name and arguments for debugging ...
...oginManager: " + message + "\n"); this._logService.logStringMessage("SampleLoginManager: " + message); }, // Logs function name and arguments for debugging stub: function(arguments) { var args = []; for (let i = 0; i < arguments.length; i++) args.push(arguments[i]) this.log("Called " + arguments.callee.name + "(" + args.join(",") + ")"); }, init: function SLMS_init
() { this.stub(arguments); }, initWithFile: function SLMS_initWithFile(aInputFile, aOutputFile) { this.stub(arguments); }, addLogin: function SLMS_addLogin(login) { this.stub(arguments); }, removeLogin: function SLMS_removeLogin(login) { this.stub(arguments); }, modifyLogin: function SLMS_modifyLogin(oldLogin, newLogin) { this.stub(arguments); }, getAllLogins:...
...b(arguments); }, addLogin: function SLMS_addLogin(login) { this.stub(arguments); }, removeLogin: function SLMS_removeLogin(login) { this.stub(arguments); }, modifyLogin: function SLMS_modifyLogin(oldLogin, newLogin) { this.stub(arguments); }, getAllLogins: function SLMS_getAllLogins(count) { this.stub(arguments); }, removeAllLogins: function SLMS_removeAllLogins
() { this.stub(arguments); }, getAllDisabledHosts: function SLMS_getAllDisabledHosts(count) { this.stub(arguments); }, getLoginSavingEnabled: function SLMS_getLoginSavingEnabled(hostname) { this.stub(arguments); }, setLoginSavingEnabled: function SLMS_setLoginSavingEnabled(hostname, enabled) { this.stub(arguments); }, findLogins: function SLMS_findLogins(count, hostna...
Experimental features in Firefox
element whose contenteditable attribute is enabled--immediately before the element's value changes. Release channel Version added Enabled by default? Nightly 74 No Developer Edition 74 No Beta 74 No Release 74 No Preference name dom.input_events.beforeinput.enabled HTMLMediaElement method: setSinkId
() HTMLMediaElement.setSinkId
() allows you to set the sink ID of an audio output device on an HTMLMediaElement, thereby changing where the audio is being output. See bug 934425 for more details. Release channel Version added Enabled by default? Nightly 64 No Developer Edition 64 No Beta 64 No Release 64 No Pref...
... and disallowed (autoplay is not allowed at this time). See bug 1506289 for more details. Release channel Version added Enabled by default? Nightly 66 No Developer Edition 66 No Beta 66 No Release 66 No Preference name dom.media.autoplay.autoplay-policy-api GeometryUtils methods: convertPointFromNode
(), convertRectFromNode
(), and convertQuadFromNode
() The GeometryUtils methods convertPointFromNode
(), convertRectFromNode
(), and convertQuadFromNode
() map the given point, rectangle, or quadruple from the Node on which they're called to another node. See bug 918189 for more details. Release channel Version added Enabled by default? Nightly 31 Yes Develop...
...ngle, or quadruple from the Node on which they're called to another node. See bug 918189 for more details. Release channel Version added Enabled by default? Nightly 31 Yes Developer Edition 31 No Beta 31 No Release 31 No Preference name layout.css.getBoxQuads.enabled GeometryUtils method: getBoxQuads
() The GeometryUtils method getBoxQuads
() returns the CSS boxes for a Node relative to any other node or viewport. See bug 917755 for more details. Release channel Version added Enabled by default? Nightly 31 Yes Developer Edition 31 No Beta 31 No Release 31 No Preference name layout.css.convertFromNode.enab...
... metadata. See bug 1112032 for more details. Release channel Version added Enabled by default? Nightly 71 Yes Developer Edition 71 No Beta 71 No Release 71 No Preference name dom.media.mediasession.enabled Asynchronous SourceBuffer add and remove This adds the promise-based methods appendBufferAsync
() and removeAsync
() for adding and removing media source buffers to the SourceBuffer interface. See bug 1280613 and bug 778617 for more information. Release channel Version added Enabled by default? Nightly 62 No Developer Edition 62 No Beta 62 No Release 62 No Preference name media.mediasource.experimental.
Process scripts
e 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 the content process. But if you register it in a frame script, and the frame script is loade...
...bserver notifications must be registered in the content process, but if you do this in a frame script, and the frame script is loaded more than once, then you will get multiple notifications for that event. The solution in these cases is to use a process script instead of a frame script. You can load a process script by accessing a parent process message manager and calling its loadProcessScript
() function. The following code uses the global parent process message manager, which will load the script into the the chrome process and any child processes: // chrome code let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIProcessScriptLoader); ppmm.loadProcessScript("chrome://whatever/process-script.js", true); ppmm.addMessageListener("Hello", function(msg) { ... })...
...If you do, you must call removeDela...
...("Hello"); In this example, the dump
() statement will run once in each content process as well as in the main process. This example also figures out whether it is running in the chrome or in a content process by looking at the process type in Services.appinfo. In just about every respect, using process scripts is like using frame scripts: you can pass the allowDelayedLoad to loadProcessScript
(). If you do, you must call removeDelayedProcessScript
() when your extension is disabled or removed the message-passing APIs are the same: sendAsyncMessage
() is available in both directions, while sendSyncMessage
() is available from content to chrome only process scripts are system-privileged, and have access to the Components object. However, process scripts are subject to the same kinds of limi...
Implementing QueryInterface
This document describes the right way to write QueryInterface
(). A reference implementation of QueryInterface NS_IMETHODIMP nsMyImplementation::QueryInterface( REFNSIID aIID, void** aInstancePtr ) { NS_ASSERTION(aInstancePtr, "QueryInterface requires a non-NULL destination!"); // It's a logic error, not a runtime error, to call me without any place to put my answer! // ...but that won't matter when someone calls me wrongly in a non-debug build. if ( !aInstancePtr ) return NS_ERROR_NULL_POINTER; nsISupports* foundInterface; if ( aIID.Equals(nsCOMTypeInfo<nsIX>::GetIID
()) ) foundInterface = NS_STATIC_CAST(nsIX*, this); else if ( aIID.Equals(nsCOMTypeInfo<nsIY>::GetIID
()) ) foundInterface = NS_STATIC_CAST(nsIY*, this); // .
...nstancePtr ) return NS_ERROR_NULL_POINTER; nsISupports* foundInterface; if ( aIID.Equals(nsCOMTypeInfo<nsIX>::GetIID
()) ) foundInterface = NS_STATIC_CAST(nsIX*, this); else if ( aIID.Equals(nsCOMTypeInfo<nsIY>::GetIID
()) ) foundInterface = NS_STATIC_CAST(nsIY*, this); // ...as many cases as needed... ...
...'s So Good About It? It's clear and simple. OK. It has more than one return, but the primary return is at the end of the function as expected; and the additional return is clear and alone at the top of the function. It only has one AddRef. It AddRefs the resulting interface, not this, thus following the COM-correct way (particularly important in aggregation) It uses nsCOMTypeInfo<T>::GetIID
() instead of kTIID thus saving a global declaration and global space It uses C 's static_cast, via NS_STATIC_CAST, which detects errors when you can't really get to the desired interface. It avoids repeated uses of and assignments to *aInstancePtr, which compilers have trouble optimizing. It clears the result, *aInstancePtr, when returning an error. It generates less code than the typical imple...
...REFNSIID aIID, void** aInstancePtr ) /* I just add the interfaces |nsIX| and |nsIY|. My base class |nsBaseImplementation| provides all the rest. */ { NS_ASSERTION(aInstancePtr, "QueryInterface requires a non-NULL destination!"); if ( !aInstancePtr ) return NS_ERROR_NULL_POINTER; nsISupports* foundInterface; if ( aIID.Equals(nsCOMTypeInfo<nsIX>::GetIID
()) ) foundInterface = NS_STATIC_CAST(nsIX*, this); else if ( aIID.Equals(nsCOMTypeInfo<nsIY>::GetIID
()) ) foundInterface = NS_STATIC_CAST(nsIY*, this); // Note: Don't check for |nsISupports|; |nsBaseImplementation| will do that for me. else foundInterface = 0; nsresult status; if ( !foundInterface ) // OK, _I_ didn't find an interface. Maybe my base ...
AddonInstall
An AddonInstall instance tracks download and installation process of an add-on. Instances can be created using the getInstallForFile
() or getInstallForURL
() methods on the AddonManager. Once you have an instance the install
() method is used to start automatic download and installation. This can be canceled at any time with the cancel
() method. Method Overview void install
() void cancel
() void addListener(in InstallListener listener) void removeListener(in InstallListener listener) Properties Attribute Type Description name string The name of the add-on being installed. version string The version of the add-on being installed. iconURL string The icon of the add-on being installed. ...
...s the simple display name of the signer. existingAddon Addon The Addon that this install will update. May be null if it isn't updating anything installed. This is guaranteed to be correct after downloading is complete but may be set earlier. addon Addon The full Addon that this install will install. Only available after downloading is complete. ...
...ding is complete but may be set earlier. addon Addon The full Addon that this install will install. Only available after downloading is complete. Methods install
() Starts or continues the install process. The process will continue in the background until it fails, completes, one of the registered InstallListeners pauses it, or the process is canceled by a call to the cancel
() method. void install( ) cancel
() Cancels the install process, it cannot be restarted after this. ...
...fter downloading is complete. Methods install
() Starts or continues the install process. The process will continue in the background until it fails, completes, one of the registered InstallListeners pauses it, or the process is canceled by a call to the cancel
() method. void install( ) cancel
() Cancels the install process, it cannot be restarted after this. void cancel( ) addListener
() Adds a new InstallListener if the listener is not already registered to monitor this specific AddonInstall. void addListener( in InstallListener listener ) Parameters listener The InstallListener to add. removeListener
() Removes an InstallListener if the listener is registered for monitoring this specific AddonInstall. void removeListener( in InstallListener listener ) Parameters ...
AddonUpdateChecker
The AddonUpdateChecker is used to download and parse update information for an add-on's update manifest. If all you care about is finding the newest version for an Addon then you probably want to use findUpdates
() instead. To import the AddonUpdateChecker, use: Components.utils.import("resource://gre/modules/AddonUpdateChecker.jsm"); Method Overview UpdateInfo getCompatibilityUpdate(in UpdateInfo updates[], in string version, in boolean ignoreCompatibility, in string appVersion, in string platformVersion) UpdateInfo getNewestCompatibleUpdate(in UpdateInfo updates[], in string appVersion, in string platformVersion) void checkForUpdates(in string id, in string type, in string updateKey, string URL, in UpdateCheckListener listener) Constants Con...
... ERROR_DOWNLOAD_ERROR There was an error while downloading the update information. ERROR_PARSE_ERROR The update information was malformed in some way. ERROR_UNKNOWN_FORMAT The update information was not in any known format. ERROR_SECURITY_ERROR The update information was not signed by the update key used for retrieval. Methods getCompatibilityUpdate
() Retrieves the best matching compatibility update for the application from a list of available update objects. UpdateInfo getCompatibilityUpdate( in UpdateInfo updates[], in string version, in boolean ignoreCompatibility, in string appVersion, in string platformVersion ) Parameters updates An array of update objects version The version of the add-on to get new compatibility info...
... UpdateInfo getNewestCompatibleUpdate( in UpdateInfo updates[], in string appVersion, in string platformVersion ) Parameters updates An array of update objects appVersion The version of the application or null to use the current version platformVersion The version of the platform or null to use the current version ...
...est available update from a list of update objects. UpdateInfo getNewestCompatibleUpdate( in UpdateInfo updates[], in string appVersion, in string platformVersion ) Parameters updates An array of update objects appVersion The version of the application or null to use the current version platformVersion The version of the platform or null to use the current version checkForUpdates
() Starts an update check. void checkForUpdates( in string id, in string type, in string updateKey, string URL, in UpdateCheckListener listener ) Parameters id The ID of the add-on being checked for updates type The type of add-on being checked for updates updateKey An optional update key for the add-on URL The URL of the add-on's update manifest listener An observer to noti...
UpdateListener
An UpdateListener receives messages from an update check for a single add-on, though it is possible to pass the same UpdateListener to as many calls to findUpdates
() as you like. For each individual update check, the following methods will be called on the listener: Either onCompatibilityUpdateAvailable
() or onNoCompatibilityUpdateAvailable
(), depending on whether compatibility information for the requested application version was seen. Either onUpdateAvailable
() or onNoUpdateAvailable
(), depending on whether a newer version of the Addon was found. onUpdateFinished
() to signal that the update check has completed. Method Overview void onCompatibilityUpdateAvailable(in Addon addon) void onNoCompatibilityUpdateAvailable(in Addon addon) void onUpdateAvailable(...
...e check has completed. ...
...inished(in Addon addon, in integer error) Methods onCompatibilityUpdateAvailable
() Called when the update check found compatibility information for the application and platform version that the update check was being performed for. void onCompatibilityUpdateAvailable( in Addon addon ) Parameters addon The Addon that was being checked for updates onNoCompatibilityUpdateAvailable
() Called when the update check found no new compatibility information for the application and platform version that the update check was being performed for. void onNoCompatibilityUpdateAvailable( in Addon addon ) Parameters addon The Addon that was being checked for updates onUpdateAvailable
() Called when a new version of an add-on has been found for install. void onUpdateAvailable( ...
...dateAvailable( in Addon addon ) Parameters addon The Addon that was being checked for updates onUpdateAvailable
() Called when a new version of an add-on has been found for install. void onUpdateAvailable( in Addon addon, in AddonInstall install ) Parameters addon The Addon that was being checked for updates install An AddonInstall for the updated version onNoUpdateAvailable
() Called when no new version of an add-on has been found for install. void onNoUpdateAvailable( in Addon addon ) Parameters addon The Addon that was being checked for updates onUpdateFinished
() Called when the update check is complete. void onUpdateFinished( in Addon addon, in integer error ) Parameters addon The Addon that was being checked for updates error Any error from ...
DownloadSummary
Method overview Promise bindToList(DownloadList aList); Promise addView(Object aView); Promise removeView(Object aView); Properties Attribute Type Description allHaveStopped Read only boolean Indicates whether all the downloads are currently stopped. ...
...ently transferred is reported as part of this property. This is zero if no downloads are currently in progress. progressCurrentBytes Read only number Number of bytes currently transferred as part of all the downloads that are currently in progress. This is zero if no downloads are currently in progress. Methods bindToList
() This method may be called once to bind this object to a DownloadList. Views on the summarized data can be registered before this object is bound to an actual list. This allows the summary to be used without requiring the initialization of the DownloadList first. Note: This method is already called internally by the Downloads.getSummary
() function. Promise bindToList( DownloadList aList ); P...
...The newly added view will receive an initial onSummaryChanged notification. Promise addView( Object aView ); Parameters aView The view object to add. ...
...an initial onSummaryChanged notification. Promise addView( Object aView ); Parameters aView The view object to add. The following methods may be defined: onSummaryChanged: Optional Called after any property of the summary has changed. Promise resolves to undefined when the view has been registered and the onSummaryChanged notification has been sent. removeView
() Removes a view that was previously added using addView
(). Promise removeView( Object aView ); Parameters aView The view object to remove. Promise resolves to undefined when the view has been removed. At this point, the removed view will not receive any more notifications. ...
WebRequest.jsm
ent-specific documentation for details. In particular, "blocking" may be passed to several event types, and will make the event dispatch synchronous, so the browser will wait for the event listener to return before continuing with the request. This then enables the event listener to modify or cancel the request. See Modifying & canceling requests. Some examples of using addListener
(). To remove a listener for an event, call removeListener on the event in question, passing it the listener to remove. Filtering The filter argument is the second argument to addListener
(). If you don't pass filter, then the listener is invoked for every web request the browser makes that triggers that particular event. filter is an object that may contain up to two properties: urls and types. ...
... request depends on the stage at which you have intercepted the request: that is, the WebRequest event that your listener is attached to. For example, it obviously doesn't make sense to cancel a network request after it has completed. The general approach to modifying and canceling requests is this: first, pass an array containing the string "blocking" as the third argument to your addListener
() call. This tells the browser to wait for your event listener to return before continuing with the request. next, return an object from the listener that contains instructions for what the browser should do with this request. There are four things you can do with a request: cancel it redirect it modify request headers modify response headers. To perform one of these operations, include ...
...Array of HTTP headers. See some examples of canceling, redirecting, and modifying request headers. Events The events exported by WebRequest.jsm are triggered at the various stages of making a request. This section describes the stage corresponding to each event. It also documents two data structures that vary from one event to another: the opt_extraInfoSpec argument to addListener
() the properties of the argument passed to the listener. onBeforeRequest This event is triggered when a request is about to be made, and before headers are available. This is a good place to listen if you want to cancel the request. opt_extraInfoSpec values Name Description "blocking" Make the browser wait until the listener returns. Use this if you want to cancel ...
.... We're working on addressing them, though. filtering by windowId and tabId is not supported. the onAuthRequired, onBeforeRedirect, and onErrorOccurred events are not supported. the "requestBody" instruction in opt_extraInfoSpec is not supported. redirection is not allowed in onBeforeRequest or onHeadersReceived, but is allowed in onBeforeSendHeaders. See bug 1176092. handlerBehaviorChanged
() is not supported. requestId is not included in the argument passed to the listener. Examples Basic examples This example just logs the URL for every request initiated: let {WebRequest} = Cu.import("resource://gre/modules/WebRequest.jsm", {}); WebRequest.onBeforeRequest.addListener(logURL); function logURL(e) { console.log("Loading: " + e.url); } Filtering This example logs URLs for re...
Mozilla Web Developer FAQ
such as document.all and document.layers are not part of the W3C DOM and are not supported in Mozilla. (There is partial undetectable support for document.all, though, in newer versions of Mozilla. However, that functionality only exists for compatibility with sites authored specifically for IE. You should not rely on Mozilla's document.all support on new pages.) The method document.getElementById
() can be used instead. In the Standards mode Mozilla does not generate implicit top-level JavaScript variable bindings for elements with the id or name attribute. The correct way to access an element by id is to call the document.getElementById
() method with the id as a string as the argument. Also, old client sniffers can shut out new browsers. The point of having a common API (the W3C DOM) is i...
...od with the id as a string as the argument. Also, old client sniffers can shut out new browsers. The point of having a common API (the W3C DOM) is interoperability, and checking for a particular browser defeats that purpose. When working with the DOM, it is better to check for the existence of the methods and objects you are planning on using. For example, the existence of document.getElementById
() can be checked as follows: if(document.getElementById) { /* code that uses document.getElementById
() */ } Why doesn't Mozilla display my alt tooltips? Contrary to a popular belief stemming from the behavior of a couple browsers running on the Windows platform, alt isn't an abbreviation for 'tooltip' but for 'alternative'. The value of the alt attribute is a textual replacement for the imag...
...ing XML processors are not required to support externally defined character entities (other than the five pre-defined ones), the use of externally defined character entities (other than the five pre-defined ones) is inherently unsafe in XML documents intended for the Web. The best practice is to use straight UTF-8 instead of entities. (Numeric character references are safe, too.) document.write
() is not supported. The stream that is going into the parser can't be tampered with in mid-parse. Things that look like XML comments are treated as XML comments--even inside script or style elements. Elements need to be in the XHTML namespace in order to be treated as XHTML elements. meta tags are not examined for character encoding information. tbody, head, body, and html are not infer...
...ally. The layout mode is the (Full) Standards Mode regardless of doctype. CSS works according to the XML+CSS rules. HTML-specific CSS exceptions do not apply. For example, the body element gets no special treatment. CSS selectors are case-sensitive. The DOM is in the XML mode. Namespace-aware variants of methods need to be used when working with elements (eg. createElementNS
() instead of createElement
()). Element and attribute names are not normalized to upper case. Other namespaces are supported. MathML SVG (in SVG-enabled builds only) XUL (Please note that XUL is Mozilla-specific and, therefore, using it on the public Web causes interoperabilty problems.) xml:base is observed when following links. Style sheets can be references using proce...
DMD
XULElement::Create(nsXULPrototypeElement*, nsIDocument*, bool, bool,mozilla::dom::Element**) (/home/njn/moz/mi5/dom/xul/nsXULElement.cpp:287) #06: nsXBLContentSink::CreateElement(char16_t const**, unsigned int, mozilla::dom::NodeInfo*, unsigned int, nsIContent**, bool*, mozilla::dom::FromParser) (/home/njn/moz/mi5/dom/xbl/nsXBLContentSink.cpp:874) #07: nsCOMPtr<nsIContent>::StartAssignment
() (/home/njn/moz/mi5/go64dmd/dom/xml/../../dist/include/nsCOMPtr.h:753) #08: nsXMLContentSink::HandleStartElement(char16_t const*, char16_t const**, unsigned int, unsigned int, bool) (/home/njn/moz/mi5/dom/xml/nsXMLContentSink.cpp:1007) } } It tells you that there were 150 heap blocks that were allocated from the program point indicated by the "Allocated at" stack trace, that these blocks to...
...In this case it was the cycle collector's reporter. By default, DMD does not record an allocation stack trace for most blocks, to make it run faster. The decision on whether to record is done proba...
...home/njn/moz/mi5/dom/base/nsAttrAndChildArray.cpp:880) #04: mozilla::dom::FragmentOrElement::SizeOfExcludingThis(unsigned long (*)(void const*)) const (/home/njn/moz/mi5/dom/base/FragmentOrElement.cpp:2337) #05: nsINode::SizeOfIncludingThis(unsigned long (*)(void const*)) const (/home/njn/moz/mi5/go64dmd/parser/html/../../../dom/base/nsINode.h:307) #06: mozilla::dom::NodeInfo::NodeType
() const (/home/njn/moz/mi5/go64dmd/dom/base/../../dist/include/mozilla/dom/NodeInfo.h:127) #07: nsHTMLDocument::DocAddSizeOfExcludingThis(nsWindowSizes*) const (/home/njn/moz/mi5/dom/html/nsHTMLDocument.cpp:3710) #08: nsIDocument::DocAddSizeOfIncludingThis(nsWindowSizes*) const (/home/njn/moz/mi5/dom/base/nsDocument.cpp:12820) } } The choice of whether to record an allocation stack trace...
...t you'll have less context. Or you can choose a larger number, in which cases allocations will be split across more records, but you will have more context. There is no single best value, but values in the range 2..10 are often good. The maximum is 24. -a / --ignore-alloc-frames. Many allocation stack traces start with multiple frames that mention allocation wrapper functions, e.g. js_calloc
() calls replace_calloc
(). This option filters these out. It often helps improve the quality of the output when using a small --max-frames value. -s / --sort-by. This controls how records are sorted. Acceptable values are usable (the default), req, slop and num-blocks. --clamp-contents. For a heap scan log, this performs a conservative pointer analysis on the contents of each block, changin...
A brief guide to Mozilla preferences
on on editing preferences. What is a preference? A preference is any value or defined behavior that can be set (presumably, one setting is preferable to another). Preference changes via user interface usually take effect immediately. The values are saved to the user profile (in prefs.js), for both Firefox and Thunderbird. A preference is read from a file, and can call up to four methods: pref
(), user_pref
(), sticky_pref
() and lockPref
(). All preferences files may call pref
(), user_pref
() and sticky_pref
(), while the config file in addition may call lockPref
(). Preferences files To protect privacy by preventing inadvertent loading of a preferences file in the browser, the first line of the file is made un-parseable and skipped on loading. The only exception to this is user.js . On a...
...Beta, Release) browser/defaults/preferences/firefox-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 L...
...hat preferences initially set by user.js will also be saved to prefs.js. Do NOT edit prefs.js directly. Note the application never changes user.js, so on launch user.js overrides conflicting preferences from the previous application session. When prefs.js is written, it only saves user preferences which are different from the default. The exception to this is a preference read using sticky_pref
() - these preference will be written whenever the preference has a user value even when it is the same as the default. Modifying preferences Advanced users can set named preferences via the advanced preferences editor, by typing about:config in the Location Bar. This UI is not recommended for most users. Programmatic changes to preferences can be made using the Preferences.jsm module from JS co...
...eference will result in being added to the Firefox blocklist or the preferences being forcibly removed. Note: because of abuse of user.js preferences, support for user.js may be removed in a future version of Firefox. See bug 1543752. Sticky Preferences Sticky preferences were introduced in Firefox 40 via bug 1098343. Sticky preferences are created when they are defined using sticky_pref
(). These preferences act as default preferences but whenever a value is created for the preference, that value is always written even when it matches the default. Sticky preferences are generally used for preferences that have a different default value in different channels with the intent being that once the user sets the preference in one channel, the preference will remain with that value when u...
NSPR's Position On Abrupt Thread Termination
mo describes my position on a facility that is currently under discussion for inclusion in the NetScape Portable Runtime (NSPR); the ability of a thread to abruptly exit. I resist including this function in NSPR because it results in bad programming practice and unsupportable programs. Threads are not processes. Abrupt termination has been available in the UNIX/C environment for some time (exit
()), and I assume that the basic semantics defined there are applicable here. In that environment, exit
() may be called and any time, and results in the calling thread's immediate termination. In the situation where it was defined (UNIX), which has only a single thread of execution, that is equivalent to terminating the process. The process abstraction is then responsible for closing all open files ...
...open files and reclaiming all storage that may have been allocated during the process' lifetime. This practice does not extend to threads. Threads run within the confines of a process (or similar abstractions in other environments). Threads are lightweight because they do not maintain the full protection domain provided by a process. So in a threaded environment, what is the parallel to UNIX' exit
()? NSPR has defined a function, callable by any thread within a process at any time, called PR_ProcessExit
(). This is identical to UNIX exit
() and was so named in an effort to make the obvious even more so. When called, the process exits, closing files and reclaiming the process' storage. Certain people have been disappointed when NSPR did not provide a functional equivalent to exit just a particul...
...rom the root function. This is not all that difficult (though having done it a number of times to already existing code, I will admit it isn't much fun either). The implementation of either strategy within the NSPR runtime is not difficult. That is not what this memo is about. This is about providing an API that coaxes people to do the right thing in as many ways as possible. The existence of exit
() in the UNIX/C environment is a perfect example of how programmers will employ the most expediant solution available. The definition of the language C is such that returning from main
() is a perfectly fine thing to do. But what percentage of C programs actually bother? In UNIX, with its complex definition of a protection domain, it happens to work (one might even say it's more efficient) to exit f...
...m anywhere. But threads are not processes. If threads have to maintain the same type of resource knowledge as a process, they loose all of their benefit. Threads are an implementation strategy to provide the illusion of concurrency within a process. They are alternatives to large state machines with mostly non-blocking library functions. When the latter is used to provide concurrency, calling exit
() will terminate the entire process. Why would anyone expect a thread to behave differently? Threads are not processes. Original Document Information Author: Alan O. Freier Last Updated Date: December 1998 ...
PR_IntervalNow
Returns the value of NSPR's free-running interval timer. Syntax #include <prinrval.h> PRIntervalTime PR_IntervalNow(void); Returns A PRIntervalTime object. Description You can use the value returned by PR_IntervalNow
() to establish epochs and to determine intervals (that is, compute the difference between two times). PR_IntervalNow
() is both very efficient and nonblocking, so it is appropriate to use (for example) while holding a mutex. The most common use for PR_IntervalNow
() is to establish an epoch and test for the expiration of intervals. ...
...d by PR_IntervalNow
() to establish epochs and to determine intervals (that is, compute the difference between two times). PR_IntervalNow
() is both very efficient and nonblocking, so it is appropriate to use (for example) while holding a mutex. The most common use for PR_IntervalNow
() is to establish an epoch and test for the expiration of intervals. In this case, you typically call PR_IntervalNow
() in a sequence that looks like this: PRUint32 interval = ... ; // milliseconds // ... ...
...oth very efficient and nonblocking, so it is appropriate to use (for example) while holding a mutex. The most common use for PR_IntervalNow
() is to establish an epoch and test for the expiration of intervals. In this case, you typically call PR_IntervalNow
() in a sequence that looks like this: PRUint32 interval = ... ; // milliseconds // ... ...
...sh an epoch and test for the expiration of intervals. In this case, you typically call PR_IntervalNow
() in a sequence that looks like this: PRUint32 interval = ... ; // milliseconds // ... ...
NSS_3.12_release_notes.html
Bug 391291: Shared Database Integrity checks not yet implemented. Bug 39...
...Bug 391291: Shared Database Integrity checks not yet implemented. Bug 391292: Shared Database implementation slow Bug 391294: Shared Database implementation really slow on network file systems ...
...Bug 217538: softoken databases cannot be shared between multiple processes Bug 294531: Design new interfaces for certificate path building and verification for libPKIX Bug 326482: NSS ECC performance problems (intel) Bug 391296: Need an ...
...ry efficient Bug 390185: signtool error message wrongly uses the term database Bug 391651: Need config.mk file for Windows Vista Bug 396322: Fix secutil's code and NSS tools that print public keys Bug 417641: miscellaneous minor NSS bugs Bug 334914: hopefully useless null check of out it in JAR_find_next Bug 95323: ckfw should support cipher operations. ...
NSS Sample Code sample2
i, result_len, tmp1_outlen, tmp2_outlen; /* Initialize NSS * If your application code has already initialized NSS, you can skip it * here. ...
...GetError
()); goto out; } /* choose mechanism: CKM_DES_CBC_PAD, CKM_DES3_ECB, CKM_DES3_CBC..... * Note that some mechanisms (*_PAD) imply the padding is handled for you * by NSS. If you choose something else, then data padding is the * application's responsibility */ cipherMech = CKM_DES_CBC_PAD; slot = PK11_GetBestSlot(cipherMech, NULL); /* slot = PK11_GetInternalKeySlot
(); is a simpler alternative but in * theory, it *may not* return the optimal slot for the operation. For * DES ops, Internal slot is typically the best slot */ if (slot == NULL) { fprintf(stderr, "Unable to find security device (err %d)\n", PR_GetError
()); goto out; } /* NSS passes blobs around as SECItems. These contain a pointer to * data and a length. Tur...
...bject. We use PK11_OriginUnwrap * to indicate the key was unwrapped - which is what should be done * normally anyway - using raw keys isn't a good idea */ SymKey = PK11_ImportSymKey(slot, cipherMech, PK11_OriginUnwrap, CKA_ENCRYPT, &keyItem, NULL); if (SymKey == NULL) { fprintf(stderr, "Failure to import key into NSS (err %d)\n", PR_GetError
()); goto out; } /* set up the PKCS11 encryption paramters. * when not using CBC mode, ivItem.data and ivItem.len can be 0, or you * can simply pass NULL for the iv parameter in PK11_ParamFromIV func */ ivItem.type = siBuffer; ivItem.data = gIV; ivItem.len = sizeof(gIV); SecParam = PK11_ParamFromIV(cipherMech, &ivItem); if (SecParam == NULL) { fprintf(stderr, "Failu...
...ers. ...
NSS Sample Code sample5
slot = NULL; /* Initialize NSS * You need to explicitly authenticate to the internal token if you use * NSS_Init insteadf of NSS_NoDB_Init * Invoke this after getting the internal token handle * PK11_Authenticate(slot, PR_FALSE, NULL); */ rv = NSS_NoDB_Init("."); if (rv != SECSuccess) { fprintf(stderr, "NSS initialization failed (err %d)\n", PR_GetError
()); goto cleanup; } /* get internal slot */ slot = PK11_GetInternalKeySlot
(); if (slot == NULL) { fprintf(stderr, "Couldn't find slot (err %d)\n", PR_GetError
()); goto cleanup; } rv = ATOB_ConvertAsciiToItem(&der, pubkstr); if (rv!= SECSuccess) { fprintf(stderr, "ATOB_ConvertAsciiToItem failed %d\n", PR_GetError
()); goto cleanup; } spki = SECKEY_DecodeDER...
...rv = ATOB_ConvertAsciiToItem(&der, pubkstr); if (rv!= SECSuccess) { fprintf(stderr, "ATOB_ConvertAsciiToItem failed %d\n", PR_GetError
()); goto cleanup; } spki = SECKEY_DecodeDERSubjectPublicKeyInfo(&der); SECITEM_FreeItem(&der, PR_FALSE); pubkey = SECKEY_ExtractPublicKey(spki); if (pubkey == NULL) { fprintf(stderr, "Couldn't extract public key (err %d)\n", PR_GetError
()); goto cleanup; } modulus_len = SECKEY_PublicKeyStrength(pubkey); fprintf(stderr, "Public Key Modulus %d bytes\n", modulus_len); buf1 = (char *)malloc(modulus_len); buf2 = (char *)malloc(modulus_len); /* initialize buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= (i %26) + 'A'; } buf1[modulus_len-1] = '\0'; fprintf(stderr, "Buffer being encrypted = \n%s\n", buf1); ...
...tialize buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= (i %26) + 'A'; } buf1[modulus_len-1] = '\0'; fprintf(stderr, "Buffer being encrypted = \n%s\n", buf1); /* encrypt buf1, result will be in buf2 */ rv = PK11_PubEncryptRaw(pubkey, buf2, buf1, modulus_len, NULL); if (rv != SECSuccess) { fprintf(stderr, "Encrypt with Public Key failed (err %d)\n", PR_GetError
()); goto cleanup; } nickname.type = siBuffer; nickname.data = "pvtkeynickname"; nickname.len = strlen("pvtkeynickname"); rv = ATOB_ConvertAsciiToItem(&der, pvtkstr); if (rv!= SECSuccess) { fprintf(stderr, "ATOB_ConvertAsciiToItem failed %d\n", PR_GetError
()); goto cleanup; } /* KU_ALL includes a lot of different key usages, KU_DATA_ENCIPHERMENT * is enough for jus...
...h) can be NULL for RSA key - I think it is even * ignored */ PK11_ImportDERPrivateKeyInfoAndReturnKey(slot, &der, NULL, NULL, PR_FALSE, PR_TRUE, KU_ALL, &pvtkey, NULL); SECITEM_FreeItem(&der, PR_FALSE); if (pvtkey == NULL) { fprintf(stderr, "Couldn't extract private key (err %d)\n", PR_GetError
()); goto cleanup; } /* clear buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= '\0'; } /* decrypt buf2, result will be in buf1 */ rv = PK11_PubDecryptRaw(pvtkey, buf1, &outlen, modulus_len, buf2, modulus_len); if (rv != SECSuccess) { fprintf(stderr, "Decrypt with Private Key failed (err %d)\n", PR_GetError
()); goto cleanup; } ...
NSS Sample Code sample6
SECStatus rv; /* Initialize NSS */ PK11_SetPasswordFunc(passwdcb); /* The NSS db must be initialized read-write since we'll be creating * keys in it. Once keys are generated, it can be opened without read-write * subsequently (NSS_Init). */ rv = NSS_InitReadWrite("."); if (rv != SECSuccess) { fprintf(stderr, "NSS initialization failed (err %d)\n", PR_GetError
()); exit(1); } /* generate a key with id 1. should succeed on first run on a fresh db, * should fail on successive runs because key with that id already exists */ genkey(1); /* generate a key with id 2. should succeed on first run on a fresh db, * should fail on successive runs because key with that id already exists */ genkey(2); /* generate a key with id 1 - this will fai...
... /* generate a key with id 1 - this will fail because key with that id * already exists */ genkey(1); } void genkey(int id) { PK11SlotInfo* slot = NULL; PK11SymKey* key = NULL; SECItem keyiditem; int keyid[1]; CK_MECHANISM_TYPE cipherMech; /* using CKM_AES_CBC_PAD mechanism for example */ cipherMech = CKM_AES_CBC_PAD; slot = PK11_GetInternalKeySlot
(); /* slot = PK11_GetBestSlot(cipherMech, NULL); didn't work. * Error code: token is read-only. ?? */ if (slot == NULL) { fprintf(stderr, "Unable to find security device (err %d)\n", PR_GetError
()); return; } keyid[0] = id; keyiditem.type = siBuffer; keyiditem.data = (void *)keyid; keyiditem.len = sizeof(keyid[0]); /* Note: keysize must be 0 for fixed k...
... keysize must be 0 for fixed key-length algorithms like DES. ...
...n; } fprintf(stderr, "key length of generated key is %d\n", PK11_GetKeyLength(key)); fprintf(stderr, "mechanism of key is %d (asked for %d)\n", PK11_GetMechanism(key), cipherMech); PK11_FreeSymKey(key); key = PK11_FindFixedKey(slot, cipherMech, &keyiditem, 0); if (key == NULL) { fprintf(stderr, "PK11_FindFixedKey failed (err %d)\n", PR_GetError
()); PK11_FreeSlot(slot); return; } fprintf(stderr, "Found key!\n"); fprintf(stderr, "key length of generated key is %d\n", PK11_GetKeyLength(key)); fprintf(stderr, "mechanism of key is %d (asked for %d)\n", PK11_GetMechanism(key), cipherMech); PK11_FreeSymKey(key); PK11_FreeSlot(slot); } char *passwdcb(PK11SlotInfo *info, PRBool retry, void *arg) { if (...
nss tech note7
exponent is to factor the modulus. At present 1024 bit and 2048 bit RSA keys are the most common and recommended. To prevent denial-of-service attacks with huge public keys, NSS disallows modulus size greater than 8192 bits. How are these keys created in NSS? There are a few possibilities. RSA key pairs may be generated inside a crypto module (also known as a token). Use PK11_GenerateKeyPair
() to generate a key pair in a crypto module. Key pairs may be generated elsewhere, exported in encrypted form, and imported into a crypto module. Public keys may be imported into NSS. Call SECKEY_ImportDERPublicKey
() with type=CKK_RSA to import a DER-encoded RSA public key. If you have the modulus and public exponent, you need to first encode them into an RSA public key and then import the public...
...teger; inPubKey.m_exponent.type = siUnsignedInteger; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); SEC_ASN1EncodeItem(arena, &derPubKey, &inPubKey, MyRSAPublicKeyTemplate); pubKey = SECKEY_ImportDERPublicKey(&derPubKey, CKK_RSA); PORT_FreeArena(arena, PR_FALSE); Public keys may be extracted from certificates. Given a certficate (CERTCertificate *), use CERT_ExtractPublicKey
() to extract its public key. The returned public key may be used after the certificate is destroyed. When the keys are no longer needed, they need to be destroyed. Use SECKEY_DestroyPublicKey
() to destroy a public key (SECKEYPublicKey *). Use SECKEY_DestroyPrivateKey
() to destroy a private key (SECKEYPrivateKey *). Unlike SECKEYPublicKey and SECKEYPrivateKey, PK11SymKey objects are reference c...
...returned public key may be used after the certificate is destroyed. When the keys are no longer needed, they need to be destroyed. Use SECKEY_DestroyPublicKey
() to destroy a public key (SECKEYPublicKey *). Use SECKEY_DestroyPrivateKey
() to destroy a private key (SECKEYPrivateKey *). Unlike SECKEYPublicKey and SECKEYPrivateKey, PK11SymKey objects are reference counted. Use PK11_ReferenceSymKey
() to acquire a reference to a symmetric key (PK11SymKey *). Use PK11_FreeSymKey
() to release a reference to a symmetric key (PK11SymKey *); the symmetric key is destroyed when its reference count becomes zero. Functions RSA signing and encryption functions are provided by two layers of NSS function: the SGN_ and VFY_ functions in cryptohi.h, and the PK11_ functions in pk11pub.h. As a general princ...
...ith a protocol that isn't implemented by NSS, then you may need to use the PK11_ functions. (This API pretty much consists of what was needed to implement SSL and S/MIME, plus a few enhancements over the years to support JSS.) When using the PK11_ interfaces, the same principal applies: use the highest available function. If you are really trying to send a key, you should use PK11_PubWrapSymKey
(). For a low level signature, use PK11_Sign
(). Both of these functions do the PKCS #1 wrapping of the data. PK11_Sign does not do the BER encoding of the hash (as is done in SGN_ functions). If you are trying to just send data, use PK11_PubEncryptPKCS1. PK11_PubEncryptRaw is the lowest level function. It takes a modulus size data and does a raw RSA operation on the data. It's used to support ...
FC_InitToken
Name FC_InitToken
() - initialize or re-initialize a token. Syntax CK_RV FC_InitToken( CK_SLOT_ID slotID, CK_CHAR_PTR pPin, CK_ULONG ulPinLen, CK_CHAR_PTR pLabel ); Parameters FC_InitToken
() has the following parameters: slotID the ID of the token's slot pPin the password of the security officer (SO) ulPinLen the length in bytes of the SO password pLabel points to the label of the token, which must be padded with spaces to 32 bytes and not be null-terminated Description FC_InitToken
() initializes a brand new token or re-initializes a token that was initialized before. Specifically, FC_InitToken
() initializes or clears the key database, removes the password, and then marks all the user certs in the certificate database as non-user certs. (User certs are the certif...
...Token
() initializes a brand new token or re-initializes a token that was initialized before. Specifically, FC_InitToken
() initializes or clears the key database, removes the password, and then marks all the user certs in the certificate database as non-user certs. (User certs are the certificates that have their associated private keys in the key database.) A user must be able to call FC_InitToken
() without logging into the token (to assume the NSS User role) because either the user's password hasn't been set yet or the user forgets the password and needs to blow away the password-encrypted private key database and start over. Note: The SO password should be the empty string, i.e., ulPinLen argument should be 0. FC_InitToken
() ignores the pLabel argument. ...
...ken
() without logging into the token (to assume the NSS User role) because either the user's password hasn't been set yet or the user forgets the password and needs to blow away the password-encrypted private key database and start over. Note: The SO password should be the empty string, i.e., ulPinLen argument should be 0. FC_InitToken
() ignores the pLabel argument. Return value FC_InitToken
() returns the following return codes. CKR_OK: token initialization succeeded. CKR_SLOT_ID_INVALID: slot ID is invalid. CKR_TOKEN_WRITE_PROTECTED we don't have a reference to the key database (we failed to open the key database or we have released our reference). CKR_DEVICE_ERROR: failed to reset the key database. ...
...abel argument. Return value FC_InitToken
() returns the following return codes. CKR_OK: token initialization succeeded. CKR_SLOT_ID_INVALID: slot ID is invalid. CKR_TOKEN_WRITE_PROTECTED we don't have a reference to the key database (we failed to open the key database or we have released our reference). CKR_DEVICE_ERROR: failed to reset the key database. Application usage FC_InitToken
() is used to reset the password for the key database when the user forgets the password. The "Reset Password" button of the Mozilla Application Suite and SeaMonkey (in Preferences->Privacy & Security->Master Passwords) calls FC_InitToken
(). The "-T" (token reset) command of certutil calls FC_InitToken
(). Note: Resetting the password clears all permanent secret and private keys. You won't be abl...
FC_Login
CKR_OK: the user logged in successfully. ...
... CKR_OK: the user logged in successfully. ...
... CKR_OK: the user logged in successfully. ...
... CKR_OK: the user logged in successfully. CKR_DEVICE_ERROR: the token is in the Error state. CKR_HOST_MEMORY: memory allocation failed. CKR_PIN_INCORRECT: the PIN is incorrect. ...
NSC_InitToken
Name NSC_InitToken
() - initialize or re-initialize a token. Syntax CK_RV NSC_InitToken( CK_SLOT_ID slotID, CK_CHAR_PTR pPin, CK_ULONG ulPinLen, CK_CHAR_PTR pLabel ); Parameters NSC_InitToken
() has the following parameters: slotID the ID of the token's slot pPin the password of the security officer (SO) ulPinLen the length in bytes of the SO password pLabel points to the label of the token, which must be padded with spaces to 32 bytes and not be null-terminated Description NSC_InitToken
() initializes a brand new token or re-initializes a token that was initialized before. Specifically, NSC_InitToken
() initializes or clears the key database, removes the password, and then marks all the user certs in the certificate database as non-user certs. (User certs are the c...
... CKR_OK: token initialization succeeded. CKR_SLOT_ID_INVALID: slot ID is invalid. CKR_TOKEN_WRITE_PROTECTED slot ID is 1. (The non-FIPS mode has two slots: 1 and 2. The key database is in slot 2. ...
...itializes or clears the key database, removes the password, and then marks all the user certs in the certificate database as non-user certs. (User certs are the certificates that have their associated private keys in the key database.) Note: The SO password should be the empty string, i.e., ulPinLen argument should be 0. NSC_InitToken
() ignores the pLabel argument. Return value NSC_InitToken
() returns the following return codes. CKR_OK: token initialization succeeded. CKR_SLOT_ID_INVALID: slot ID is invalid. CKR_TOKEN_WRITE_PROTECTED slot ID is 1. (The non-FIPS mode has two slots: 1 and 2. The key database is in slot 2. Slot 1 doesn't have a key database.) we don't have a reference to the key database (we failed to open the key database or we have released our reference). CKR_D...
...INVALID: slot ID is invalid. CKR_TOKEN_WRITE_PROTECTED slot ID is 1. (The non-FIPS mode has two slots: 1 and 2. The key database is in slot 2. Slot 1 doesn't have a key database.) we don't have a reference to the key database (we failed to open the key database or we have released our reference). CKR_DEVICE_ERROR: failed to reset the key database. Examples Application usage NSC_InitToken
() is used to reset the password for the key database when the user forgets the password. The "Reset Password" button of the Mozilla Application Suite and SeaMonkey (in Preferences->Privacy & Security->Master Passwords) calls NSC_InitToken
(). The "-T" (token reset) command of certutil calls NSC_InitToken
(). Note: Resetting the password clears all permanent secret and private keys. You won't be a...
NSC_Login
CKR_OK: the user logged in successfully. ...
... CKR_OK: the user logged in successfully. ...
... CKR_OK: the user logged in successfully. ...
... CKR_OK: the user logged in successfully. CKR_DEVICE_ERROR: the token is in the Error state. CKR_HOST_MEMORY: memory allocation failed. CKR_PIN_INCORRECT: the PIN is incorrect. ...
Rhino shell
lements Java2 security model. Predefined Properties Scripts executing in the shell have access to some additional properties of the top-level object. arguments The arguments object is an array containing the strings of all the arguments given at the command line when the shell was invoked. environment Returns the current environment object. history Displays the shell command history. help
() Executing the help function will print usage and help messages. defineClass(className) Define an extension using the Java class named with the string argument className. Uses ScriptableObject.defineClass
() to define the extension. deserialize(filename) Restore from the specified file an object previously written by a call to serialize. gc
() Runs the garbage collector. load([filename, ...]...
...fy its properties would throw an exception. serialize(object, filename) Serialize the given object to the specified file. spawn(functionOrScript) Run the given function or script in a different thread. sync(function) creates a synchronized function (in the sense of a Java synchronized method) from an existing function. The new function synchronizes on the this object of its invocation. quit
() Quit shell. The shell will also quit in interactive mode if an end-of-file character is typed at the prompt. version([number]) Get or set JavaScript version number. If no argument is supplied, the current version number is returned. If an argument is supplied, it is expected to be one of 100, 110, 120, 130, 140, 150, 160 or 170 to indicate JavaScript version 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6 o...
...self. The next invocation has no arguments, so the shell goes into interactive mode, reading and evaluating each line as it is typed in. Finally, the last invocation executes a script from a file and accesses arguments to the script itself. $ java org.mozilla.javascript.tools.shell.Main -e "print('hi')" hi $ java org.mozilla.javascript.tools.shell.Main js> print('hi') hi js> 6*7 42 js> function f
() { return a; } js> var a = 34; js> f
() 34 js> quit
() $ cat echo.js for (i in arguments) { print(arguments[i]) } $ java org.mozilla.javascript.tools.shell.Main echo.js foo bar foo bar $ spawn and sync The following example creates 2 threads via spawn and uses sync to create a synchronized version of the function test. js> function test(x) { print("entry"); java.lang.Thread.sleep(x*1000)...
...r (i in arguments) { print(arguments[i]) } $ java org.mozilla.javascript.tools.shell.Main echo.js foo bar foo bar $ spawn and sync The following example creates 2 threads via spawn and uses sync to create a synchronized version of the function test. js> function test(x) { print("entry"); java.lang.Thread.sleep(x*1000); print("exit"); } js> var o = { f : sync(test) }; js> spawn(function
() {o.f(5);}); Thread[Thread-0,5,main] entry js> spawn(function
() {o.f(5);}); Thread[Thread-1,5,main] js> exit entry exit runCommand Here are a few examples of invoking runCommand under Linux. js> runCommand('date') Thu Jan 23 16:49:36 CET 2003 0 // Using input option to provide process input js> runCommand("sort", {input: "c\na\nb"}) a b c 0 js> // Demo of output and err options js> var opt={in...
64-bit Compatibility
4-T/Intel64), it is important to keep in mind an invariant that bits 63-48 must be sign-extended from bit 47. If you use these bits to squirrel away a payload, they must be adjusted before attempting to dereference the pointer. For more information and platform specific details on virtual address widths, see this article on Wikipedia. Builtins and Calls When passing arguments to LirWriter::insCall
(), there are four types: ARGSIZE_F - floating point value ARGSIZE_I - 32-bit integer ARGSIZE_Q - 64-bit integer ARGSIZE_P - 32-bit integer on 32-bit platforms, 64-bit integer on 64-bit platforms. Remember to use ARGSIZE_P where appropriate - on pointers or natively sized integers (including jsvals). Similarly, when adding types to jsbuiltins.h, remember to use _JS_PTR for pointer-width values...
...-bit. On 64-bit machines you must use LIR_ldq. Luckily there is an alias that will choose the right opcode for you - LIR_ldp: struct Object { void *data; }; lir->insLoad(LIR_ldp, objIns, ins->insImm(offsetof(Object, data))); When you use LirWriter::insStore, the correct size is chosen for you automatically, based on the size of the input operands. To insert constants, use LirWriter::insImmPtr
() for pointer types or LirWriter::insImmWord
() for integral types. Note that LirWriter::insImm
() is always 32-bit. Quad versus Float Internally, "quads" are 64-bit opaque values in Nanojit. They can be either floating point values or integral values. To help form well-typed LIR, there is a special opcode called LIR_float which specifies that the associated constant value is definitely floating-poin...
...ternally, "quads" are 64-bit opaque values in Nanojit. They can be either floating point values or integral values. To help form well-typed LIR, there is a special opcode called LIR_float which specifies that the associated constant value is definitely floating-point. TraceMonkey uses this to decide whether arbitrary constants in LIR are pointers or doubles. You should never use LirWriter::insImmq
() to inject a floating point value. Use LirWriter::insImmf
() instead. Mucking with Native Integers in LIR The following opcodes can be used to safely load, modify, and compare native integers. For such opcodes there are two forms, an "undecorated" form which is 32-bit, and a form decorated with a "q" or "qi" that is 64-bit. To make it easier to generate platform specific code, these opcodes have al...
...teger to a 32-bit integer (for example, array or string lengths in TraceMonkey) or extend a 32-bit integer to a native integer. There are three such opcodes: LIR_i2q - Sign-extends a 32-bit integer to a 64-bit integer. LIR_u2q - Zero-extends a 32-bit integer to a 64-bit integer. LIR_qlo - Truncates a 64-bit integer to its lower 32 bits. There are three helper functions in LirWriter: ins_i2p
() - On 32-bit platforms, does nothing. On 64-bit platforms, performs a LIR_i2q. ins_u2p
() - On 32-bit platforms, does nothing. On 64-bit platforms, performs a LIR_u2q. ins_p2i
() - On 32-bit platforms, does nothing. On 64-bit platforms, performs a LIR_qlo. A common use for extending values is to perform advanced addressing. For example, this code tries to load an index from an integer array, but ...
JS_ConvertArguments
ated (W for wide) o JSObject * Object reference f JSFunction * The argument is converted to a function as though by a call to JS_ValueToFunction. This conversion is dangerous and almost entirely useless, because the resulting JSFunction is not a real function object and therefore cannot be safely passed to any other JSAPI function. ...
...o JSObject * Object reference f JSFunction * The argument is converted to a function as though by a call to JS_ValueToFunction. This conversion is dangerous and almost entirely 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
(). ...
... v jsval Argument value (no conversion) * N/A None. If an asterisk (*) is present in format, it tells the conversion routine to skip converting the current argument. ...
... v jsval Argument value (no conversion) * N/A None. If an asterisk (*) is present in format, it tells the conversion routine to skip converting the current argument. / N/A None. Arguments after the slash are optional. ...
JS_ValueToFunction
convert. Description JS_ValueToFunction converts a specified JavaScript value, v, to a function. JS_ValueToConstructor is the exactly same function as JS_ValueToFunction. This conversion is dangerous and almost entirely useless, because the resulting JSFunction is not a real function object and therefore cannot be safely passed to any other JSAPI function. ...
...n JS_ValueToFunction converts a specified JavaScript value, v, to a function. JS_ValueToConstructor is the exactly same function as JS_ValueToFunction. This conversion is dangerous and almost entirely 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
(). ...
... 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_ValueToFunction returns NULL. Otherwise, v is an object. ...
... 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_ValueToFunction returns NULL. Otherwise, v is an object. The JavaScript engine attempts to convert it to a function. ...
Web Replay
devtools server, debugging a recording/replaying process is very similar to debugging a live process. When execution is paused, the Debugger JS object and its various child objects can be used to inspect the execution state in the same way for a either kind of process. Here are the main differences: Explicit commands must be sent to the debugger to control execution. The replayResumeBackward
() and replayResumeForward
() members may be called to resume execution, and the replayPause
() member may be called to pause execution at the next opportunity. A child process can only pause at breakpoints and at snapshot points (currently these only happen when graphics updates are performed, at which point there is no JS on the stack). There is a new onPopFrame handler, which is needed when doing...
...ction is needed for a function is that the replay tests crash inside it while replaying. New redirections can be added to toolkit/recordreplay/ProcessRedirectDarwin.cpp, adding just a few lines for functions with simple interfaces using the various RRFunction macros. Missing redirections can also be temporarily worked around by avoiding the call when mozilla::recordreplay::IsRecordingOrReplaying
(). Recording events in disallowed areas GC marking and finalization may behave differently when recording and replaying, and recording events for a thread -- calling redirected library functions, using recorded locks or recorded atomics -- is disallowed at these times. There are some other areas where recorded events are also disallowed, such as during JS interrupt callbacks. Recording an event...
...ization may behave differently when recording and replaying, and recording events for a thread -- calling redirected library functions, using recorded locks or recorded atomics -- is disallowed at these times. There are some other areas where recorded events are also disallowed, such as during JS interrupt callbacks. Recording an event in one of these areas will fail a !AreThreadEventsDisallowed
() assertion. These failures usually result from accessing a recorded lock or atomic. Core xpcom and mozglue lock classes and mozilla::Atomic atomics are recorded by default, but many locks and atomics don't actually need to be recorded in order to correctly replay. Recording for a lock or atomic can be turned off by specifying recordreplay::Behavior::DontPreserve in either the lock's contructor ...
... ...
Packaging WebLock
The following HTML specifies a complete webpage in which the trigger script is defined as a JavaScript function, installWebLock, that gets called when the user clicks the hyperli...
...ears in the XPI. The following HTML specifies a complete webpage in which the trigger script is defined as a JavaScript function, installWebLock, that gets called when the user clicks the hyperlink. ...
...r clicks the hyperlink. <!DOCTYPE html> <html> <title>WebLock Installation</title> <script> /* * Trigger function that downloads the XPI so the * install.js file inside can be read and executed */ function installWebLock
() { weblock_xpi = {'WebLock Extension': 'weblock.xpi'}; InstallTrigger.install(weblock_xpi); } </script> <h1>Install WebLock</h1> <p><a href="#" onclick="installWebLock
();">install weblock</a></p> </html> Distributing Your Component Once you have the component packaged properly and the necessary installation and trigger scripts, you are ready to distribute your component so others can install it in their Gecko applications. In Mozilla and Netscape browsers, XPInstall makes this process especially easy by providing the file format (XPI) and the necessary insta...
...XPInstall is not available, then you will have to devise a separate installation scheme. We leave this as an exercise for the reader. Note: install-object-methods The methods are available on the main Install object, which is implied in the script below in the same way that the window object is implied in JavaScript manipulation of the DOM of a web page. In other words, the fragment initInstall
() from the script is equivalent to Install.initInstall
(). << 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 h...
Components.isSuccessCode
Summary Determines whether a given XPCOM return code (that is, an nsresult value) indicates the success or failure of an operation, returning true or false respectively. Syntax var succeeded = Components.isSuccessCode(returnCode); Parameters returnCode The return code (of type nsresult) to be checked. ...
...However, if you are using asynchronous APIs, it may be essential. ...
...us APIs, it may be essential. For example, if you ask a component or service to asynchronously perform some task, you must usually pass in an object which will be notified when the task is completed. If the task is sufficiently complex that it can fail, the notification will include a status code indicating the success or failure of the operation (see, for example, nsIRequestObserver.onStopRequest
()). To determine the success or failure of the complex task, you would call Components.isSuccessCode
() upon the status code included in the notification. Examples Checking whether copying a stream's data succeeded The following example demonstrates copying data from a buffered nsIInputStream to an nsIOutputStream, checking for whether the copy succeeded using Components.isSuccessCode
(). Note: n...
...ess or failure of the complex task, you would call Components.isSuccessCode
() upon the status code included in the notification. Examples Checking whether copying a stream's data succeeded The following example demonstrates copying data from a buffered nsIInputStream to an nsIOutputStream, checking for whether the copy succeeded using Components.isSuccessCode
(). Note: nsIAsyncStreamCopier.init
() has changed in Gecko 1.9.2, omit last 2 boolean parameters if you're using Gecko 1.9.1 and earlier. const Cc = Components.classes; const Ci = Components.interfaces; const Cr = Components.results; // global flags polled externally var copyFailed = false; var copyInProgress = false; function copyBufferedStream(inStream, outStream) { var copyObserver = { onStartRequest: function(reque...
Components.lastResult
than doing multiple tests against Components.lastResult. This is because many 'Components' properties and methods are themselves implemented using XPConnect and subsequent calls to Components.lastResult might reflect the result of 'implicit' XPConnect calls rather than the result of the target call. ...
...ests against Components.lastResult. This is because many 'Components' properties and methods are themselves implemented using XPConnect and subsequent calls to Components.lastResult might reflect the result of 'implicit' XPConnect calls rather than the result of the target call. ...
... themselves implemented using XPConnect and subsequent calls to Components.lastResult might reflect the result of 'implicit' XPConnect calls rather than the result of the target call. Example In the following example, the local variable i contains the actual result returned by bar
() (assuming that bar
() is called via XPConnect), and Components.lastResult contains the success code returned by bar
(). // Given that foo.bar is a method that might return // the success codes NS_OK, '5', and '6' OR some error code... ...
...ther than the result of the target call. Example In the following example, the local variable i contains the actual result returned by bar
() (assuming that bar
() is called via XPConnect), and Components.lastResult contains the success code returned by bar
(). // Given that foo.bar is a method that might return // the success codes NS_OK, '5', and '6' OR some error code... try { var i = foo.bar
(); switch (Components.lastResult) { case Components.results.NS_OK: // NS_OK is good! break; case 5: // do something with 5 here break; case 6: // do something with 6 here break; default: // this was a success code we did not expect. Bad component! break; } // and so on.... } catch (e) { // the call threw an exception or a na...
Components.utils.cloneInto
Suppose the page script defines a...
...Window)); // "they said: hello from add-on" Cloning objects that have functions If the object to be cloned contains functions, you must pass the {cloneFunctions:true} flag or you'll get an error. ...
...: // add-on script var addonScriptObject = { greetme: function
() { alert("hello from add-on"); } }; contentWindow.addonScriptObject = cloneInto(addonScriptObject, contentWindow, {cloneFunctions: true}); // page script var test = document.getElementById("test"); test.addEventListener("click", function
() { window.addonScriptObject.greetme
(); }, false); Cloning objects that contain DOM elements By default, if the object you clone contains objects that are reflected from C++, such as DOM elements, the cloning operation will fail with an error. If you pass the {wrapReflectors:true} flag, then the object you clone is allowed to contain these objects: // add-on script var addonScriptObject = { bo...
... ...
Components.utils.getWeakReference
Syntax weakRef = Components.utils.getWeakReference(obj); Parameters obj The object for which to obtain a weak reference. ...
... Syntax weakRef = Components.utils.getWeakReference(obj); Parameters obj The object for which to obtain a weak reference. ...
... Syntax weakRef = Components.utils.getWeakReference(obj); Parameters obj The object for which to obtain a weak reference. ...
...nged to throw an exception if obj is null. ...
nsIRegistry
ents.interfaces; var rc = Cc["@mozilla.org/registry;1"]; var rs = rc.getService(Ci.nsIRegistry); Now you have the registry service. rs.openWellKnownRegistry(2); // 2 signifies the ApplicationRegistry, if I understand right var st = rs.enumerateAllSubtrees(2); // 2 signifies "common", see libreg source (reg.h) for info Now you have an nsIEnumerator that can report the subtrees. ...
...rg/registry;1"]; var rs = rc.getService(Ci.nsIRegistry); Now you have the registry service. rs.openWellKnownRegistry(2); // 2 signifies the ApplicationRegistry, if I understand right var st = rs.enumerateAllSubtrees(2); // 2 signifies "common", see libreg source (reg.h) for info Now you have an nsIEnumerator that can report the subtrees. ...
...ies the ApplicationRegistry, if I understand right var st = rs.enumerateAllSubtrees(2); // 2 signifies "common", see libreg source (reg.h) for info Now you have an nsIEnumerator that can report the subtrees. try { st.first
(); do { var data = st.currentItem
(); if( data instanceof Ci.nsIRegistryNode ) print("nsIRegistryNode: " + data.nameUTF8 + " (" + data.key + ")"); st.next
(); } while( Components.lastResult == 0 ); } catch(e) {} Now, the output is something like: Profiles (344) Profiles/default (530) Profiles/foo (1046) Profiles/bar (1518) The number inside the parenthesis is the "key." You can use this key with the rest of the nsIRegistry API (see MXR). Now, I know from visual inspection that there's a key called "directory" for each profile. I don't know how to ...
...icular profile. js> rs.getStringUTF8(530, "directory") // 530: key corresponding with Profiles/default The output is something like: /home/lion/.mozilla/default/awp83kud.slt Boo-yah! Can we change it? js> rs.setStringUTF8(530, "directory", "/home/lion/somewhere/else") js> rs.getStringUTF8(530, "directory") /home/lion/somewhere/else Yes! Now, the only puzzle is: how do you save it? js> rs.flush
() // this is not enough... Perhaps if we quit with the XPConnect:appShellService, it will work. ...
Language bindings
omponents.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 result is structured cloned back to the original context, unless it is native (for example...
...ne the global object with which an object is associated. This is the global object in place at the time the object was created, which is to say the global object used when executing the script that created the object.Components.utils.getWeakReferenceThis 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.Components.utils.importComponents.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.Components.utils.importGlobalPropertiesImports various objects into a system scope.Components.utils.isX...
...wrappers.Components.utils.reportErrorComponents.utils.reportError reports a JavaScript Error object to the Error Console, and returns. It is meant for use by extension developers who have exception handler blocks which want to "eat" an exception, but still want to report it to the console.Components.utils.SandboxComponents.utils.Sandbox is used to create a sandbox object for use with evalInSandbox
().Components.utils.schedulePreciseGCThis method lets scripts schedule a garbage collection cycle. The garbage collection cycle will occur sometime in the future, when no JavaScript code is executing. This is useful particularly when testing for memory leaks, because normal garbage collection is conservative when JavaScript code is running to ensure that in-use memory isn't inadvertently collected.C...
...hrough to that thusly:Components.utils.unloadComponents.utils.unload was introduced in Firefox 7 and is used to unload JavaScript code modules. This can be particularly handy with restartless (boostrapped) extensions, so that you can unload an old version of a code module when a new version of your add-on is installed.Components.utils.unwaiveXraysUndo a previous call to Components.utils.waiveXrays
(), restoring Xray vision for the caller.Components.utils.waiveXraysWaives Xray vision for an object, giving the caller a transparent wrapper to the underlying object.JavaXPCOMJavaXPCOM allows for communication between Java and XPCOM, such that a Java application can access XPCOM objects, and XPCOM can access any Java class that implements an XPCOM interface. JavaXPCOM is not actively maintained.PlX...
nsACString_internal
hods Constructors void nsACString_internal(const nsCSubstringTuple&) - source this is public to support automatic conversion of tuple to string base type, which helps avoid converting to nsTAString. ...
...e Parameters char* data PRUint32 length PRUint32 flags BeginReading char* BeginReading
() const - source reading iterators nsReadingIterator<char>& BeginReading(nsReadingIterator<char>&) const - source deprecated reading iterators Parameters nsReadingIterator<char>& iter char*& BeginReading(const char*&) const - source Parameters char*& iter EndReading char* EndReading
() const - source nsReadingIterator<char>& EndReading(nsReadingIterator<char>&) const - source Parameters nsReadingIterator<char>& iter char*& EndReading(const char*&) const - source Parameters char*& iter BeginWriting char* BeginWriting
() - source writing iterators nsWritingIterator<char>& BeginWriting(nsWritingIterator<char>&) - source deprecated writing iterators Paramete...
... iter char*& EndReading(const char*&) const - source Parameters char*& iter BeginWriting char* BeginWriting
() - source writing iterators nsWritingIterator<char>& BeginWriting(nsWritingIterator<char>&) - source deprecated writing iterators Parameters nsWritingIterator<char>& iter char*& BeginWriting(char*&) - source Parameters char*& iter EndWriting char* EndWriting
() - source nsWritingIterator<char>& EndWriting(nsWritingIterator<char>&) - source Parameters nsWritingIterator<char>& iter char*& EndWriting(char*&) - source Parameters char*& iter Data char* Data
() const - source accessors Length PRUint32 Length
() const - source IsEmpty PRBool IsEmpty
() const - source IsVoid PRBool IsVoid
() const - source IsTerminated ...
...gIterator<char>& EndWriting(nsWritingIterator<char>&) - source Parameters nsWritingIterator<char>& iter char*& EndWriting(char*&) - source Parameters char*& iter Data char* Data
() const - source accessors Length PRUint32 Length
() const - source IsEmpty PRBool IsEmpty
() const - source IsVoid PRBool IsVoid
() const - source IsTerminated PRBool IsTerminated
() const - source CharAt char CharAt(PRUint32) const - source Parameters PRUint32 i operator[] char operator[](PRUint32) const - source Parameters PRUint32 i First char First
() const - source Last char Last
() const - source CountChar PRUint32 CountChar(char) const - source Parameters char <anonymous> FindChar PRInt32 FindChar(char, PRUint32) const -...
nsAString_internal
tructors void nsAString_internal(const nsSubstringTuple&) - source this is public to support automatic conversion of tuple to string base type, which helps avoid converting to nsTAString. ...
...nReading PRUnichar* BeginReading
() const - source reading iterators nsReadingIterator<short unsigned int>& BeginReading(nsReadingIterator<short unsigned int>&) const - source deprecated reading iterators Parameters nsReadingIterator<short unsigned int>& iter PRUnichar*& BeginReading(const PRUnichar*&) const - source Parameters PRUnichar*& iter EndReading PRUnichar* EndReading
() const - source nsReadingIterator<short unsigned int>& EndReading(nsReadingIterator<short unsigned int>&) const - source Parameters nsReadingIterator<short unsigned int>& iter PRUnichar*& EndReading(const PRUnichar*&) const - source Parameters PRUnichar*& iter BeginWriting PRUnichar* BeginWriting
() - source writing iterators nsWritingIterator<short unsigned int>& BeginWritin...
...Unichar*& iter BeginWriting PRUnichar* BeginWriting
() - source writing iterators nsWritingIterator<short unsigned int>& BeginWriting(nsWritingIterator<short unsigned int>&) - source deprecated writing iterators Parameters nsWritingIterator<short unsigned int>& iter PRUnichar*& BeginWriting(PRUnichar*&) - source Parameters PRUnichar*& iter EndWriting PRUnichar* EndWriting
() - source nsWritingIterator<short unsigned int>& EndWriting(nsWritingIterator<short unsigned int>&) - source Parameters nsWritingIterator<short unsigned int>& iter PRUnichar*& EndWriting(PRUnichar*&) - source Parameters PRUnichar*& iter Data PRUnichar* Data
() const - source accessors Length PRUint32 Length
() const - source IsEmpty PRBool IsEmpty
() const - source ...
...ator<short unsigned int>& EndWriting(nsWritingIterator<short unsigned int>&) - source Parameters nsWritingIterator<short unsigned int>& iter PRUnichar*& EndWriting(PRUnichar*&) - source Parameters PRUnichar*& iter Data PRUnichar* Data
() const - source accessors Length PRUint32 Length
() const - source IsEmpty PRBool IsEmpty
() const - source IsVoid PRBool IsVoid
() const - source IsTerminated PRBool IsTerminated
() const - source CharAt PRUnichar CharAt(PRUint32) const - source Parameters PRUint32 i operator[] PRUnichar operator[](PRUint32) const - source Parameters PRUint32 i First PRUnichar First
() const - source Last PRUnichar Last
() const - source CountChar PRUint32 CountChar(PRUnichar) const - source Par...
nsDependentCSubstring
PRUint32) - source Parameters nsACString_internal& str PRUint32 startPos PRUint32 length void nsDependentCSubstring(const char*, const char*) - source Parameters char* start char* end void nsDependentCSubstring(const nsReadingIterator<char>&, const nsReadingIterator<char>&) - source Parameters nsReadingIterator<char>& start nsReadingIterator<char>& end void nsDependentCSubstring
() - source Rebind void Rebind(const nsACString_internal&, PRUint32, PRUint32) - source Parameters nsACString_internal& <anonymous> PRUint32 startPos PRUint32 length void Rebind(const char*, const char*) - source Parameters char* start char* end BeginReading char* BeginReading
() const - source reading iterators nsReadingIterator<char>& BeginReading(nsReadingIterator<char>&...
...const char*) - source Parameters char* start char* end BeginReading char* BeginReading
() const - source reading iterators nsReadingIterator<char>& BeginReading(nsReadingIterator<char>&) const - source deprecated reading iterators Parameters nsReadingIterator<char>& iter char*& BeginReading(const char*&) const - source Parameters char*& iter EndReading char* EndReading
() const - source nsReadingIterator<char>& EndReading(nsReadingIterator<char>&) const - source Parameters nsReadingIterator<char>& iter char*& EndReading(const char*&) const - source Parameters char*& iter BeginWriting char* BeginWriting
() - source writing iterators nsWritingIterator<char>& BeginWriting(nsWritingIterator<char>&) - source deprecated writing iterators Paramete...
... iter char*& EndReading(const char*&) const - source Parameters char*& iter BeginWriting char* BeginWriting
() - source writing iterators nsWritingIterator<char>& BeginWriting(nsWritingIterator<char>&) - source deprecated writing iterators Parameters nsWritingIterator<char>& iter char*& BeginWriting(char*&) - source Parameters char*& iter EndWriting char* EndWriting
() - source nsWritingIterator<char>& EndWriting(nsWritingIterator<char>&) - source Parameters nsWritingIterator<char>& iter char*& EndWriting(char*&) - source Parameters char*& iter Data char* Data
() const - source accessors Length PRUint32 Length
() const - source IsEmpty PRBool IsEmpty
() const - source IsVoid PRBool IsVoid
() const - source IsTerminated ...
...gIterator<char>& EndWriting(nsWritingIterator<char>&) - source Parameters nsWritingIterator<char>& iter char*& EndWriting(char*&) - source Parameters char*& iter Data char* Data
() const - source accessors Length PRUint32 Length
() const - source IsEmpty PRBool IsEmpty
() const - source IsVoid PRBool IsVoid
() const - source IsTerminated PRBool IsTerminated
() const - source CharAt char CharAt(PRUint32) const - source Parameters PRUint32 i operator[] char operator[](PRUint32) const - source Parameters PRUint32 i First char First
() const - source Last char Last
() const - source CountChar PRUint32 CountChar(char) const - source Parameters char <anonymous> FindChar PRInt32 FindChar(char, PRUint32) const -...
nsDependentSubstring
Pos PRUint32 length void nsDependentSubstring(const PRUnichar*, const PRUnichar*) - source Parameters PRUnichar* start PRUnichar* end void nsDependentSubstring(const nsReadingIterator<short unsigned int>&, const nsReadingIterator<short unsigned int>&) - source Parameters nsReadingIterator<short unsigned int>& start nsReadingIterator<short unsigned int>& end void nsDependentSubstring
() - source Rebind void Rebind(const nsAString_internal&, PRUint32, PRUint32) - source Parameters nsAString_internal& <anonymous> PRUint32 startPos PRUint32 length void Rebind(const PRUnichar*, const PRUnichar*) - source Parameters PRUnichar* start PRUnichar* end BeginReading PRUnichar* BeginReading
() const - source reading iterators nsReadingIterator<short unsigned int>& ...
...nReading PRUnichar* BeginReading
() const - source reading iterators nsReadingIterator<short unsigned int>& BeginReading(nsReadingIterator<short unsigned int>&) const - source deprecated reading iterators Parameters nsReadingIterator<short unsigned int>& iter PRUnichar*& BeginReading(const PRUnichar*&) const - source Parameters PRUnichar*& iter EndReading PRUnichar* EndReading
() const - source nsReadingIterator<short unsigned int>& EndReading(nsReadingIterator<short unsigned int>&) const - source Parameters nsReadingIterator<short unsigned int>& iter PRUnichar*& EndReading(const PRUnichar*&) const - source Parameters PRUnichar*& iter BeginWriting PRUnichar* BeginWriting
() - source writing iterators nsWritingIterator<short unsigned int>& BeginWritin...
...Unichar*& iter BeginWriting PRUnichar* BeginWriting
() - source writing iterators nsWritingIterator<short unsigned int>& BeginWriting(nsWritingIterator<short unsigned int>&) - source deprecated writing iterators Parameters nsWritingIterator<short unsigned int>& iter PRUnichar*& BeginWriting(PRUnichar*&) - source Parameters PRUnichar*& iter EndWriting PRUnichar* EndWriting
() - source nsWritingIterator<short unsigned int>& EndWriting(nsWritingIterator<short unsigned int>&) - source Parameters nsWritingIterator<short unsigned int>& iter PRUnichar*& EndWriting(PRUnichar*&) - source Parameters PRUnichar*& iter Data PRUnichar* Data
() const - source accessors Length PRUint32 Length
() const - source IsEmpty PRBool IsEmpty
() const - source ...
...ator<short unsigned int>& EndWriting(nsWritingIterator<short unsigned int>&) - source Parameters nsWritingIterator<short unsigned int>& iter PRUnichar*& EndWriting(PRUnichar*&) - source Parameters PRUnichar*& iter Data PRUnichar* Data
() const - source accessors Length PRUint32 Length
() const - source IsEmpty PRBool IsEmpty
() const - source IsVoid PRBool IsVoid
() const - source IsTerminated PRBool IsTerminated
() const - source CharAt PRUnichar CharAt(PRUint32) const - source Parameters PRUint32 i operator[] PRUnichar operator[](PRUint32) const - source Parameters PRUint32 i First PRUnichar First
() const - source Last PRUnichar Last
() const - source CountChar PRUint32 CountChar(PRUnichar) const - source Par...
IAccessibleRelation
[propge...
...Index, [out] IUnknown target ); [propget] HRESULT targets([in] long maxTargets, [out, size_is(maxTargets), length_is( nTargets)] IUnknown targets, [out] long nTargets ); Methods localizedRelationType
() Returns a localized version of the relation type. [propget] HRESULT localizedRelationType( [out] BSTR localizedRelationType ); Parameters localizedRelationType Return value S_OK. nTargets
() Returns the number of targets
() for this relation. [propget] HRESULT nTargets( [out] long nTargets ); Parameters nTargets Return value S_OK. relationType
() Returns the type of the relation. [propget] HRESULT relationType( [out] BSTR relationType ); Parameters relationType The strings returned are defined @ref grpRelations "in this section of the documentation". Return value S_OK. targe...
...Returns the number of targets
() for this relation. [propget] HRESULT nTargets( [out] long nTargets ); Parameters nTargets Return value S_OK. relationType
() Returns the type of the relation. [propget] HRESULT relationType( [out] BSTR relationType ); Parameters relationType The strings returned are defined @ref grpRelations "in this section of the documentation". Return value S_OK. target
() Returns one accessible relation target. [propget] HRESULT target( [in] long targetIndex, [out] IUnknown target ); Parameters targetIndex 0 based index. target Return value E_INVALIDARG if bad [in] passed, [out] value is null. S_FALSE if there is nothing to return, [out] value is null. S_OK. targets
() Returns multiple accessible relation targets. [propget] HRESULT targets( [in] long maxT...
...S_OK. See also IAccessible2 ...
amIInstallTrigger
toolkit/mozapps/extensions/amIInstallTrigger.idlScriptable Called when an install completes or fails. 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview boolean enabled
(); boolean install(in nsIVariant aArgs, [optional] in amIInstallCallback aCallback); boolean installChrome(in PRUint32 aType, in AString aUrl, in AString aSkin); Deprecated since Gecko 2.0 boolean startSoftwareUpdate(in AString aUrl, [optional] in PRInt32 aFlags); Deprecated since Gecko 2.0 boolean updateEnabled
(); Deprecated since Gecko 2.0 Constants Retained for backwards compatibility. Constant Value Description SKIN ...
... boolean startSoftwareUpdate(in AString aUrl, [optional] in PRInt32 aFlags); Deprecated since Gecko 2.0 boolean updateEnabled
(); Deprecated since Gecko 2.0 Constants Retained for backwards compatibility. Constant Value Description SKIN 1 LOCALE 2 CONTENT 4 PACKAGE 7 Methods enabled
() Tests if installation is enabled. boolean enabled
(); Parameters None. Return value install
() Starts a new installation of a set of add-ons. boolean install( in nsIVariant aArgs, in amIInstallCallback aCallback Optional ); Parameters aArgs The add-ons to install. This should be a JS object, each property is the name of an add-on to be installed. The value of the property shoul...
...tring URL, or an object with the following properties: URL for the add-on's URL IconURL for an icon for the add-on Hash for a hash of the add-on. aCallback Optional A callback to call as each installation succeeds or fails. Return value true if the installations were successfully started. installChrome Starts installing a new add-on. This method is deprecated, please use install
() in the future. boolean installChrome( in PRUint32 aType, in AString aUrl, in AString aSkin ); Parameters aType Unused, retained for backwards compatibility. aUrl The URL of the add-on. aSkin Unused, retained for backwards compatibility. Return value true if the installation was successfully started. startSoftwareUpdate Starts installing a new add-on. boolean startSoftwareUp...
...ssfully started. startSoftwareUpdate Starts installing a new add-on. boolean startSoftwareUpdate( in AString aUrl, in PRInt32 aFlags Optional ); Parameters aUrl The URL of the add-on. aFlags Optional Unused, retained for backwards compatibility. Return value true if the installation was successfully started. updateEnabled Tests if installation is enabled. boolean updateEnabled
(); Parameters None. Return value ...
mozISpellCheckingEngine
d suggest(in wstring word,[array, size_is(count)] out wstring suggestions, out PRUint32 count); Attributes Attribute Type Description copyright wstring A string indicating the copyright of the engine. Not currently used. Read only. dictionary wstring The name of the current dictionary used by check
() and suggest
(). This will be either element from the array returned by getDictionaryList
() or an empty string if no dictionary is selected. Note: Setting this value to a value that doesn't match an existing dictionary throws a NS_ERROR_FILE_NOT_FOUND exception. When this attribute's value is changed, a "spellcheck-dictionary-update" notification is sent. If the dictionar...
...ine. Not currently used. Read only. personalDictionary mozIPersonalDictionary The personal dictionary. providesPersonalDictionary boolean Does the engine provide its own personalDictionary? Read only. providesWordUtils boolean Does the engine provide its own word utilities? Read only. Methods addDirectory
() Adds all the dictionaries in the specified directory to the spell checker. void addDirectory( nsIFile dir ); Parameters dir An nsIFile object indicating the directory from which to add dictionaries. check
() Checks a word to determine if it's spelled correctly. When this changes, the spell checker sends a "spellcheck-dictionary-update" notification. boolean check( in wstring w...
...cks a word to determine if it's spelled correctly. When this changes, the spell checker sends a "spellcheck-dictionary-update" notification. boolean check( in wstring word ); Parameters word A word to check for correct spelling. Return value Returns true if word is spelled correctly according to the dictionary attribute, and returns false if word is misspelled. getDictionaryList
() Gets the list of dictionaries. void getDictionaryList( [array, size_is(count)] out wstring dictionaries, out PRUint32 count ); Parameters dictionaries A list of dictionaries supported by this spell checker. The dictionary attribute can be set to one of these. Each dictionary name is typically but not always a locale code. count The length of dictionaries. remove...
... list of dictionaries. void getDictionaryList( [array, size_is(count)] out wstring dictionaries, out PRUint32 count ); Parameters dictionaries A list of dictionaries supported by this spell checker. The dictionary attribute can be set to one of these. Each dictionary name is typically but not always a locale code. count The length of dictionaries. removeDirectory
() Removes all the dictionaries in the specified directory from the spell checker. void removeDirectory( nsIFile dir ); Parameters dir An nsIFile object indicating the directory whose spell checkers are to be removed from the spell checker. suggest
() Gets a list of suggestions for a misspelled word. When this changes, the spell checker sends a "spellcheck-dictionary-update" notifi...
mozIStorageBindingParams
The mozIStorageBindingParams interface is used to bind values to parameters prior to calling mozIStorageStatement.executeAsync
(). storage/public/mozIStorageBindingParams.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Inherits from: nsISupports You can only create mozIStorageBindingParams objects by calling the mozIStorageBindingParamsArray.newBindingParams
(). Method overview void bindByIndex(in unsigned long aIndex, in nsIVariant aValue); void bindBlobByIndex(in unsigned long aIndex, [array, const, size_is(aValueSize)] in octet aValue, in unsigned long aValueSize); void bindDoubleByIndex(in unsigned long aIndex, in double aValue); Native code only! void bindInt32By...
...); Native code only! void bindInt64ByName(in AUTF8String aName, in long long aValue); Native code only! void bindNullByName(in AUTF8String aName); Native code only! void bindStringByName(in AUTF8String aName, in AString aValue); Native code only! void bindUTF8StringByName(in AUTF8String aName, in AUTF8String aValue); Native code only! ...
... void bindBlobByIndex( in unsigned long aIndex, [array, const, size_is(aValueSize)] in octet aValue, in unsigned long aValueSize ); Parameters aIndex The zero-based numerical index for the parameter to be bound. ...
...only!bindUTF8StringByIndex Binds a UTF8String to the specified index. void bindStringByIndex( in unsigned long aIndex, in AUTF8String aValue ); Parameters aIndex The zero-based numerical index for the parameter to be bound. This will be one less than the number used in the SQL (<code>?1</code> maps to <code>0</code>, and so on). aValue to be bound to the specified index. bindByName
() Binds a value to a parameter with the specified name. void bindByName( in AUTF8String aName, in nsIVariant aValue ); Parameters aName The name of the named index for the parameter to be bound. aValue to be bound to the specified index. bindBlobByName
() Binds a blob to the specified index. void bindBlobByName( in AUTF8String aName, [array, const, size_is(aValueSize)] in o...
mozIStorageStatementWrapper
You can then wrap that statement with a wrapper, which implements nsIXPCScriptable and provides scriptable helpers letting you execute the statement as a function, access bind variables by name as properties, etc. Firefox 3.5 note Firefox 3.5 adds support for these features directly into the mozIStorageStatement interface, so this interface is essentially deprecated. ...
...s directly into the mozIStorageStatement interface, so this interface is essentially deprecated. storage/public/mozIStorageStatementWrapper.idlScriptable Please add a summary to this article. Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Inherits from: nsISupports Method overview void initialize(in mozIStorageStatement aStatement); void reset
(); boolean step
(); void execute
(); Attributes Attribute Type Description statement mozIStorageStatement The statement that is wrapped. row mozIStorageStatementRow The current row. Throws an exception if no row is currently available. Useful only from script. The value of this is only valid while the statement is still executing, a...
.... row mozIStorageStatementRow The current row. Throws an exception if no row is currently available. Useful only from script. The value of this is only valid while the statement is still executing, and is still on the appropriate row. params mozIStorageStatementParams The parameters; these can be set in lieu of using the call notation on this. Methods initialize
() This method initializes this wrapper with aStatement. void initialize( in mozIStorageStatement aStatement ); Parameters aStatement The statement to be initialized. reset
() This method resets the wrapped statement. void reset
(); Parameters None. step
() This method steps the wrapped statement. boolean step
(); Parameters None. Return value Returns true if the stepping the wrapped...
...d initialize( in mozIStorageStatement aStatement ); Parameters aStatement The statement to be initialized. reset
() This method resets the wrapped statement. void reset
(); Parameters None. step
() This method steps the wrapped statement. boolean step
(); Parameters None. Return value Returns true if the stepping the wrapped statement was successful, otherwise returns false. execute
() This method executes the wrapped statement. void execute
(); Parameters None. See also Storage mozIStorageStatement mozIStorageStatementRow mozIStorageStatementParams ...
mozITXTToHTMLConv
Substitution unsigned long Enables conversion of smilies and non-ASCII special characters. kStructPhrase unsigned long Enables conversion of text attributes, such as converting "*some text*" to boldfaced "some text" by wrapping in the HTML <strong> element. kURLs unsigned long Enables automatic addition of hyperlinks for URLs in the text. Methods scanTXT
() Scans the specified text, applying the requested conversions and outputting HTML. wstring scanTXT( in wstring text, in unsigned long whattodo ); Parameters text The original, plain text to scan and convert into HTML. whattodo A bit field composed of the Conversion control attributes indicating what conversions to apply. Return value The HTML version of the specified string. scan...
...ans the specified text, applying the requested conversions and outputting HTML. wstring scanTXT( in wstring text, in unsigned long whattodo ); Parameters text The original, plain text to scan and convert into HTML. whattodo A bit field composed of the Conversion control attributes indicating what conversions to apply. Return value The HTML version of the specified string. scanHTML
() Scans the specified user-edited HTML, adding additional formatting that the user may not have known to do. This should correct HTML that isn't entirely standards-compliant. Warning: Don't use the kGlyphSubstitution conversion type with this method, as doing so generates HTML that is non-standard. wstring scanHTML( in wstring text, in unsigned long whattodo ); Parameters text The orig...
...itution conversion type with this method, as doing so generates HTML that is non-standard. wstring scanHTML( in wstring text, in unsigned long whattodo ); Parameters text The original, user-edited HTML. whattodo A bit field composed of the Conversion control attributes indicating what conversions to apply. Return value A normalized version of the original HTML string. citeLevelTXT
() Returns the "cite level" of the specified text; that is, it indicates how many levels of email reply quotes are used, when the text uses "quote" characters (such as ">") at the beginning of the line to indicate cite levels. unsigned long citeLevelTXT( in wstring line, out unsigned long logLineStart ); Parameters line The original line of text, which may begin with one or more cite cha...
...e of text, which may begin with one or more cite characters such as ">". logLineStart On output, this parameter is set to indicate the offset into the string of the first non-cite character. You must set this value to zero before calling this method. Return value The cite level of the quote; that is, the number of text quote characters found at the beginning of the string. findURLInPlaintext
() Returns the start and end offsets of the first URL found in a substring. void findURLInPlaintext( in wstring text, in long aLength, in long aPos, out long aStartPos, out long aEndPos ); Parameters text The string to scan for the presence of a URL. aLength The length of the buffer to scan. aPos The character offset into the string at which to begin the scan. aStartPos On re...
mozIThirdPartyUtil
This is done as follows: If aChannel is an nsIHttpChannel and has the 'forceAllowThirdPartyCookie' property set, then: If aURI is null, return false. Otherwise, find the URI of the channel, determine whether it is foreign with respect to aURI, and return. Find the URI of the channel and determine whether it ...
...channel's notification callbacks. Then: If the parent is the same as the bottommost window, and the channel has the LOAD_DOCUMENT_URI flag set, return false. This represents the case where a toplevel load is occurring and the window's URI has not yet been updated. (We have already checked that aURI is not foreign with respect to the channel URI.) Otherwise, return the result of isThirdPartyWindow
() with arguments of the channel's bottommost window and the channel URI, respectively. Therefore, both the channel's URI and each level in the window hierarchy associated with the channel is tested. For example, if aURI is "http://mail.google.com/", aChannel has a URI of "http://google.com/", and its parent is the topmost content window with a URI of "http://mozilla.com", the result will be true...
.... boolean isThirdPartyChannel( in nsIChannel aChannel, in nsIURI aURI Optional ); Parameters aChannel The channel associated with the load. aURI Optional A URI to test against. If null, the URI of the channel will be used. Return value true if aURI is third party with respect to the channel URI or any of the URIs associated with the same-type window hierarchy of the channel. isThirdPartyURI
() Determine whether two URIs are third party with respect to each other. This is determined by computing the base domain for both URIs. If they can be determined, and the base domains match, the request is defined as first party. If it cannot be determined because one or both URIs do not have a base domain (for instance, in the case of IP addresses, host aliases such as 'localhost', or a file:// U...
... the URI "http://mail.google.com/" is not third party with respect to "http://images.google.com/", but "http://mail.yahoo.com/" and "http://192.168.1.1/" are. boolean isThirdPartyURI( in nsIURI aFirstURI, in nsIURI aSecondURI ); Parameters aFirstURI Missing Description aSecondURI Missing Description Return value true if aFirstURI is third party with respect to aSecondURI. isThirdPartyWindow
() Determine whether the given window hierarchy is third party. This is done as follows: Obtain the URI of the principal associated with aWindow. Call this the 'bottom URI'. If aURI is provided, determine if it is third party with respect to the bottom URI. If so, return. Find the same-type parent window, if there is one, and its URI. Determine whether it is third party with respect to the bottom ...
GetAccessibleAbove
<< nsIAccessible Page Summary This method returns an accessible node geometrically above this one. nsIAccessible getAccessibleAbove
(); Return value Returns an accessible node geometrically above this one. ...
... << nsIAccessible Page Summary This method returns an accessible node geometrically above this one. nsIAccessible getAccessibleAbove
(); Return value Returns an accessible node geometrically above this one. ...
... << nsIAccessible Page Summary This method returns an accessible node geometrically above this one. nsIAccessible getAccessibleAbove
(); Return value Returns an accessible node geometrically above this one. ...
... << nsIAccessible Page Summary This method returns an accessible node geometrically above this one. nsIAccessible getAccessibleAbove
(); Return value Returns an accessible node geometrically above this one. ...
GetAccessibleBelow
<< nsIAccessible Page Summary This method returns an accessible node geometrically below this one. nsIAccessible getAccessibleBelow
(); Return value Returns an accessible node geometrically below this one. ...
... << nsIAccessible Page Summary This method returns an accessible node geometrically below this one. nsIAccessible getAccessibleBelow
(); Return value Returns an accessible node geometrically below this one. ...
... << nsIAccessible Page Summary This method returns an accessible node geometrically below this one. nsIAccessible getAccessibleBelow
(); Return value Returns an accessible node geometrically below this one. ...
... << nsIAccessible Page Summary This method returns an accessible node geometrically below this one. nsIAccessible getAccessibleBelow
(); Return value Returns an accessible node geometrically below this one. ...
GetAccessibleToLeft
<< nsIAccessible Page Summary This method returns an accessible node geometrically to the left of this one. nsIAccessible getAccessibleToLeft
(); Return value Returns an accessible node geometrically to the left of this one. ...
... << nsIAccessible Page Summary This method returns an accessible node geometrically to the left of this one. nsIAccessible getAccessibleToLeft
(); Return value Returns an accessible node geometrically to the left of this one. ...
... << nsIAccessible Page Summary This method returns an accessible node geometrically to the left of this one. nsIAccessible getAccessibleToLeft
(); Return value Returns an accessible node geometrically to the left of this one. ...
... << nsIAccessible Page Summary This method returns an accessible node geometrically to the left of this one. nsIAccessible getAccessibleToLeft
(); Return value Returns an accessible node geometrically to the left of this one. ...
GetAccessibleToRight
<< nsIAccessible Page Summary This method returns an accessible node geometrically to the right of this one. nsIAccessible getAccessibleToRight
(); Return value Returns an accessible node geometrically to the right of this one. ...
... << nsIAccessible Page Summary This method returns an accessible node geometrically to the right of this one. nsIAccessible getAccessibleToRight
(); Return value Returns an accessible node geometrically to the right of this one. ...
... << nsIAccessible Page Summary This method returns an accessible node geometrically to the right of this one. nsIAccessible getAccessibleToRight
(); Return value Returns an accessible node geometrically to the right of this one. ...
... << nsIAccessible Page Summary This method returns an accessible node geometrically to the right of this one. nsIAccessible getAccessibleToRight
(); Return value Returns an accessible node geometrically to the right of this one. ...
nsIAccessibleDocument
y is turned on in Gecko, there is an nsIAccessibleDocument for each document whether it is XUL, HTML or whatever. Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) You can QueryInterface to nsIAccessibleDocument from the nsIAccessible or nsIAccessNode for the root node of a document. ...
...ibleDocument for each document whether it is XUL, HTML or whatever. Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) You can QueryInterface to nsIAccessibleDocument from the nsIAccessible or nsIAccessNode for the root node of a document. ...
... URL AString The URL of the document Read only. window nsIDOMWindow The nsIDOMWindow that the document resides in. Read only. windowHandle voidPtr The window handle for the OS window the document is being displayed in. For example, in Windows you can static cast it to an HWND. Read only. Native code only! Methods getAccessibleInParentChain
() Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Returns the first accessible parent of a DOM node. Guaranteed not to return null if the DOM node is in a document. nsIAccessible getAccessibleInParentChain( in nsIDOMNode aDOMNode, in boolean aCanCreate ); Parameters aDOMNode The DOM node we need an accessible for. aCanCreate If true, this method...
...raged since it could be removed at any time. Try to avoid using it. Returns the access node cached by this document. nsIAccessNode getCachedAccessNode( in voidPtr aUniqueID ); Parameters aUniqueID The unique ID used to cache the node. This matches up with the uniqueID attribute on nsIAccessNode. Return value The nsIAccessNode cached for this particular unique ID. getNameSpaceURIForID
() The namespace for each ID that is handed back. AString getNameSpaceURIForID( in short nameSpaceID ); Parameters nameSpaceID The ID of the name space. Return value The name space for given ID. See also nsIAccessible nsIAccessibleEvent nsIAccessNode ...
nsIAccessibleHyperText
a text document, that are used to reference other documents. A typical implementation is to implement this interface on the small text object such as a paragraph of text. Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) Method overview nsIAccessibleHyperLink getLink(in long linkIndex); long getLinkIndex(in long charIndex); long getSelectedLinkIndex
(); Obsolete since Gecko 1.9 Attributes Attribute Type Description linkCount long The number of links contained within this hypertext object. Read only. Note: Renamed from links in Gecko 1.9 Methods getLink
() Retrieves the nsIAccessibleHyperLink object at the given link index. nsIAccessibleHyperLink getLink( in long linkIndex ); Parameters linkI...
...linkCount long The number of links contained within this hypertext object. Read only. Note: Renamed from links in Gecko 1.9 Methods getLink
() Retrieves the nsIAccessibleHyperLink object at the given link index. nsIAccessibleHyperLink getLink( in long linkIndex ); Parameters linkIndex 0-based index of the link that is to be retrieved. This can be retrieved via getLinkIndex
(). Return value An nsIAccessibleHyperLink object. Exceptions thrown NS_ERROR_FAILURE Indicates that the accessible is unattached from the accessible tree. NS_ERROR_INVALID_ARG The link index is invalid. getLinkIndex
() The link index at the given offset (character index). long getLinkIndex( in long charIndex ); Parameters charIndex The 0-based character index. Return value ...
... Return value Missing Description Exceptions thrown NS_ERROR_FAILURE Indicates that the accessible is unattached from the accessible tree. ...
...n long charIndex ); Parameters charIndex The 0-based character index. Return value The index of the link if it's presented on the given character index, otherwise -1. Exceptions thrown NS_ERROR_FAILURE Indicates that the accessible is unattached from the accessible tree. getSelectedLinkIndex
() Obsolete since Gecko 1.9 (Firefox 3) long getSelectedLinkIndex
(); Parameters None. Return value Missing Description Exceptions thrown NS_ERROR_FAILURE Indicates that the accessible is unattached from the accessible tree. See also nsIAccessibleHyperLink ...
nsIAsyncInputStream
Inherits from: nsIInputStream Last changed in Gecko 1.7 If an input stream is non-blocking, it may return NS_BASE_STREAM_WOULD_BLOCK when read. The caller must then wait for the stream to have some data to read. If the stream implements nsIAsyncInputStream, then the caller can use this interface to request an asynchronous notification when the stream becomes readable or closed (via the AsyncWait
() method). While this interface is almost exclusively used with non-blocking streams, it is not necessary that nsIInputStream.isNonBlocking
() return true. Nor is it necessary that a non-blocking nsIInputStream implementation also implement nsIAsyncInputStream. Method overview void asyncWait(in nsIInputStreamCallback aCallback, in unsigned long aFlags, in unsigned long aRequestedCount, in nsIEven...
... it necessary that a non-blocking nsIInputStream implementation also implement nsIAsyncInputStream. Method overview void asyncWait(in nsIInputStreamCallback aCallback, in unsigned long aFlags, in unsigned long aRequestedCount, in nsIEventTarget aEventTarget); void closeWithStatus(in nsresult aStatus); Constants Constant Value Description WAIT_CLOSURE_ONLY (1<<0) If passed to asyncWait
(), this flag overrides the default behavior, causing the OnInputStreamReady notification to be suppressed until the stream becomes closed (either as a result of closeWithStatus
()/close being called on the stream or possibly due to some error in the underlying stream). Methods asyncWait
() Asynchronously wait for the stream to be readable or closed. The notification is one-shot, meaning that each ...
...bject. It is safe to call asyncWait again from the notification handler. This method may be called at any time (even if read has not been called). In other words, this method may be called when the stream already has data to read. It may also be called when the stream is closed. If the stream is already readable or closed when asyncWait is called, then the nsIInputStreamCallback.onInputStreamReady
() event will be dispatched immediately. Otherwise, the event will be dispatched when the stream becomes readable or closed. void asyncWait( in nsIInputStreamCallback aCallback, in unsigned long aFlags, in unsigned long aRequestedCount, in nsIEventTarget aEventTarget ); Parameters aCallback This object is notified when the stream becomes ready. This parameter may be null to clear an existi...
...Wait until at least this many bytes can be read. This is only a suggestion to the underlying stream; it may be ignored. The caller may pass zero to indicate no preference. aEventTarget Specify null to receive notification on ANY thread (possibly even recursively on the calling thread, that is synchronously), or specify that the notification be delivered to a specific event target. closeWithStatus
() This method closes the stream and sets its internal status. If the stream is already closed, then this method is ignored. Once the stream is closed, the stream's status cannot be changed. Any successful status code passed to this method is treated as NS_BASE_STREAM_CLOSED, which has an effect equivalent to nsIInputStream.close
(). Note: This method exists in part to support pipes, which have both ...
nsIAuthModule
ial, out voidPtr aOutToken, out unsigned long aOutTokenLength); Constants Constant Value Description REQ_DEFAULT 0 Default behavior. REQ_MUTUAL_AUTH (1 << 0) Client and server will be authenticated. REQ_DELEGATE (1 << 1) The server is allowed to impersonate the client. The REQ_MUTUAL_AUTH flag may also need to be specified in order for this flag to take effect. Methods getNextToken
() This method is called to get the next token in a sequence of authentication steps. void getNextToken( [const] in voidPtr aInToken, in unsigned long aInTokenLength, out voidPtr aOutToken, out unsigned long aOutTokenLength ); Parameters aInToken A buffer containing the input token (For example a challenge from a server). This may be null. aInTokenLength The length of the input token. aOut...
...s aInToken A buffer containing the input token (For example a challenge from a server). This may be null. aInTokenLength The length of the input token. aOutToken If getNextToken succeeds, then aOutToken will point to a buffer to be sent in response to the server challenge. The length of this buffer is given by aOutTokenLength. The buffer at aOutToken must be recycled with a call to nsIMemory.free
(). aOutTokenLength If getNextToken succeeds, then aOutTokenLength contains the length of the buffer (number of bytes) pointed to by aOutToken. init
() This method is called to initialize an auth module. The other methods cannot be called unless this method succeeds. void init( in string aServiceName, in unsigned long aServiceFlags, in wstring aDomain, in wstring aUsername, in wstring aPas...
...ame, in wstring aPassword ); Parameters aServiceName The service name, which may be null if not applicable (For example, for NTLM, this parameter should be null). aServiceFlags A bitwise-or of the REQ_ constants (pass REQ_DEFAULT for default behavior). aDomain The authentication domain, which may be null if not applicable. aUsername The user's login name. aPassword The user's password. unwrap
() This method is used to unpack, decrypt, and verify the checksums on data returned by a server when security layers are in use. void unwrap( [const] in voidPtr aInToken, in unsigned long aInTokenLength, out voidPtr aOutToken, out unsigned long aOutTokenLength ); Parameters aInToken A buffer containing the data received from the server. aInTokenLength The length of the input token. aOutTo...
...gned long aOutTokenLength ); Parameters aInToken A buffer containing the data received from the server. aInTokenLength The length of the input token. aOutToken A buffer containing the plaintext data from the server. aOutTokenLength The length of the output token buffer. Exceptions thrown NS_ERROR_NOT_IMPLEMENTED If the underlying authentication mechanism does not support security layers. wrap
() Once a security context has been established through calls to getNextToken
() it may be used to protect data exchanged between client and server. Calls to this method are used to protect items of data to be sent to the server. void wrap( [const] in voidPtr aInToken, in unsigned long aInTokenLength, in boolean confidential, out voidPtr aOutToken, out unsigned long aOutTokenLength ); Para...
nsIAuthPrompt2
hInformation authInfo); Constants Constant Value Description LEVEL_NONE 0 The password will be sent unencrypted. No security provided. LEVEL_PW_ENCRYPTED 1 Password will be sent encrypted, but the connection is otherwise insecure. LEVEL_SECURE 2 The connection, both for password and data, is secure. Methods asyncPromptAuth
() Asynchronously prompt the user for a username and password. This has largely the same semantics as nsIAuthPrompt.promptUsernameAndPassword
(), but must return immediately after calling and return the entered data in a callback. If the user closes the dialog using a cancel button or similar, the callback's nsIAuthPromptCallback.onAuthCancelled
() method must be called. Calling nsICancelable.cancel...
... This implementation may: Coalesce identical prompts. ...
... This implementation may: Coalesce identical prompts. This means prompts that are guaranteed to want the same authentication information from the user. A single prompt will be shown; then the callbacks for all the coalesced prompts will be notified with the resulting authentication information. ...
...back, in nsISupports aContext, in PRUint32 level, in nsIAuthInformation authInfo ); Parameters aChannel The channel that requires authentication. aCallback aContext level One of the level constants. authInfo Authentication information object. The implementation should fill in this object with the information entered by the user before returning. Return value promptAuth
() Requests a username and a password. Implementations will commonly show a dialog with a username and password field, depending on flags also a domain field. Note: Exceptions thrown from this function will be treated like a return value of false. boolean promptAuth( in nsIChannel aChannel, in PRUint32 level, in nsIAuthInformation authInfo ); Parameters aChannel The channel that requi...
nsIBidiKeyboard
some magic for them. A user is a bidirectional writer if they have keyboard layouts in both left-to-right and right-to-left directions (that is users who use Arabic, Iranian (Persian), or Israel (Hebrew) keyboard layout, beside an US (English) layout.) Inherits from: nsISupports Last changed in Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) Method overview boolean isLangRTL
(); void setLangFromBidiLevel(in PRUint8 aLevel); Attributes Attribute Type Description haveBidiKeyboards boolean Indicates whether or not the system has at least one keyboard for each direction (left-to-right and right-to-left) installed. Read only. Note: This throws NS_ERROR_NOT_IMPLEMENTED if the widget layer doesn't provide this inform...
...Attribute Type Description haveBidiKeyboards boolean Indicates whether or not the system has at least one keyboard for each direction (left-to-right and right-to-left) installed. Read only. Note: This throws NS_ERROR_NOT_IMPLEMENTED if the widget layer doesn't provide this information. Currently, this is only implemented on Windows. Methods isLangRTL
() Determines if the current keyboard language is right-to-left. (supported on: win32, mac, gtk2) Note: Prior to Gecko 1.9 this method used a parameter 'out PRBool aIsRTL' to return the value. boolean isLangRTL
(); Parameters None. Return value true if the current keyboard is right-to-left, false if it is not. Exceptions thrown NS_ERROR_FAILURE If no right-to-left keyboards are installed. ...
...urrent keyboard language is right-to-left. (supported on: win32, mac, gtk2) Note: Prior to Gecko 1.9 this method used a parameter 'out PRBool aIsRTL' to return the value. boolean isLangRTL
(); Parameters None. Return value true if the current keyboard is right-to-left, false if it is not. Exceptions thrown NS_ERROR_FAILURE If no right-to-left keyboards are installed. setLangFromBidiLevel
() Sets the keyboard language to left-to-right or right-to-left. (supported on: win32) void setLangFromBidiLevel( in PRUint8 aLevel ); Parameters aLevel If odd set the keyboard to right-to-left, if even set left-to-right. Exceptions thrown NS_ERROR_FAILURE If no right-to-left keyboards are installed. Remarks Implementation Windows This implementation uses win32 API to get the ...
...he keyboard to right-to-left, if even set left-to-right. Exceptions thrown NS_ERROR_FAILURE If no right-to-left keyboards are installed. Remarks Implementation Windows This implementation uses win32 API to get the language of the keyboard layout, and the direction of those languages. Linux This implementation depends on the Gecko and GTK+ version. In the Gecko 1.8 branch, just isLangRTL
() had been implemented, and uses GDK's API to check the direction of keyboard layout, which has a problem with Hebrew language. The problem is fixed on GTK+ version 2.10.1 and 2.12. In the Gecko 1.9 branch, we are going to implement all the interface, with XKB functions for xlib and gtk2 backends. On the gtk2 backend, we will have GTK+ version checking, to use GTK+ implementations, if the problem d...
nsIBoxObject
the box relative to the screen origin, in device pixels. Read only. screenY long The y coordinate of the box relative to the screen origin, in device pixels. Read only. width long The width of the box, in CSS pixels. Read only. x long The x coordinate of the box, in CSS pixels. Read only. y long The y coordinate of the box, in CSS pixels. Read only. ...
.... width long The width of the box, in CSS pixels. Read only. x long The x coordinate of the box, in CSS pixels. Read only. y long The y coordinate of the box, in CSS pixels. Read only. ...
...Read only. y long The y coordinate of the box, in CSS pixels. Read only. ...
... Obsolete since Gecko 1.9 (Firefox 3) wstring getLookAndFeelMetric( in wstring propertyName ); Parameters propertyName Return value getProperty
() wstring getProperty( in wstring propertyName ); Parameters propertyName Return value getPropertyAsSupports
() nsISupports getPropertyAsSupports( in wstring propertyName ); Parameters propertyName Return value removeProperty
() void removeProperty( in wstring propertyName ); Parameters propertyName setProperty
() void setProperty( in wstring propertyName, in wstring propertyValue ); Parameters propertyName propertyValue setPropertyAsSupports
() void setPropertyAsSupports( in wstring propertyName, in nsISupports value ); Parameters propertyName value ...
nsICachingChannel
ntics (for JAR and plugins). Support for "pinning" cached data in the cache (for printing and save-as). Support for uniquely identifying cached data in cases when the URL is insufficient. For example a HTTP form submission. A channel may optionally implement this interface to allow clients to affect its behavior with respect to how it uses the cache service. Method overview boolean isFromCache
(); Obsolete since Gecko 2.0 Attributes Attribute Type Description cacheAsFile boolean Specifies whether or not the data should be cached to a file. This may fail if the disk cache is not present. The value of this attribute is usually only settable during the processing of a channel's OnStartRequest. The default value of this attribute depends on the particular implementation of nsICachingC...
...e key retrieved from a particular instance of nsICachingChannel could be set on another instance of nsICachingChannel provided the underlying implementations are compatible and provided the new channel instance was created with the same URI. The implementation of nsICachingChannel would be expected to use the cache entry identified by the cache token. Depending on the value of nsIRequest.loadFlags
(), the cache entry may be validated, overwritten, or simply read. The cache key may be null indicating that the URI of the channel is sufficient to locate the same cache entry. Setting a null cache key is likewise valid. cacheToken nsISupports Uniquely identifies the data in the cache. Holding a reference to this token prevents the cached data from being removed. A cache token retrieved from a p...
...D will be sent to the listener's onStopRequest in this case. This flag is set automatically when the application is offline. LOAD_ONLY_IF_MODIFIED 1 << 31 This load flag controls what happens when a document would be loaded from the cache to satisfy a call to AsyncOpen. If this attribute is set to true, then the document will not be loaded from the cache. ...
...true, then the document will not be loaded from the cache. A stream listener can check isFromCache
() to determine if the AsyncOpen will actually result in data being streamed. If this flag has been set, and the request can be satisfied via the cache, then the OnDataAvailable events will be skipped. The listener will only see OnStartRequest followed by OnStopRequest. Methods isFromCache
() Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) This method finds out whether or not this channel's data is being loaded from the cache. boolean isFromCache
(); Parameters None. Return value Returns true if this channel's data is being loaded from the cache, otherwise returns false. This value is undefined before the channel fires its OnStartRequest notific...
nsIChannelEventSink
Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Channels will try to get this interface from a channel's notificationCallbacks or, if not available there, from the loadGroup's notificationCallbacks. These methods are called before onStartRequest. Note: Prior to Gecko 2.0, redirect handling was synchronous, using the onChannelRedirect
() method. Starting in Gecko 2.0, that method no longer exists, and instead the asyncOnChannelRedirect
() method is called; this uses a callback to handle redirects asynchronously. Method overview void asyncOnChannelRedirect(in nsIChannel oldChannel, in nsIChannel newChannel, in unsigned long flags, in nsIAsyncVerifyRedirectCallback callback); void onChannelRedirect(in nsIChannel ...
...nel (This might be an HTTP 301 reponse). If this flag is not set, this is a temporary redirect. The new URI may be identical to the old one. REDIRECT_INTERNAL 1 << 2 This is an internal redirect, i.e. it was not initiated by the remote server, but is specific to the channel implementation. The new URI may be identical to the old one. Methods asyncOnChannelRedirect
() Called when a redirect occurs. This may happen due to an HTTP 3xx status code. This method notifies the sink that a redirect is about to happen, but also to gives the sink the right to veto the redirect by throwing an exception or passing a failure code in the callback. Note: Vetoing the redirect simply means that newChannel will not be opened. It is important to understand that oldChannel will c...
...ote: Vetoing the redirect simply means that newChannel will not be opened. It is important to understand that oldChannel will continue loading as if it received a response of HTTP 200, which includes notifying observers and possibly display or process content attached to the HTTP response. If the sink wants to prevent this loading it must explicitly deal with it, e.g. by calling oldChannel->Cancel
() There is a certain freedom in implementing this method: If the return-value indicates success, a callback on callback is required. This callback can be done from within asyncOnChannelRedirect
() (effectively making the call synchronous) or at some point later (making the call asynchronous). If the return value indicates that an error occurred, in which case an exception is thrown, the redirect is ...
...tmask consisting of flags from above. One of REDIRECT_TEMPORARY and REDIRECT_PERMANENT will always be set. callback Object to inform about the async result of this method. Exceptions thrown This method can throw any exception; if an exception occurs, the load will be canceled, and no network requests will occur for the new channel. The redirect will be canceled. onChannelRedirect
() Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Called when a redirect occurs. This may happen due to an HTTP 3xx status code. void onChannelRedirect( in nsIChannel oldChannel, in nsIChannel newChannel, in unsigned long flags ); Parameters oldChannel The channel that's being redirected. newChannel The new channel. This channel is n...
nsIChromeRegistry
ecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Implemented by: @mozilla.org/chrome/chrome-registry;1 as a service: var chromeRegistry = Components.classes["@mozilla.org/chrome/chrome-registry;1"] .getService(Components.interfaces.nsIChromeRegistry); Method overview void canonify(in nsIURI aChromeURL); Obsolete since Gecko 1.8 void checkForNewChrome
(); nsIURI convertChromeURL(in nsIURI aChromeURL); boolean wrappersEnabled(in nsIURI aURI); Violates the XPCOM interface guidelines Constants Constant Value Description NONE 0 PARTIAL 1 FULL 2 Methods canonify
() Obsolete since Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) ...
... boolean wrappersEnabled(in nsIURI aURI); Violates the XPCOM interface guidelines Constants Constant Value Description NONE 0 PARTIAL 1 FULL 2 Methods canonify
() Obsolete since Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Note: This method is obsolete; use convertChromeURL
() instead. Converts a chrome URL into a canonical representation by ensuring that the filename portion of the URL is included, as in chrome://package/provider/file. This is useful because chrome URLs are allowed to be specified in "shorthand", leaving the "file" portion off. In that case, the URL is expanded to chrome://package/provider/package.ext. The extension, ext, is one of: xul For a...
...pecified in "shorthand", leaving the "file" portion off. In that case, the URL is expanded to chrome://package/provider/package.ext. The extension, ext, is one of: xul For a "content" package. css For a "skin" package. dtd For a "locale" package. void canonify( in nsIURI aChromeURL ); Parameters aChromeURL The URL that is to be canonified. checkForNewChrome
() Refreshes the chrome list at runtime, looking for new packages and so forth. void checkForNewChrome
(); Parameters None. convertChromeURL
() Resolves a chrome URL to an loadable URI using the information in the registry. A new nsIURI is returned; the original is left unmodified. This lets you take a non-canonical chrome URI, such as chrome://package/provider/file, and convert it into a canonical o...
...ion, ext, is one of: xul For a "content" package. css For a "skin" package. dtd For a "locale" package. nsIURI convertChromeURL( in nsIURI aChromeURL ); Parameters aChromeURL The URL that is to be converted. Return value A new nsIURI object containing the loadable URI for the specified chrome URL. Violates the XPCOM interface guidelines wrappersEnabled
() Returns whether XPCNativeWrappers are enabled for the specified URI. boolean wrappersEnabled( in nsIURI aURI ); Parameters aURI The URI for which to determine if XPCNativeWrappers are enabled. Return value true if XPCNativeWrappers are enabled for the specified URI; otherwise false. See also Chrome Registration ...
nsIClipboardDragDropHooks
. Adding the same hook to the same window will not add a second call. Each hook can only be called once per user action/api. Not all hooks are guaranteed to be called. If there are multiple hooks set for a window, any of them has an opportunity to cancel the action so no further processing will occur. If any errors occur (without setting the boolean result) the default action will occur. ...
...boolean allowDrop( in nsIDOMEvent event, in nsIDragSession session ); Parameters event The DOM event (drag gesture). session The drag session from which client can get the flavors present or the actual data. ...
...rameters event The DOM event (drag gesture). session The drag session from which client can get the flavors present or the actual data. Return value true indicates to the Operating System that if a drop does happen on this browser, it will be accepted. Otherwise, false to indicates to the Operating System that drop is not allowed. On win32, this will change the cursor to "reject". allowStartDrag
() Prevents the drag from starting. boolean allowStartDrag( in nsIDOMEvent event ); Parameters event The DOM event (drag gesture). Return value true if the drag can proceed. Otherwise, false to show the drag is canceled (Does not go to Operating System). onCopyOrDrag
() Alters the flavors or data presented to the OS. Used for drag and copy actions. Because this can be called many times, it is hi...
.... boolean onCopyOrDrag( in nsIDOMEvent aEvent, in nsITransferable trans ); Parameters aEvent The DOM event (drag drop). null if triggered by copy. trans The transferable holding the list of flavors and the data for each flavor. Return value true to indicate that copy/drag can proceed. Otherwise, false to indicate that the copy/drag is canceled, does not go to Operating System. onPasteOrDrop
() Provide an alternative action to the built-in behavior when something is dropped on the browser or in an editor. boolean onPasteOrDrop( in nsIDOMEvent event, in nsITransferable trans ); Parameters event The DOM event (drag drop); null if triggered by paste. trans The transferable holding the list of flavors and the data for each flavor. Return value true to indicate the action was handled,...
nsICookiePermission
ss's access default value ACCESS_ALLOW 1 nsCookieAccess's access allow value ACCESS_DENY 2 nsCookieAccess's access deny value ACCESS_SESSION 8 Additional values for nsCookieAccess, which are not directly used by any methods on this interface, but are nevertheless convenient to define here. These may be relocated somewhere else if we ever consider freezing this interface. Methods canAccess
() Tests whether or not the given URI/channel may access the cookie database, either to set or get cookies. nsCookieAccess canAccess( in nsIURI aURI, in nsIURI aFirstURI, Obsolete since Gecko 1.9 in nsIChannel aChannel ); Parameters aURI The URI trying to access cookies. aFirstURI The URI initiated by the user that resulted in aURI being loaded. aChannel The channel corresponding to aURI. R...
.... nsCookieAccess canAccess( in nsIURI aURI, in nsIURI aFirstURI, Obsolete since Gecko 1.9 in nsIChannel aChannel ); Parameters aURI The URI trying to access cookies. aFirstURI The URI initiated by the user that resulted in aURI being loaded. aChannel The channel corresponding to aURI. Return value One of the nsCookieAccess values: ACCESS_DEFAULT, ACCESS_ALLOW, or ACCESS_DENY. canSetCookie
() Tests whether or not the given URI/channel may set a specific cookie. This method is always preceded by a call to canAccess
(). It may modify the isSession and expiry attributes of the cookie via the aIsSession and aExpiry parameters, in order to limit or extend the lifetime of the cookie. This is useful, for instance, to downgrade a cookie to session-only if it fails to meet certain criteria. boo...
... canSetCookie is invoked, this is the current isSession attribute of the cookie. canSetCookie may leave this value unchanged to preserve this attribute of the cookie. aExpiry When canSetCookie is invoked, this is the current expiry time of the cookie. canSetCookie may leave this value unchanged to preserve this attribute of the cookie. Return value true if the cookie can be set. getOriginatingURI
() Determines the originating URI for a load given a channel, for third-party cookie blocking. This is done by leveraging the loadgroup of the channel to find the root content docshell, and the URI associated with its principal. If the root content docshell or its principal's URI cannot be obtained, this method will throw. nsIURI getOriginatingURI( in nsIChannel aChannel ); Parameters aChannel T...
...is done by leveraging the loadgroup of the channel to find the root content docshell, and the URI associated with its principal. If the root content docshell or its principal's URI cannot be obtained, this method will throw. nsIURI getOriginatingURI( in nsIChannel aChannel ); Parameters aChannel The channel for the load trying to get or set cookies. Return value The originating URI. setAccess
() Sets cookie access permissions for the given URI. This may result in other URIs being blocked as well, such as URIs that share the same host name. void setAccess( in nsIURI aURI, in nsCookieAccess aAccess ); Parameters aURI The URI to block. aAccess The new cookie access permissions for the URI. See also nsICookie nsICookie2 nsICookieManager nsICookieManager2 ...
nsICookieService
I aURI, in nsIURI aFirstURI, in nsIPrompt aPrompt, in string aCookie, in string aServerTime, in nsIChannel aChannel); Attributes Attribute Type Description cookieIconIsVisible boolean This attribute really doesn't belong on this interface. CVS blame will tell you why it is here. It remains until we can find a better home for it. Methods getCookieString
() Get the complete cookie string associated with the URI. string getCookieString( in nsIURI aURI, in nsIChannel aChannel ); Parameters aURI The URI of the document for which cookies are being queried. aChannel The channel used to load the document. this parameter may be null, but it is strongly recommended that a non-null value be provided to ensure that the cookie privacy prefere...
...I aURI, in nsIChannel aChannel ); Parameters aURI The URI of the document for which cookies are being queried. aChannel The channel used to load the document. this parameter may be null, but it is strongly recommended that a non-null value be provided to ensure that the cookie privacy preferences are honored. Return value Returns the resulting cookie string. getCookieStringFromHttp
() Get the complete cookie string associated with the URI. Note: This function is redundant and will most likely be removed in a future revision of this interface. getCookieString
() will query the documentURI property off of nsIHttpChannelInternal if supported, so getCookieString
() can be used in place of this method. string getCookieStringFromHttp( in nsIURI aURI, in nsIURI aFirstURI, ...
...ed. aFirstURI The URI that the user originally typed in or clicked on to initiate the load of the document referenced by aURI. aChannel The channel used to load the document. this parameter may be null, but it is strongly recommended that a non-null value be provided to ensure that the cookie privacy preferences are honored. Return value Returns the resulting cookie string. setCookieString
() Set the cookie string associated with the URI. Note: Should be able to allow null aPrompt, since nsIPrompt can be queried from aChannel. void setCookieString( in nsIURI aURI, in nsIPrompt aPrompt, in string aCookie, in nsIChannel aChannel ); Parameters aURI The URI of the document for which cookies are being queried. aPrompt The prompt to use for all user-level cookie not...
... aURI The URI of the document for which cookies are being queried. aPrompt The prompt to use for all user-level cookie notifications. aCookie The cookie string to set. aChannel The channel used to load the document. this parameter may be null, but it is strongly recommended that a non-null value be provided to ensure that the cookie privacy preferences are honored. setCookieStringFromHttp
() Set the cookie string and expires associated with the URI. Note: This function is redundant and will most likely be removed in a future revision of this interface. setCookieString
() will query the documentURI property off of nsIHttpChannelInternal if supported, and setCookieString
() could also query the Date header from the channel if aChannel supports nsIHttpChannel. void setCookieStringFrom...
nsIDOMHTMLAudioElement
The nsIDOMHTMLAudioElement interface is used to implement the HTML5 <audio> element. dom/interfaces/html/nsIDOMHTMLAudioElement.idlScriptable Please add a summary to this article. Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Inherits from: nsIDOMHTMLMediaElement Method overview unsigned long long mozCurrentSampleOffset
(); void mozSetup(in PRUint32 channels, in PRUint32 rate); [implicit_jscontext] unsigned long mozWriteAudio(in jsval data); Methods mozCurrentSampleOffset
() Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in...
...ot on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. Returns the current offset of the audio stream, specified as the number of samples that have played since the beginning of the stream. unsigned long long mozCurrentSampleOffset
(); Parameters None. Return value An unsigned 64-bit value indicating how many audio samples have been played since the stream began playing. mozSetup
() Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the b...
...ementations and the behavior may change in the future. Sets up the audio stream for writing. void mozSetup( in PRUint32 channels, in PRUint32 rate ); Parameters channels The number of audio channels the audio stream should use. Specify 1 for mono or 2 for stereo. rate The sampling rate to use on the stream, in samples per second. For example, specify 44100 for 44.1kHz. ...
...NS_ERROR_DOM_TYPE_MISMATCH_ERR The data isn't a valid data type (an array or typed array of numeric values). NS_ERROR_DOM_INDEX_SIZE_ERR The number of samples specified doesn't divide evenly across the number of channels; you must provide exactly the same number of samples for all channels. ...
nsIDOMOfflineResourceList
esourceList.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Inherits from: nsISupports Method overview void mozAdd(in DOMString uri); boolean mozHasItem(in DOMString uri); DOMString mozItem(in unsigned long index); void mozRemove(in DOMString uri); void swapCache
(); void update
(); Attributes Attribute Type Description mozItems nsIDOMOfflineResourceList The list of dynamically-managed entries in the offline resource list. Read only. mozLength unsigned long The number of entries in the dynamically managed offline resource list. Read only. onchecking nsIDOMEventListener An event lis...
... in the process of being updated. CHECKING 2 The application cache manifest is being fetched and checked for updates. DOWNLOADING 3 Resources are being downloaded to be added to the cache. UPDATEREADY 4 There is a new version of the application cache available. OBSOLETE 5 The application cache group is now obsolete. Methods mozAdd
() Adds an item to the dynamically managed entries. The resource will be fetched and added to the application cache. void mozAdd( in DOMString uri ); Parameters uri The URI of the resource to add to the list. mozHasItem Returns a Boolean value indicating whether or not the specified URI represents a resource that's in the application cache's list. Note: This method has been deprecat...
...tem at the specific offset into the list of cached resources. Note: This method is deprecated in Firefox 3.5; you should instead access the list directly using the items attribute. DOMString mozItem( in unsigned long index ); Parameters index The index of the cached item whose URI should be returned. Return value An DOMString containing the URI of the specified resource. mozRemove
() Removes an item from the list of dynamically managed entries. If this was the last reference to the given URI in the application cache, the cache entry is removed. void mozRemove( in DOMString uri ); Parameters uri The URI of the item to remove from the list. swapCache
() Swaps in the newest version of the application cache. The newest version of resources are updated on first refr...
...tring uri ); Parameters uri The URI of the item to remove from the list. swapCache
() Swaps in the newest version of the application cache. The newest version of resources are updated on first refresh. This means already loaded resources should only update after a page refresh. Note: Versioned application caches are not yet supported; this method will throw an exception. void swapCache
(); Parameters None. update
() Begins the application cache update process. This will check for a new cache manifest but will not tell the browser to use the updated cache. void update
(); Parameters None. See also Offline resources in Firefox nsIApplicationCache nsIApplicationCacheContainer nsIApplicationCacheService nsIApplicationCacheChannel nsIApplicationCacheNamespace ...
nsIDOMXPathEvaluator
Note: Prior to Gecko 1.9, you could call this method on documents other than the one you planned to run the XPath against; starting with Gecko 1.9, however, you must call it on the same document. nsIDOMXPathExpression createExpression( in DOMString expression, in nsIDOMXPathNSResolver resolver ); Param...
... on documents other than the one you planned to run the XPath against; starting with Gecko 1.9, however, you must call it on the same document. nsIDOMXPathExpression createExpression( in DOMString expression, in nsIDOMXPathNSResolver resolver ); Parameters expression A string representing the XPath to be created. 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 XPa...
...fied 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 resolver. evaluate
() Evaluate the specified XPath expression. nsISupports evaluate( in DOMString expression, in nsIDOMNode contextNode, in nsIDOMXPathNSResolver resolver, in unsigned short type, in nsISupports result ); Parameters expression A string representing the XPath to be evaluated. contextNode A DOM Node to evaluate the XPath expression against. To evaluate against a whole document...
...Node contextNode, in nsIDOMXPathNSResolver resolver, in unsigned short type, in nsISupports result ); Parameters expression A string representing the XPath to be evaluated. contextNode A DOM Node to evaluate the XPath expression against. To evaluate against a whole document, use the document.documentElement. 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. type A number that corresponds to one of the type constants of nsIXPathResult. result An existing nsIXPathResult to use for the result. Using null will create a new nsIXPathResult. Return value An XPath result. See also Introduction to usi...
nsIDOMXULSelectControlElement
getItemAtIndex(in long index); nsIDOMXULSelectControlItemElement insertItemAt(in long index, in DOMString label, in DOMString value); nsIDOMXULSelectControlItemElement removeItemAt(in long index); Attributes Attribute Type Description itemCount unsigned long Read only. ...
...lectControlItemElement removeItemAt(in long index); Attributes Attribute Type Description itemCount unsigned long Read only. ...
...ng Read only. ...
... appendItem
() nsIDOMXULSelectControlItemElement appendItem( in DOMString label, in DOMString value ); Parameters label value Return value getIndexOfItem
() long getIndexOfItem( in nsIDOMXULSelectControlItemElement item ); Parameters item Return value getItemAtIndex
() nsIDOMXULSelectControlItemElement getItemAtIndex( in long index ); Parameters index Return value insertItemAt
() nsIDOMXULSelectControlItemElement insertItemAt( in long index, in DOMString label, in DOMString value ); Parameters index label value Return value removeItemAt
() nsIDOMXULSelectControlItemElement removeItemAt( in long index ); Parameters index Return value ...
nsIDialogParamBlock
ng( in PRInt32 inIndex ); void SetInt( in PRInt32 inIndex, in PRInt32 inInt ); void SetNumberStrings( in PRInt32 inNumStrings ); void SetString( in PRInt32 inIndex, in wstring inString); Attributes Attribute Type Description objects nsIMutableArray A place where you can store an nsIMutableArray to pass nsISupports. Methods GetInt
() Get a previously set integer. PRInt32 GetInt( in PRInt32 inIndex ); Parameters inIndex The index of the integer to get. Must be in the range 0..7. Return value The previously set integer, or 0 if no integer has been previously set at that index. GetString
() Get a previously set string. wstring GetString( in PRInt32 inIndex ); Parameters inIndex The index of the string to ...
...Default is 16. ...
...be in the range 0..15 unless SetNumberStrings was called. Return value The string at the given index, or the empty string if no string has previously been set at that index. SetInt
() void SetInt( in PRInt32 inIndex, in PRInt32 inInt ); Parameters inIndex The index of the integer to set. Must be in the range 0..7. inInt The integer to set at the given index. SetNumberStrings
() Set the maximum number of strings to pass. Default is 16. Use before setting any string (if you want to change it from the default). This method can only be called once. ...
...Must be in the range 0..15 unless SetNumberStrings was called. ...
nsIDictionary
n Firefox 3.5; use Dict.jsm instead. See bug 668424 for further information. Method overview boolean hasKey(in string key); void getKeys(out PRUint32 count, [retval, array, size_is(count)] out string keys); nsISupports getValue(in string key); void setValue(in string key, in nsISupports value); nsISupports deleteValue(in string key); void clear
(); Methods hasKey
() Check if a given key is present in the dictionary. boolean hasKey( in string key ); Parameters key Key to check for. Return value true if present, false if absent. getKeys
() Retrieve all keys in the dictionary. void getKeys( out PRUint32 count, [retval, array, size_is(count)] out string keys ); Return value Array of all keys, unsorted. ge...
...If the key is already present, the new value replaces the old one. ...
...t PRUint32 count, [retval, array, size_is(count)] out string keys ); Return value Array of all keys, unsorted. getValue
() Find the value indicated by the key. nsISupports getValue( in string key ); Parameters key The lookup key indicating the value. Return value The value associated with the specified key. If the key doesn't exist, NS_ERROR_FAILURE is returned. setValue
() Add the key-value pair to the dictionary. If the key is already present, the new value replaces the old one. void setValue( in string key, in nsISupports value ); Parameters key The key by which the value can be accessed. value The value to store. deleteValue
() Find the value indicated by the key. nsISupports deleteValue( in string key ); Parameters ...
...n nsISupports value ); Parameters key The key by which the value can be accessed. value The value to store. deleteValue
() Find the value indicated by the key. nsISupports deleteValue( in string key ); Parameters key The key indicating the pair to be removed. Return value The removed value. If the key doesn't exist, NS_ERROR_FAILURE will be returned. clear
() Delete all key-value pairs from the dictionary. void clear
(); Parameters None. ...
nsIDirectoryIterator
The nsIDirectoryIterator interface provides a way to iterate over the entries in a directory. xpcom/obsolete/nsIFileSpec.idlScriptable Please add a summary to this article. ...
... The nsIDirectoryIterator interface provides a way to iterate over the entries in a directory. xpcom/obsolete/nsIFileSpec.idlScriptable Please add a summary to this article. ...
...s in a directory. xpcom/obsolete/nsIFileSpec.idlScriptable Please add a summary to this article. ...
...(Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Inherits from: nsISupports Method overview void init(in nsIFileSpec parent, in boolean resolveSymlink); boolean exist
(); void next
(); Attributes Attribute Type Description currentSpec nsIFileSpec init
() void init( in nsIFileSpec parent, in boolean resolveSymlink ); Parameters parent resolveSymlink exist
() boolean exists
(); next
() void next
(); ...
nsIDispatchSupport
See nsIActiveXSecurityPolicy for list of flags. unsigned long getHostingFlags( in string aContext ); Parameters aContext Ret...
... classExists); boolean isObjectSafeForScripting(in voidPtr theObject, in nsIIDRef id); void JSVal2COMVariant(in jsval var, out COMVARIANT comvar); Methods COMVariant2JSVal
() Converts a COM Variant to a jsval. void COMVariant2JSVal( in COMVARIANTPtr comvar, out jsval val ); Parameters comvar The COM Variant to be converted. val The jsval to receive the converted value. getHostingFlags
() Return the ActiveX security and hosting flags. See nsIActiveXSecurityPolicy for list of flags. unsigned long getHostingFlags( in string aContext ); Parameters aContext Return value isClassMarkedSafeForScripting
() Test if the specified class is marked safe for scripting. boolean isClassMarkedSafeForScripting( in nsCIDRef cid, out boolean classExists ); Parameters cid The nsID represen...
...tring aContext ); Parameters aContext Return value isClassMarkedSafeForScripting
() Test if the specified class is marked safe for scripting. boolean isClassMarkedSafeForScripting( in nsCIDRef cid, out boolean classExists ); Parameters cid The nsID representation of the CLSID to test. classExists Returns containing PR_FALSE if the class is not registered. Return value isClassSafeToHost
() Test if the class is safe to host. boolean isClassSafeToHost( in JSContextPtr cx, in nsCIDRef cid, in boolean capsCheck, out boolean classExists ); Parameters cx cid capsCheck classExists Returns containing PR_FALSE if the class is not registered. Return value isObjectSafeForScripting
() Test if the instantiated object is safe for scripting on the specified interface. boolean isObje...
...id capsCheck classExists Returns containing PR_FALSE if the class is not registered. Return value isObjectSafeForScripting
() Test if the instantiated object is safe for scripting on the specified interface. boolean isObjectSafeForScripting( in voidPtr theObject, in nsIIDRef id ); Parameters theObject The object to test (an IUnknown cast into a void *). id Return value JSVal2COMVariant
() Converts a jsval to a COM Variant. void JSVal2COMVariant( in jsval var, out COMVARIANT comvar ); Parameters var The jsval to be converted. comvar The COM Variant to receive the converted value. ...
nsIEventListenerService
ure); void removeSystemEventListener(in nsIDOMEventTarget target, in DOMString type, in nsIDOMEventListener listener, in boolean useCapture); Attributes Attribute Type Description systemEventGroup nsIDOMEventGroup Returns system event group. Read only. Obsolete since Gecko 7.0 Methods getEventTargetChainFor
() Returns an array of event targets indicating all the targets that will receive the same events that are delivered to the specified target. aEventTarget will be at index 0. The objects are the ones that would be used as event.currentTarget while dispatching an event to aEventTarget. Note: Some events, especially 'load', may actually have a shorter event target chain than what this methods returns.
...rget, [optional] out unsigned long aCount, [retval, array, size_is(aCount)] out nsIDOMEventTarget aOutArray ); Parameters aEventTarget The nsIDOMEventTarget for which to return the event target chain. aCount On return, contains the number of elements in the returned array. aOutArray The array into which to store the event targets. getListenerInfoFor
() Returns an array of nsIEventListenerInfo objects describing everyone listening to the specified event target. If aEventTarget doesn't have any listeners, this returns null. void getListenerInfoFor( in nsIDOMEventTarget aEventTarget, [optional] out unsigned long aCount, [retval, array, size_is(aCount)] out nsIEventListenerInfo aOutArray ); Parameters aEventTarget The nsIEvent...
...et, [optional] out unsigned long aCount, [retval, array, size_is(aCount)] out nsIEventListenerInfo aOutArray ); Parameters aEventTarget The nsIEventTarget for which to obtain a list of listeners. aCount On return, the number of returned listener descriptors. aOutArray An array of nsIEventListenerInfo objects describing the listeners. hasListenersFor
() Returns true if a event target has any listener for the given type. boolean hasListenersFor( in nsIDOMEventTarget aEventTarget, in DOMString aType ); Parameters aEventTarget The nsIDOMEventTarget for which to check if this has any listener for aType. aType An event name. addSystemEventListener
() Add a system-group eventlistener to a event target. System-group ...
...ng type, in nsIDOMEventListener listener, in boolean useCapture ); Parameters target The nsIDOMEventTarget for the event target to listen an event. type The event name to listen. listener The nsIDOMEventListener which listens the event. useCapture True if to listen the event in capture phase, otherwise, false. removeSystemEventListener
() Remove a system-group eventlistener from a event target. void removeSystemEventListener( in nsIDOMEventTarget target, in DOMString type, in nsIDOMEventListener listener, in boolean useCapture ); Parameters target The nsIDOMEventTarget for the event target listening the event. type The listening event name. listener The nsIDOMEventListener which...
nsIEventTarget
o this target from any thread by calling the dispatch method. Implement this interface in order to support receiving events from other threads. ...
...nCurrentThread
(); void postEvent(in PLEventPtr aEvent); Native code only! Obsolete since Gecko 1.9 Constants Dispatch flags Constant Value Description DISPATCH_NORMAL 0 This flag specifies the default mode of event dispatch, whereby the event is simply queued for later processing. When this flag is specified, dispatch
() returns immediately after the event is queued. DISPATCH_SYNC 1 This flag specifies the synchronous mode of event dispatch, in which the dispatch
() method does not return until the event has been processed. Note: Passing this flag to dispatch may have the side-effect of causing other events on the current thread to be processed while waiting for the gi...
...This function may be called from any thread, and it may be called re-entrantly. void dispatch( in nsIRunnable event, in unsigned long flags ); Parameters event The event to dispatch. ...
...flags ); Parameters event The event to dispatch. flags The dispatch flags modifying the event. Exceptions thrown NS_ERROR_UNEXPECTED Indicates that the thread is shutting down and has finished processing events, so this event would never run and has not been dispatched. NS_ERROR_INVALID_ARG Indicates that event is null. isOnCurrentThread
() Check to see if this event target is associated with the current thread. boolean isOnCurrentThread
(); Parameters None. Return value Returns true if events dispatched to this event target will run on the current thread (that is, the thread calling this method). If events dispatched to this target will be processed on another thread, returns false. Native code only!postEvent Obsolete since Gecko...
nsIFeedTextConstruct
ented by: @mozilla.org/feed-textconstruct;1, but users usually don't need to create instances of this directly. Various other feed-related interfaces, such as nsIFeed, nsIFeedEntry, and nsIFeedContainer have attributes that return objects implementing nsIFeedTextConstruct. Method overview nsIDOMDocumentFragment createDocumentFragment(in nsIDOMElement element); AString plainText
(); Attributes Attribute Type Description base nsIURI If the text construct contains HTML or XHTML, relative references in the content should be resolved against this base URI. lang AString The language of the text (such as "en-US" for U.S. English). text AString The actual text content. This string may contain markup if the type is...
...the content should be resolved against this base URI. lang AString The language of the text (such as "en-US" for U.S. English). text AString The actual text content. This string may contain markup if the type is either "html" or "xhtml". type AString The type of content described; one of "text", "html", or "xhtml". ...
... Return value The plain text version of the text construct's contents. If the type attribute is "text", this method returns the value of the text attribute unchanged. ...
... Return value The plain text version of the text construct's contents. ...
nsIFormHistory2
in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) Note: This interface provides no means to access stored values. Stored values are used by the FormFillController to generate autocomplete matches. Method overview void addEntry(in AString name, in AString value); boolean entryExists(in AString name, in AString value); boolean nameExists(in AString name); void removeAllEntries
(); void removeEntriesByTimeframe(in long long aBeginTime, in long long aEndTime); void removeEntriesForName(in AString name); void removeEntry(in AString name, in AString value); Attributes Attribute Type Description DBConnection mozIStorageConnection Returns the underlying DB connection the form history module is using. Read only. hasEntries boolean Returns true if the form histo...
...ginTime, in long long aEndTime); void removeEntriesForName(in AString name); void removeEntry(in AString name, in AString value); Attributes Attribute Type Description DBConnection mozIStorageConnection Returns the underlying DB connection the form history module is using. Read only. hasEntries boolean Returns true if the form history has any entries. Read only. Methods addEntry
() Adds a name and value pair to the form history. void addEntry( in AString name, in AString value ); Parameters name value entryExists
() Gets whether a name and value pair exists in the form history. boolean entryExists( in AString name, in AString value ); Parameters name value Return value nameExists
() Returns true if there is no entry that is paired with a name. boolean nameE...
...ame, in AString value ); Parameters name value entryExists
() Gets whether a name and value pair exists in the form history. boolean entryExists( in AString name, in AString value ); Parameters name value Return value nameExists
() Returns true if there is no entry that is paired with a name. boolean nameExists( in AString name ); Parameters name Return value removeAllEntries
() Removes all entries in the entire form history. void removeAllEntries
(); Parameters None. removeEntriesByTimeframe
() Removes entries that were created between the specified times. void removeEntriesByTimeframe( in long long aBeginTime, in long long aEndTime ); Parameters aBeginTime The beginning of the timeframe, in microseconds. aEndTime The end of the timeframe, in microseconds. removeE...
...entries in the entire form history. void removeAllEntries
(); Parameters None. removeEntriesByTimeframe
() Removes entries that were created between the specified times. void removeEntriesByTimeframe( in long long aBeginTime, in long long aEndTime ); Parameters aBeginTime The beginning of the timeframe, in microseconds. aEndTime The end of the timeframe, in microseconds. removeEntriesForName
() Removes all entries that are paired with a name. void removeEntriesForName( in AString name ); Parameters name removeEntry
() Removes a name and value pair from the form history. void removeEntry( in AString name, in AString value ); Parameters name value ...
nsIIDNService
This combines two operations: running the RFC 3490 "ToUnicode" operation on the original string, then converting the resulting Unicode string into UTF-8 format. AUTF8String convertACEtoUTF8( in ACString input ); Parameters input The ACE encoded hostname to convert into UTF-8 format. Ret...
...returning a UTF-8 format string. This combines two operations: running the RFC 3490 "ToUnicode" operation on the original string, then converting the resulting Unicode string into UTF-8 format. AUTF8String convertACEtoUTF8( in ACString input ); Parameters input The ACE encoded hostname to convert into UTF-8 format. Return value The UTF-8 encoded equivalent of the hostname. convertToDisplayIDN
() Normalizes a hostname into UTF-8 format if the hostname is in the IDN whitelist. If the hostname isn't in the whitelist, it's converted into ACE format. The resulting string is useful for display purposes, and ensures that the encoding is consistent with nsIURI.GetHost
(). AUTF8String convertToDisplayIDN( in AUTF8String input, out boolean isASCII ); Parameters input The string to convert to ...
...useful for display purposes, and ensures that the encoding is consistent with nsIURI.GetHost
(). AUTF8String convertToDisplayIDN( in AUTF8String input, out boolean isASCII ); Parameters input The string to convert to display format. isASCII On return, this is set to true if the result is ASCII or ACE encoded; otherwise it's false. Return value The display formatted hostname. convertUTF8toACE
() Converts the specified hostname from UTF-8 to ACE format, using the IDNA "ToASCII" algorithm. ACString convertUTF8toACE( in AUTF8String input ); Parameters input The hostname to convert to ACE format. Return value The ACE encoded version of the hostname. isACE
() Determines whether or not the specified hostname is ACE encoded. boolean isACE( in ACString input ); Parameters input The strin...
...This is useful if you need to normalize a hostname separately from converting it to display format. ...
nsIINIParser
xpcom/ds/nsIINIParser.idlScriptable An instance of nsIINIParser can be used to read values from an INI file. Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Typically, you'll create an nsIINIParser object by calling nsIINIParserFactory.createINIParser
(). Also, if you need to write to an INI file, use nsIINIParserWriter. nsIUTF8StringEnumerator getKeys(in AUTF8String aSection); nsIUTF8StringEnumerator getSections
(); AUTF8String getString(in AUTF8String aSection, in AUTF8String aKey); Methods getKeys
() Returns an nsIUTF8StringEnumerator providing the keys available within the specified section of the INI file. nsIUTF8StringEnumerator getKeys( in AUTF8String aSection ); Parameters aSecti...
...ng aKey); Methods getKeys
() Returns an nsIUTF8StringEnumerator providing the keys available within the specified section of the INI file. nsIUTF8StringEnumerator getKeys( in AUTF8String aSection ); Parameters aSection The name of the section whose keys you wish to enumerate. Return value An nsIUTF8StringEnumerator object that can be used to access the section's keys. getSections
() Returns an nsIUTF8StringEnumerator providing a list of the sections available within the INI file. nsIUTF8StringEnumerator getSections
(); Parameters None. Return value An nsIUTF8StringEnumerator object that can be used to access the sections in the INI file. getString
() Returns the string value for the specified key within a particular section of the INI file. AUTF8String getString( in AUTF8St...
...faces.nsIINIParserFactory ); var iniParser = iniFact.createINIParser(iniFile); try { return iniParser.getString(section,prop); } catch(e) { return undefined; } } // Usage: var lang = getIniValue(file,"Setting","Language"); Enumerating sections This example gets a list of all the sections in the INI file. // get all sections in the ini file var sectEnum = iniParser.getSections
(); // save the sections in an array var sections = []; while (sectEnum && sectEnum.hasMore
()) { var section = sectEnum.getNext
(); // add an array entry for each section sections.push(section); } Enumerating keys This example shows how to fetch the values for all the keys in the section named "Setting". // get all keys for the "Setting" section var keysEnum = iniParser.getKeys("Setting"); // ...
...e
()) { var section = sectEnum.getNext
(); // add an array entry for each section sections.push(section); } Enumerating keys This example shows how to fetch the values for all the keys in the section named "Setting". // get all keys for the "Setting" section var keysEnum = iniParser.getKeys("Setting"); // save the keys and values in an object var keys = {}; while (keysEnum && keysEnum.hasMore
()) { var key = keysEnum.getNext
(); // create a property for each key and assing the ini value. keys[key] = iniParser.getString("Setting", key); } See Also nsIINIParserFactory nsIINIParserWriter ...
nsIINIParserWriter
that allow writing to INI-format configuration files. INI files contain zero or more sections, denoted by a name in square brackets, followed by zero or more lines of text with a property name on the left, then an equals sign ("="), then the value of the property. To create an nsIINIParserWriter object, you use the nsIINIParserFactory interface to create a parser, then nsISupports.QueryInterface
() that to get an nsIINIParserWriter, like this: let writer = Components.classes["@mozilla.org/xpcom/ini-processor-factory;1"]. .getService(Components.interfaces.nsIINIParserFactory) .createINIParser(someLocalFile) .QueryInterface(Components.interfaces.nsIINIParserWriter); Here, someLocalFile is an nsIFile based object, such as ...
... .getService(Components.interfaces.nsIINIParserFactory) .createINIParser(someLocalFile) .QueryInterface(Components.interfaces.nsIINIParserWriter); Here, someLocalFile is an nsIFile based object, such as an nsILocalFile. This indicates the file into which the INI data will be written. Once the writer object is created, you can use the setString
() method to set the value of a property within a given section; the section is created if it hasn't been yet. The sections are built in memory before the text of the INI file is generated, so you can add properties to the file in any order, regardless of section. When you're done and ready to write the INI file to disk, call the writeFile
() method. Method overview void setString(in AUT...
... of section. When you're done and ready to write the INI file to disk, call the writeFile
() method. Method overview void setString(in AUTF8String aSection, in AUTF8String aKey, in AUTF8String aValue); void writeFile([optional] in nsIFile aINIFile, [optional] in unsigned long aFlags); Constants File writing constants These constants are specified when calling writeFile
(), in order to change its behavior. Constant Value Description WRITE_UTF16 0x1 Windows and the NSIS installer code sometimes expect INI files to be in UTF-16 encoding. On Windows only, this flag to writeFile
() can be used to change the encoding from its default UTF-8. Methods setString
() Set the value of a property string for a particular section and key. v...
... void writeFile( in nsIFile aINIFile, Optional in unsigned long aFlags Optional ); Parameters aINIFile Optional If specified, this nsIFile based object is used as the output file instead of the one specified at initialization time (if any). aFlags Optional Flags controlling the file write operation. ...
nsILoginInfo
is article. Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) Inherits from: nsISupports Implemented by: @mozilla.org/login-manager/loginInfo;1. ...
...g The password for the login. passwordField AString The name attribute for the password input in a form. Non-form logins should specify an empty string (""). username AString The username for the login. usernameField AString The name attribute for the username input in a form. Non-form logins should specify an empty string (""). Methods clone
() Returns a clone of this login. nsILoginInfo clone
(); Parameters None. Return value An nsILoginInfo containing a clone of the login on which this method was invoked. equals
() Tests to determine whether this login is exactly equal to another nsILoginInfo object. boolean equals( in nsILoginInfo aLoginInfo ); Parameters aLoginInfo The login to which to compare for equality. Return...
...turn value An nsILoginInfo containing a clone of the login on which this method was invoked. equals
() Tests to determine whether this login is exactly equal to another nsILoginInfo object. boolean equals( in nsILoginInfo aLoginInfo ); Parameters aLoginInfo The login to which to compare for equality. Return value true if the two logins are exactly equal or false if they're not. init
() Initializes a newly created nsILoginInfo object. void init( in AString aHostname, in AString aFormSubmitURL, in AString aHttpRealm, in AString aUsername, in AString aPassword, in AString aUsernameField, in AString aPasswordField ); Parameters aHostname The value to assign to the hostname field. aFormSubmitURL The value to assign to the formSubmitURL field. aHttpRealm The...
...ssign to the hostname field. aFormSubmitURL The value to assign to the formSubmitURL field. aHttpRealm The value to assign to the httpRealm field. aUsername The value to assign to the username field. aPassword The value to assign to the password field. aUsernameField The value to assign to the usernameField field. aPasswordField The value to assign to the passwordField field. matches
() Tests to determine whether this login is loosely equivalent to another nsILoginInfo object. The passwordField and usernameField values are ignored, and the password values may be optionally ignored. If one login's formSubmitURL is an empty string (but not null), it will be treated as a wildcard. A blank value indicates the login was stored before bug 360493 was fixed. boolean matches( in nsI...
nsILoginManagerPrompter
inManagerPrompter); Method overview void init(in nsIDOMWindow aWindow); void promptToChangePassword(in nsILoginInfo aOldLogin, in nsILoginInfo aNewLogin); void promptToChangePasswordWithUsernames([array, size_is(count)] in nsILoginInfo logins, in PRUint32 count, in nsILoginInfo aNewLogin); void promptToSavePassword(in nsILoginInfo aLogin); Methods init
() Initialize the prompter. Must be called before using other interfaces. void init( in nsIDOMWindow aWindow ); Parameters aWindow The in which the user is doing some login-related action that is resulting in a need to prompt them for something. The prompt will be associated with this window (or, if a notification bar is being used, topmost opener in some cases). promptToChangePassword
()...
...sIDOMWindow aWindow ); Parameters aWindow The in which the user is doing some login-related action that is resulting in a need to prompt them for something. The prompt will be associated with this window (or, if a notification bar is being used, topmost opener in some cases). promptToChangePassword
() Ask the user if they want to change a login's password. If the user consents, modifyLogin
() will be called. void promptToChangePassword( in nsILoginInfo aOldLogin, in nsILoginInfo aNewLogin ); Parameters aOldLogin The existing login (with the old password). aNewLogin The new login. promptToChangePasswordWithUsernames
() Ask the user if they want to change the password for one of multiple logins, when the caller can not determine exactly which login should be changed. If t...
...ToChangePassword( in nsILoginInfo aOldLogin, in nsILoginInfo aNewLogin ); Parameters aOldLogin The existing login (with the old password). aNewLogin The new login. promptToChangePasswordWithUsernames
() Ask the user if they want to change the password for one of multiple logins, when the caller can not determine exactly which login should be changed. If the user consents, modifyLogin
() will be called. Note: Because the caller does not know the username of the login to be changed, aNewLogin.username and aNewLogin.usernameField will be set (using the user's selection) before modifyLogin
() is called. void promptToChangePasswordWithUsernames( [array, size_is(count)] in nsILoginInfo logins, in PRUint32 count, in nsILoginInfo aNewLogin ); Parameters logins An array of e...
...d, aNewLogin.username and aNewLogin.usernameField will be set (using the user's selection) before modifyLogin
() is called. void promptToChangePasswordWithUsernames( [array, size_is(count)] in nsILoginInfo logins, in PRUint32 count, in nsILoginInfo aNewLogin ); Parameters logins An array of existing logins. count (length of the array) aNewLogin The new login. promptToSavePassword
() Ask the user if they want to save a login (Yes, Never, Not Now) void promptToSavePassword( in nsILoginInfo aLogin ); Parameters aLogin The login to be saved. ...
nsIMessageListenerManager
All listener callbacks for a particular message are invoked when that message is received. The message manager holds a strong reference to listener. If the same listener registers twice for the same message, the second registration is ignored. void addMessageListener(in AString messageName, in nsIMessageListener listener, ...
... the short period after a frame has been removed from the DOM and before its frame script has finished unloading; this is false by default. This parameter only has an effect for frame message managers in the main process. An alternative method to listen for death of frame script is to use a message-manager-disconnect observer; see Observer Notifications :: Message Manager. removeMessageListener
() Undo an addMessageListener
() call; that is, calling this causes listener to stop being invoked when the specified message is received. void removeMessageListener(in AString messageName, in nsIMessageListener listener); removeMessageListener
() does not remove a message listener added via addWeakMessageListener
(); use removeWeakMessageListener
() for that. Parameters...
...AString messageName, in nsIMessageListener listener); removeMessageListener
() does not remove a message listener added via addWeakMessageListener
(); use removeWeakMessageListener
() for that. Parameters messageName The name of the message whose listener is to be removed. listener An nsIMessageListener representing the listener to remove. addWeakMessageListener
() This is just like addMessageListener
(), except that the message manager holds a weak reference to listener. void addWeakMessageListener(in AString messageName, in nsIMessageListener listener); If you have two weak message listeners for the same message, they may be called in any order. Parameters messageName A string indicating the name of the message to list...
... in nsIMessageListener listener); If you have two weak message listeners for the same message, they may be called in any order. Parameters messageName A string indicating the name of the message to listen for. listener An nsIMessageListener to invoke when a message is received. See nsIMessageListener for details of the message syntax. removeWeakMessageListener
() Undo an addWeakMessageListener
() call. That is, calling this causes the listener to no longer be invoked when messageName is received. void removeWeakMessageListener(in AString messageName, in nsIMessageListener listener); removeWeakMessageListener
() does not remove a message listener added via addMessageListener
(); use removeMessageListener
() for that. Parame...
nsIMicrosummary
Since generators and pages can be remote resources, and we need them to generate the content, this may not always be available. Read only. generator nsIMicrosummaryGenerator The generator that generates this microsummary. May need to be loaded. needsR...
...l boolean Used when a site author has indicated that a microsummary (or an associated generator) will no longer be available. Read only. pageURI nsIURI The URI of the page being summarized. Read only. updateInterval long The minimum interval after which this microsummary would like to be refreshed or null if it doesn't care. Read only. Methods addObserver
() Add a microsummary observer to this microsummary. void addObserver( in nsIMicrosummaryObserver observer ); Parameters observer The microsummary observer to add. equals
() Microsummary equivalence test. Microsummaries equal if they summarize the same page with the same microsummary-generator (see also nsIMicrosummaryGenerator.equals
()). boolean equals( in nsIMicrosummary aOther ); P...
...l if they summarize the same page with the same microsummary-generator (see also nsIMicrosummaryGenerator.equals
()). boolean equals( in nsIMicrosummary aOther ); Parameters aOther The microsummary to compare against. Return value Returns true if the microsummaries are equal. false if they aren't. Note: This method returns false if either objects don't have a generator removeObserver
() Remove a microsummary observer from this microsummary. void removeObserver( in nsIMicrosummaryObserver observer ); Parameters observer The microsummary observer to remove. update
() Update the microsummary, first loading its generator and page content as necessary. ...
...Observer
() Remove a microsummary observer from this microsummary. void removeObserver( in nsIMicrosummaryObserver observer ); Parameters observer The microsummary observer to remove. update
() Update the microsummary, first loading its generator and page content as necessary. If you want know when a microsummary finishes updating, add an observer before calling this method. ...
nsIMicrosummaryGenerator
ntent, while those which represent the actual microsummary do not. Read only. uri nsIURI The canonical location and unique identifier of the generator. It tells us where the generator comes from and where to go for updates. Read only. For generators referenced by web pages via <link> tags, this URI is the URL specified by the tag. For generators installed via nsISidebar.addMicrosummaryGenerator
(), this URI is a URN of the form urn:source:<url>, where <url> is the remote location from which we installed the generator. For generators installed via some other mechanism (for example an extension that dynamically creates generators), this URI is a URN in a form of the extension's own choosing, with the only restriction being that the URI be globally unique. To ensure this, we recommend that su...
...nstalled via some other mechanism (for example an extension that dynamically creates generators), this URI is a URN in a form of the extension's own choosing, with the only restriction being that the URI be globally unique. To ensure this, we recommend that such extensions incorporate UUIDs created by nsIUUIDGenerator into the URNs of the generators they create. ...
...Interval
() Calculates the interval until the microsummary should be updated for the next time, depending on the page content. If the generator doesn't specify an interval, null is returned. long calculateUpdateInterval( in nsIDOMNode aPageContent ); Parameters aPageContent The content of the page being summarized. Return value The interval in milliseconds until the next update request. equals
() Microsummary-generator equivalence test. Generators are considered equal if their canonical locations (uri attribute) are equal. boolean equals( in nsIMicrosummaryGenerator aOther ); Parameters aOther The generator to compare against. Return value A boolean indicating if the two generators are equal. ...
...If a generator doesn't need content, pass null as the parameter to this method. Note: In the future, this may be expanded to support rich text content. ...
nsIModule
boolean canUnload( in nsIComponentManager aCompMgr ); Parameters aCompMgr The global component manager. Return value Indicates to the caller whether or not the component module can be unloaded. Returning true is not a guarantee that the module will be unloaded. It constitues only wil...
...o ensure that no outstanding references to the module's code/data exist before returning true. Returning false guaratees that the module will not be unloaded. If the component module is native (that is, as part of a DLL), then this method may be called to determine whether or not the DLL may be unloaded from memory. Note: As of Gecko 1.7, native component modules are never unloaded. getClassObject
() Obtains a Class Object from a nsIModule for a given CID and IID pair. This class object can either be query to a nsIFactory or a may be query to a nsIClassInfo. void getClassObject( in nsIComponentManager aCompMgr, in nsCIDRef aClass, in nsIIDRef aIID, [retval, iid_is(aIID)] out nsQIResult aResult ); Parameters aCompMgr The global component manager. aClass The ClassID of...
...r The global component manager. aClass The ClassID of object instance requested. aIID The IID of interface requested. aResult The resulting interface pointer. Exceptions thrown NS_ERROR_FACTORY_NOT_REGISTERED Indicates that the requested class is not available. NS_ERROR_NO_INTERFACE Indicates that the requested interface is not supported. registerSelf
() When the nsIModule is discovered, this method will be called so that any setup registration can be preformed. void registerSelf( in nsIComponentManager aCompMgr, in nsIFile aLocation, in string aLoaderStr, in string aType ); Parameters aCompMgr The global component manager. aLocation The location of the nsIModule on disk. aLoaderStr Opaque loader specific string.
...setup registration can be preformed. void registerSelf( in nsIComponentManager aCompMgr, in nsIFile aLocation, in string aLoaderStr, in string aType ); Parameters aCompMgr The global component manager. aLocation The location of the nsIModule on disk. aLoaderStr Opaque loader specific string. aType Loader Type being used to load this module. unregisterSelf
() When the nsIModule is being unregistered, this method will be called so that any unregistration can be preformed. void unregisterSelf( in nsIComponentManager aCompMgr, in nsIFile aLocation, in string aLoaderStr ); Parameters aCompMgr The global component manager. aLocation The location of the nsIModule on disk. aLoaderStr Opaque loader specific string. Remarks Thi...
nsIMsgWindow
n instance, use: msgWindow = Components.classes["@mozilla.org/messenger/msgwindow;1"] .createInstance(Components.interfaces.nsIMsgWindow); In Thunderbird the default message window is stored in the global variable msgWindow. Method overview void displayHTMLInMessagePane(in AString title, in AString body, in boolean clearMsgHdr); void StopUrls
(); void closeWindow
(); Attributes Attribute Type Description windowCommands nsIMsgWindowCommands This allows the backend code to send commands to the UI, such as clearMsgPane. statusFeedback nsIMsgStatusFeedback This allows the backend code to send status feedback to the UI. m...
...ng). stopped boolean Check if a running url been stopped. If you are checking this flag, you need to clear it before you start your operation since there's no convenient place to clear it. domWindow nsIDOMWindow The message window's global chrome window object. Set this to initialize the rootDocShell. Methods displayHTMLInMessagePane
() Loads the specified HTML in the message pane. This is equivalent to calling LoadURI on the nsIWebNavigation object with a data: URL specifying the HTML. void displayHTMLInMessagePane(in AString title, in AString body, in boolean clearMsgHdr); Parameters title Not used. body The HTML to display in the message...
... in AString body, in boolean clearMsgHdr); Parameters title Not used. body The HTML to display in the message pane. Note that the HTML is wrapped in <html> and <body> tags for you. clearMsgHdr Whether or not the existing message pane and header should be cleared before the HTML is displayed. StopUrls
() This is equivalent to calling Stop(nsIWebNavigation::STOP_NETWORK) on the nsIWebNavigation object. void StopUrls
(); closeWindow
() When the msg window is being unloaded from the content window, this notification can be used to force a flush on anything the message window hangs on. For some reason XPConnect is still hanging onto the message window even though all of our objects have let go of it.
...msg window is being unloaded from the content window, this notification can be used to force a flush on anything the message window hangs on. For some reason XPConnect is still hanging onto the message window even though all of our objects have let go of it. This forces a release. It clears out the content listener, the windowCommands, the statusFeedback and the docShell objects. void closeWindow
(); Remarks See also ...
nsIMutableArray
ys that are mutable; that is, they can be altered programmatically. Inherits from: nsIArray Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Consumers of nsIArray should not QueryInterface to nsIMutableArray unless they own the array. As above, it is legal to add null elements to the array. Note also that null elements can be created as a side effect of insertElementAt
(). Conversely, if insertElementAt
() is never used, and null elements are never explicitly added to the array, then it is guaranteed that nsIArray.queryElementAt
() will never return a null value. Any of these methods may throw NS_ERROR_OUT_OF_MEMORY when the array must grow to complete the call, but the allocation fails. Method overview void appendElement(in nsISupports element, in boolean ...
...mentAt
() is never used, and null elements are never explicitly added to the array, then it is guaranteed that nsIArray.queryElementAt
() will never return a null value. Any of these methods may throw NS_ERROR_OUT_OF_MEMORY when the array must grow to complete the call, but the allocation fails. Method overview void appendElement(in nsISupports element, in boolean weak); void clear
(); void insertElementAt(in nsISupports element, in unsigned long index, in boolean weak); void removeElementAt(in unsigned long index); void replaceElementAt(in nsISupports element, in unsigned long index, in boolean weak); Methods appendElement
() Append an element at the end of the array. void appendElement( in nsISupports element, in boolean weak ); Paramete...
... Methods appendElement
() Append an element at the end of the array. void appendElement( in nsISupports element, in boolean weak ); Parameters element The element to append. weak Whether or not to store the element using a weak reference. Exceptions thrown NS_ERROR_FAILURE When a weak reference is requested, but the element does not support nsIWeakReference. clear
() Clear the entire array, releasing all stored objects. void clear
(); Parameters None. insertElementAt
() Insert an element at the given position, moving the element currently located in that position, and all elements in higher position, up by one. void insertElementAt( in nsISupports element, in unsigned long index, in boolean weak ); Parameters element The element to insert. ...
...ion is equal to the current length of the array, the new element is appended. An index lower than 0 or higher than the current length of the array is invalid and will be ignored. weak Whether or not to store the element using a weak reference. Exceptions thrown NS_ERROR_FAILURE When a weak reference is requested, but the element does not support nsIWeakReference. removeElementAt
() Remove an element at a specific position, moving all elements stored at a higher position down one. To remove a specific element, use nsIArray.indexOf
() to find the index first, then call removeElementAt. void removeElementAt( in unsigned long index ); Parameters index The position of the item. replaceElementAt
() Replace the element at the given position. void replaceElementAt( in ...
nsINavHistoryContainerResultNode
nodes; accessing this throws an NS_ERROR_NOT_AVAILABLE exception of containerOpen is false. Read only. childrenReadOnly boolean false if the node's list of children can be modified (by adding or removing children, or rearranging them), or true if the user interface should not allow the list of children to be altered. Read-only. This is false for bookmark folder nodes unless the setFolderReadOnly
() method has been called to specifically make the folder read-only. It's true for non-folder nodes. If this container is a remote container, this flag may be redefined by the remote container provider. Read-only. containerOpen boolean Set this to true to allow descent into this container. When closed, attempting to call getChild
() or access childCount results in an error. When you're done readin...
...ations. state unsigned short The current state of the container. This is one of the state constants. Constants State constants Constant Value Description STATE_CLOSED 0 The container is closed. STATE_LOADING 1 The container has been opened asynchronously, but is still loading and is not all the way opened yet. STATE_OPENED 2 The container is open. Methods findNodeByDetails
() Returns a node matching specified details. nsINavHistoryResultNode findNodeByDetails( in AUTF8String aURIString, in PRTime aTime, in long long aItemId, in boolean recursive ); Parameters aURIString The URI attribute value to match on. aTime The time attribute to match on. aItemId The item ID to match on. aRecursive If true, the search will recurse through all child containers of the cur...
...te to match on. aItemId The item ID to match on. aRecursive If true, the search will recurse through all child containers of the current container; if false, only direct children of the container are searched. Return value An nsINavHistoryResultNode of a node matching the specified details or null if no match is found. Exceptions thrown NS_ERROR_NOT_AVAILABLE The container is not open. ...
...unsigned long getChildIndex( in nsINavHistoryResultNode aNode ); Parameters aNode The node whose index is to be returned. Return value The index of the specified node into the list of immediate children of the container. Exceptions thrown NS_ERROR_NOT_AVAILABLE The container isn't open (that is, containerOpen is false). ...
nsIParentalControlsService
Attributes Attribute Type Description blockFileDownloadsEnabled boolean true if the current user account's parental controls restrictions include the blocking of all file downloads. Read only. loggingEnabled boolean true if the current user account has parental controls logging enabled. If this is true, applications should log relevant events using log
() method. Read only. parentalControlsEnabled boolean true if the current user account has parental controls restrictions enabled. Read only. Constants Constant Value Description ePCLog_URIVisit 1 This log entry type represents an access to web content. ePCLog_FileDownload 2 This log entry type represents a file download. Met...
...Read only. parentalControlsEnabled boolean true if the current user account has parental controls restrictions enabled. Read only. Constants Constant Value Description ePCLog_URIVisit 1 This log entry type represents an access to web content. ePCLog_FileDownload 2 This log entry type represents a file download. Methods log
() Logs an application specific parental controls event. void log( in short aEntryType, in boolean aFlag, in nsIURI aSource, in nsIFile aTarget Optional ); Parameters aEntryType The type of event to log. See the constants for allowed values. aFlag Pass true if the event was blocked or false if it was allowed. aSource The URI source of the subject content. aTarget Optional The l...
...ryType, in boolean aFlag, in nsIURI aSource, in nsIFile aTarget Optional ); Parameters aEntryType The type of event to log. See the constants for allowed values. aFlag Pass true if the event was blocked or false if it was allowed. aSource The URI source of the subject content. aTarget Optional The location to which the content was saved if it was not blocked. requestURIOverride
() Requests that a blocked URI be allowed through parental control filters. This method may block while the operating system presents user interface to handle the override request (such as an "enter an administrator's password" dialog box). boolean requestURIOverride( in nsIURI aTarget, in nsIInterfaceRequestor aWindowContext Optional ); Parameters aTarget The URI to be overridden. aWi...
...dle the override request (such as an "enter an administrator's password" dialog box). boolean requestURIOverride( in nsIURI aTarget, in nsIInterfaceRequestor aWindowContext Optional ); Parameters aTarget The URI to be overridden. aWindowContext Optional The window generating the event. Return value true if the block was successfully overridden, otherwise false. requestURIOverrides
() Requests that a set of URIs be allowed through the parental control filters. This method may block while the operating system presents user interface to handle the override request (such as an "enter an administrator's password" dialog box). boolean requestURIOverrides( in nsIArray aTargets, in nsIInterfaceRequestor aWindowContext Optional ); Parameters aTargets An array of nsIURI ob...
nsIPlacesImportExportService
interface name has been kept for compatibility reasons for code using the export service. ...
...aFile); void importHTMLFromFile(in nsILocalFile aFile, in boolean aIsInitialImport); Obsolete since Gecko 14.0 void importHTMLFromFileToFolder(in nsILocalFile aFile, in PRInt64 aFolder, in boolean aIsInitialImport); Obsolete since Gecko 14.0 void importHTMLFromURI(in nsIURI aURI, in boolean aIsInitialImport); Obsolete since Gecko 14.0 Methods backupBookmarksFile
() Backs up the bookmarks.html file. void backupBookmarksFile
(); Parameters None. exportHTMLToFile
() Saves the current bookmarks hierarchy to a bookmarks.html file. void exportHTMLToFile( in nsILocalFile aFile ); Parameters aFile An nsILocalFile indicating where to save the new bookmarks.html file. importHTMLFromFile
() Obsolete since Gecko 14.0 (Firefox 14.0 / Thun...
...ed through their data parameters either "html" if aIsInitialImport is false or "html-initial" if aIsInitialImport is true. The observer subject will be null. void importHTMLFromFile( in nsILocalFile aFile, in boolean aIsInitialImport ); Parameters aFile The HTML file to import into Places. aIsInitialImport Whether this is an initial import or not. importHTMLFromFileToFolder
() Obsolete since Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11) Note: This method has been removed; use the BookmarkHTMLUtils.jsm JavaScript code module instead.Loads the given bookmarks.html file and puts it in the given folder. Three nsIObserverService notifications are fired as a result of the import. "bookmarks-restore-begin" is fired just before the import is ...
...t is true. The observer subject will be an nsISupportsPRInt64 whose value is aFolder. void importHTMLFromFileToFolder( in nsILocalFile aFile, in PRInt64 aFolder, in boolean aIsInitialImport ); Parameters aFile The file to import. aFolder The ID of the bookmarks folder into which to import the bookmarks. aIsInitialImport Whether or not this is an initial import. importHTMLFromURI
() Obsolete since Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Note: This method has been removed; use the BookmarkHTMLUtils.jsm JavaScript code module instead. Same thing as importHTMLFromFile
(), but takes a URI instead. vo...
nsIPrefService
s files and also facilitates access to the preference branch object which allows the direct manipulation of the preferences themselves. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview nsIPrefBranch getBranch(in string aPrefRoot); nsIPrefBranch getDefaultBranch(in string aPrefRoot); void readUserPrefs(in nsIFile aFile); void resetPrefs
(); void resetUserPrefs
(); void savePrefFile(in nsIFile aFile); Methods getBranch
() Call to get a Preferences "Branch" which accesses user preference data. Using a Set method on this object will always create or set a user preference value. When using a Get method a user set value will be returned if one exists, otherwise a default value will be returned. nsIPrefBranch ge...
...ser.startup. is used, the branch will be able to easily access the preferences browser.startup.page, browser.startup.homepage, and browser.startup.homepage_override by simply requesting page, homepage, or homepage_override. nsnull or "" (empty string) may be used to access to the entire preference tree. Return value nsIPrefBranch - The object representing the requested branch. getDefaultBranch
() Call to get a Preferences branch which accesses only the default preference data. Using a Set method on this object will always create or set a default preference value. When using a Get method a default value will always be returned. Note: Few consumers will want to create default branch objects. Many of the branch methods do nothing on a default branch because the operations only make sense w...
...tartup. is used, the branch will be able to easily access the preferences browser.startup.page, browser.startup.homepage, and browser.startup.homepage_override by simply requesting page, homepage, or homepage_override. nsnull or "" (empty string) may be used to access to the entire preference tree. Return value nsIPrefBranch - The object representing the requested default branch. ...
... value nsIPrefBranch - The object representing the requested default branch. readUserPrefs
() Called to read in the preferences specified in a user preference file. Note: If nsnull is passed in for the aFile parameter the default preferences file(s) [prefs.js, user.js] will be read and processed. void readUserPrefs( in nsIFile aFile ); Parameters aFile The file to be read. resetPrefs
() Called to completely flush and re-initialize the preferences system. void resetPrefs
(); Parameters None. resetUserPrefs
() Called to reset all preferences with user set values back to the application default values. void resetUserPrefs
(); Parameters None. savePrefFile
() Called to write current preferences state to a file. Note: If nsnull is passed in for the aFile parameter the prefe...
nsIProcessScriptLoader
process message managers to load scripts into a child process. The scripts run only once per process. The global object for process scripts is a ContentProcessMessageManager. Methods void loadProcessScript(in AString aURL, in boolean aAllowDelayedLoad) void removeDelayedProcessScript(in AString aURL); jsval getDelayedProcessScripts
(); loadProcessScript
() Load a script in the child process. Process scripts are loaded as soon as loadProcessScript
() is called. If this function is called on a ChromeMessageBroadcaster, : it will load the process script into all child processes. if aAllowDelayedLoad is true, then the script will also be loaded into any new child processes created after the loadProcessScript
() call. Oth...
...ll. Otherwise it will only be loaded into child processes that exist at the time of the call. If this function is called on a ChromeMessageSender: it will load the process script only into this ChromeMessageSender's child process aAllowDelayedLoad should always be true. It's possible that the child process for this ChromeMessageSender is not yet available at the time of the loadProcessScript
() call, and if you pass false in this situation, your process script won't be loaded. For example: let ppmm = Services.ppmm.getChildAt(1); ppmm.loadProcessScript('data:,dump("foo\n");', true); Parameters Name Type Description 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"); ...
... aURL must be the absolute URL. data: URLs are also supported. For example data:,dump("foo\n"); aAllowDelayedLoad Boolean If this flag is false, the process script will only be loaded into child processes that are already running at the time of the call. If this flag is true, the process script will be loaded into any new child processes created after the loadProcessScript
() call, until removeDelayedProcessScript
() is called for that script. If you are calling loadProcessScript
() on a ChromeMessageSender, you should always pass true here. removeDelayedProcessScript
() Removes aURL from the list of scripts which support delayed load. This cancels the effect of the aAllowDelayedLoad flag, meaning that the loader will no longer load the script into new ...
...ls the effect of the aAllowDelayedLoad flag, meaning that the loader will no longer load the script into new child processes. If you used aAllowDelayedLoad, 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. getDelayedProcessScripts
() Returns all delayed scripts that will be loaded once a child process becomes available. The return value is a list of pairs [<URL>, false]. Returns List of the delayed scripts. Each script is returned as a pair: [<URL>, false]. ...
nsIProfile
profile currently in use. profileCount long The number of profiles. Read only. Constants Profile shutdown types Constant Value Description SHUTDOWN_PERSIST 0x00000001 When shutting down the profile, save all changes. SHUTDOWN_CLEANSE 0x00000002 When shutting down the profile, discard changes. Unimplemented Methods cloneProfile
() Clones the current profile, creating a copy of it with a new name. void cloneProfile( in wstring profileName ); Parameters profileName The name to assign to the new clone of the current profile. createNewProfile
() Creates a new profile. Appropriate default values will be copied into the preferences in the new profile. void createNewProfile( in wstring profileName, in wstring nati...
... The name to assign to the new profile. nativeProfileDir The pathname of the directory to use as the profile directory; if you specify null, a new folder will be created in the default profiles directory. langcode The locale to use for the new profile. useExistingDir If true, an existing directory may be used; otherwise, the profile directory will be unique. deleteProfile
() Deletes the specified profile. void deleteProfile( in wstring name, in boolean canDeleteFiles ); Parameters name The name of the profile to delete. canDeleteFiles If true, the Profile Manager will try to delete all of the profile's files and its directory. getProfileList
() Returns an array of strings indicating the names of all the available profiles. void getProfileList( ...
...st
() Returns an array of strings indicating the names of all the available profiles. void getProfileList( out unsigned long length, [retval, array, size_is(length)] out wstring profileNames ); Parameters length On return, contains the number of profiles in the profileNames array. profileNames On return, contains an array of all of the available profiles' names. profileExists
() Determine whether or not a profile with the specified name exists. boolean profileExists( in wstring profileName ); Parameters profileName The name of the profile to look for. Return value true if there is a profile with the specified name. renameProfile
() Renames an existing profile. void renameProfile( in wstring oldName, in wstring newName ); Parameters oldName The n...
...void shutDownCurrentProfile( in unsigned long shutDownType ); Parameters shutDownType The type of shutdown to perform; see Shutdown type constants. ...
nsIProgressEventSink
. An implementation of this interface can be passed to a channel via the channel's notificationCallbacks attribute. See nsIChannel for more info. The channel will begin passing notifications to the progress event sink after its asyncOpen method has been called. Notifications will cease once the channel calls its listener's onStopRequest method or once the channel is canceled (via nsIRequest.cancel
()). Note: This interface is actually not specific to channels and may be used with other implementations of nsIRequest. Method overview void onProgress(in nsIRequest aRequest, in nsISupports aContext, in unsigned long long aProgress, in unsigned long long aProgressMax); void onStatus(in nsIRequest aRequest, in nsISupports aContext, in nsresult aStatus, in wstring aSta...
...not specific to channels and may be used with other implementations of nsIRequest. Method overview void onProgress(in nsIRequest aRequest, in nsISupports aContext, in unsigned long long aProgress, in unsigned long long aProgressMax); void onStatus(in nsIRequest aRequest, in nsISupports aContext, in nsresult aStatus, in wstring aStatusArg); Methods onProgress
() Called to notify the event sink that progress has occurred for the given request. void onProgress( in nsIRequest aRequest, in nsISupports aContext, in unsigned long long aProgress, in unsigned long long aProgressMax ); Parameters aRequest The request being observed (may QI to nsIChannel). aContext If aRequest is a channel, then this parameter is the listener ...
...progress has occurred for the given request. void onProgress( in nsIRequest aRequest, in nsISupports aContext, in unsigned long long aProgress, in unsigned long long aProgressMax ); Parameters aRequest The request being observed (may QI to nsIChannel). aContext If aRequest is a channel, then this parameter is the listener context passed to nsIChannel.asyncOpen
(). aProgress Numeric value in the range 0 to aProgressMax indicating the number of bytes transfered thus far. aProgressMax Numeric value indicating maximum number of bytes that will be transfered (or 0xFFFFFFFFFFFFFFFF if total is unknown). onStatus
() Called to notify the event sink with a status message for the given request. void onStatus( in nsIRequest aRequest, ...
...d to notify the event sink with a status message for the given request. void onStatus( in nsIRequest aRequest, in nsISupports aContext, in nsresult aStatus, in wstring aStatusArg ); Parameters aRequest The request being observed (may QI to nsIChannel). aContext If aRequest is a channel, then this parameter is the listener context passed to nsIChannel.asyncOpen
(). aStatus Status code (not necessarily an error code) indicating the state of the channel (usually the state of the underlying transport). see nsISocketTransport for socket specific status codes. aStatusArg Status code argument to be used with the string bundle service to convert the status message into localized, human readable text. the meaning of this parameter is sp...
nsIProtocolHandler
URI_FORBIDS_AUTOMATIC_DOCUMENT_REPLACEMENT 1<<5 "Automatic" loads that would replace the document (such as a meta refresh, certain types of XLinks, and other non-user-triggered loads) are not allowed if the originating URI has this protocol flag. Keep in mind that the decision of what constitutes an automatic load is made externally, by the caller of nsIScriptSecurityManager.CheckLoadURI
(). Typically, this flag is used by protocols that show highly untrusted content in a viewing area that the user expects to have a lot of control over, such as an email reader. URI_LOADABLE_BY_ANYONE 1<<6 Anyone can load the URIs for this protocol; for example, any web site can load a URI for this protocol. Web-safe protocols such as HTTP should use this flag. URI_DANGEROUS...
...an be loaded only by callers with a principal that subsumes this uri. For example, privileged code and websites that are same origin as this uri. URI_NON_PERSISTABLE 1<<10 Loading channels from this protocol has side-effects that make it unsuitable for saving to a local file. URI_DOES_NOT_RETURN_DATA 1<<11 Channels using this protocol never call OnDataAvailable
() on the listener passed to AsyncOpen
(), and therefore do not return any usable data. URI_IS_LOCAL_RESOURCE 1<<12 URIs for this protocol are considered to be local resources. This could be a local file (URI_IS_LOCAL_FILE), a UI resource (URI_IS_UI_RESOURCE), or something else that would not hit the network. URI_OPENING_EXECUTES_SCRIPT 1<<13 URIs for this protocol...
...orts transparent proxying, the handler should implement the nsIProxiedProtocolHandler interface. If the protocol only supports HTTP proxying, it doesn't need to support nsIProxiedProtocolHandler, but should instead set the ALLOWS_PROXY_HTTP flag. ALLOWS_PROXY_HTTP 1<<3 The protocol handler can be proxied using an HTTP proxy (for example, HTTP and FTP). nsIIOService.newChannelFromURI
() will feed URIs from this protocol handler to the HTTP protocol handler instead. This flag is ignored if ALLOWS_PROXY is not set. Methods allowPort
() Lets a protocol override blacklisted ports. This method is called when there's an attempt to connect to a port that is blacklisted. For example, for most protocols, port 25 (Simple Mail Transfer Protocol) is banned. When a URI containing thi...
... this port number is encountered, this method is called to ask if the protocol handler wants to override the ban. boolean allowPort( in long port, in string scheme ); Parameters port The port for which an override is being requested. scheme The scheme for which an override is being requested. Return value Return true if the override is approved; otherwise, return false. newChannel
() Constructs a new channel from the given URI for this protocol handler. nsIChannel newChannel( in nsIURI aURI ); Parameters aURI The URI for which to construct a channel. Return value Return the newly constructed channel. newURI
() Makes a URI object that is suitable for loading by this protocol, where the URI string is given as an UTF-8 string. The caller may provide the charset fro...
nsIScreen
nstants Requires Gecko 13.0(Firefox 13.0 / Thunderbird 13.0 / SeaMonkey 2.10) Constant Value Description ROTATION_0_DEG 0 0? of rotation (that is, no rotation, or default orientation). ROTATION_90_DEG 1 90? of rotation. ROTATION_180_DEG 2 180? of rotation. ROTATION_270_DEG 3 270? of rotation. Methods GetAvailRect
() Returns a rectangle indicating the portion of the screen that is available for use. Note: This returns a rectangle representing the region of the screen that is available for application use. For example, this would exclude the area occupied by the menu bar and Dock on Mac OS X. void GetAvailRect( out long left, out long top, out long width, out long height ); Parameters left Th...
...ed by the menu bar and Dock on Mac OS X. void GetAvailRect( out long left, out long top, out long width, out long height ); Parameters left The left edge of the available screen rectangle. top The top edge of the available screen rectangle. width The width of the available screen rectangle. height The height edge of the available screen rectangle. GetRect
() Returns a rectangle indicating the entire screen's coordinate space. void GetRect( out long left, out long top, out long width, out long height ); Parameters left The left edge of the screen's rectangle. top The top edge of the screen's rectangle. width The width of the screen's rectangle. height The height edge of the screen's rectangle. lockMinimumBrig...
...ns a rectangle indicating the entire screen's coordinate space. void GetRect( out long left, out long top, out long width, out long height ); Parameters left The left edge of the screen's rectangle. top The top edge of the screen's rectangle. width The width of the screen's rectangle. height The height edge of the screen's rectangle. lockMinimumBrightness
() Locks the minimum brightness of the screen, preventing it from becoming any dimmer than that brightness level. Each call to this method must eventually be followed by a corresponding call to unlockMinimumBrightness
() with the same value for the brightness parameter. void lockMinimumBrightness( in unsigned long brightness ); Parameters brightness The new minimum brightness level; this ...
...t brightness level. Each call to this method must eventually be followed by a corresponding call to unlockMinimumBrightness
() with the same value for the brightness parameter. void lockMinimumBrightness( in unsigned long brightness ); Parameters brightness The new minimum brightness level; this must be one of the values specified in Screen brightness constants. unlockMinimumBrightness
() Releases a lock on the minimum brightness of the screen, which was previously established through a corresponding call to lockMinimumBrightness
(). void unlockMinimumBrightness( in unsigned long brightness ); Parameters brightness The brightness level to release; this must be one of the values specified in Screen brightness constants. Example var screenMan = Components.classes["@mozil...
nsISecurityCheckedComponent
by XPConnect and a handful of things that need special handing (XUL controllers, the UI for the <video> tag, etc.). Method overview string canCallMethod(in nsIIDPtr iid, in wstring methodName); string canCreateWrapper(in nsIIDPtr iid); string canGetProperty(in nsIIDPtr iid, in wstring propertyName); string canSetProperty(in nsIIDPtr iid, in wstring propertyName); Methods canCallMethod
() Returns a capability string indicating what permissions are required to call the specified method on the given interface. string canCallMethod( in nsIIDPtr iid, in wstring methodName ); Parameters iid The IID of the interface this method exists on. methodName The name of the method to be called on the interface. Return value The capability required to call this method. See Capability strin...
...icating what permissions are required to call the specified method on the given interface. string canCallMethod( in nsIIDPtr iid, in wstring methodName ); Parameters iid The IID of the interface this method exists on. methodName The name of the method to be called on the interface. Return value The capability required to call this method. See Capability strings for details. canCreateWrapper
() Returns a string indicating what permissions are required to create a wrapper for the given interface. string canCreateWrapper( in nsIIDPtr iid ); Parameters iid The interface to reflect into JavaScript. Return value The capability required to reflect this interface. Note that if wrapper creation is prevented, the properties and methods will not be defined on the JavaScript object, whereas...
...ace to reflect into JavaScript. Return value The capability required to reflect this interface. Note that if wrapper creation is prevented, the properties and methods will not be defined on the JavaScript object, whereas if wrapper creation succeeds but methods/properties are prevented, the properties and methods will be visible, not not usable. See Capability strings for details. canGetProperty
() Returns the permissions required to get the specified property on the given interface. string canGetProperty( in nsIIDPtr iid, in wstring propertyName ); Parameters iid The interface that the property to get exists on. propertyName The name of the property to be retrieved on this interface. Return value The capability required to get the property. See Capability strings for details. can...
...e permissions required to get the specified property on the given interface. string canGetProperty( in nsIIDPtr iid, in wstring propertyName ); Parameters iid The interface that the property to get exists on. propertyName The name of the property to be retrieved on this interface. Return value The capability required to get the property. See Capability strings for details. canSetProperty
() Returns the permissions required to set the specified property on the given interface. string canSetProperty( in nsIIDPtr iid, in wstring propertyName ); Parameters iid The interface that the property to set exists on. propertyName The name of the property to be set on this interface. Return value The capability required to set the property. See Capability strings for details. ...
nsIStringBundle
a string bundle can be created within a javascript context with nsIStringBundleService. Method overview wstring formatStringFromID(in long aID, [array, size_is(length)] in wstring params, in unsigned long length); wstring formatStringFromName(in wstring aName, [array, size_is(length)] in wstring params, in unsigned long length); nsISimpleEnumerator getSimpleEnumeration
(); wstring GetStringFromID(in long aID); wstring GetStringFromName(in wstring aName); Methods formatStringFromID
() Returns a formatted string with the given ID from the string bundle, where each occurrence of %S (uppercase) is replaced by each successive element in the supplied array. You may also use other formatting codes. You can only pass Unicode strings in. The ID sh...
... NOT try to use any other types. This uses nsTextFormatter::smprintf. wstring formatStringFromID( in long aID, [array, size_is(length)] in wstring params, in unsigned long length ); Parameters aID The ID of the string to retrieve. params Parameters to pass in to the string. length The length of the parameter list. Return value Returns the formatted string. formatStringFromName
() Returns a formatted string with the given key name from the string bundle, where each occurrence of %S (uppercase) is replaced by each successive element in the supplied array. You may also use other formatting codes, but can only pass Unicode strings in. The name should refer to a string in the bundle that uses %S, and the number of strings you pass MUST be the same here and in the properties f...
... This uses nsTextFormatter::smprintf to do the dirty work. wstring formatStringFromName( in wstring aName, [array, size_is(length)] in wstring params, in unsigned long length ); Parameters aName The name of the string to retrieve. params Parameters to pass in to the string. length The length of the parameter list. Return value Returns the formatted string. getSimpleEnumeration
() nsISimpleEnumerator getSimpleEnumeration
(); Parameters None. Return value Returns a nsISimpleEnumerator of all nsIPropertyElement entries in the string bundle. GetStringFromID
() Retrieves a string from the bundle by its ID. wstring GetStringFromID( in long aID ); Parameters aID The ID of the string to retrieve. String ID's are assigned by the order in which they are stored in the...
... wstring GetStringFromName( in wstring aName ); Parameters aName The name of the string to retrieve. String name are designated in the properties file. Return value Returns the requested string. ...
nsIStringBundleService
/stringbundle;1. To access this service, use: var stringBundleService = Components.classes["@mozilla.org/intl/stringbundle;1"] .getService(Components.interfaces.nsIStringBundleService); Method overview nsIStringBundle createBundle(in string aURLSpec); nsIStringBundle createExtensibleBundle(in string aRegistryKey); void flushBundles
(); wstring formatStatusMessage(in nsresult aStatus, in wstring aStatusArg); Methods createBundle
() nsIStringBundle createBundle( in string aURLSpec ); Parameters aURLSpec The URL of the properties file to load. This is typically a locale URL, e.g. chrome://global/locale/global.properties Return value A string bundle corresponding to the properties file. This string bund...
... aURLSpec The URL of the properties file to load. This is typically a locale URL, e.g. chrome://global/locale/global.properties Return value A string bundle corresponding to the properties file. This string bundle has functions available on it. On the return value object on you can call functions like GetStringFromName and formatStringFromName see nsIStringBundle. createExtensibleBundle
() nsIStringBundle createExtensibleBundle( in string aRegistryKey ); Parameters aRegistryKey The name of the category under which the properties file(s) have been registered. Return value An extensible bundle corresponding to the properties file(s). flushBundles
() Flushes the string bundle cache - useful when the locale changes or when we need to get some extra memory back. (Automatica...
...Typically used to format a message received by a nsIProgressEventSink's onStatus method. ...
...Typically used to format a message received by a nsIProgressEventSink's onStatus method. ...
nsISupports
xpcom/base/nsISupports.idlScriptable All XPCOM interfaces inherit this interface. Last changed in Gecko 1.0 Method overview nsrefcnt AddRef
();Violates the XPCOM interface guidelines void QueryInterface(in nsIIDRef uuid, [iid_is(uuid),retval] out nsQIResult result); nsrefcnt Release
();Violates the XPCOM interface guidelines Methods Violates the XPCOM interface guidelines AddRef
() Notifies the object that an interface pointer has been duplicated. nsrefcnt AddRef
(); Parameters None. Return value An integer value that is generally ignored. QueryInterface
() The QueryInterface method provides runtime type discovery. Note: The interface pointer, aResult, returned by QueryInterface must be released by a call to Relea...
...QueryInterface is a symmetric, transitive, and reflexive operator. void QueryInterface( in nsIIDRef uuid, [iid_is(uuid),retval] out nsQIResult result ); Parameters uuid The uuid of the requested interface result The resulting interface pointer. ...
...transitive, and reflexive operator. void QueryInterface( in nsIIDRef uuid, [iid_is(uuid),retval] out nsQIResult result ); Parameters uuid The uuid of the requested interface result The resulting interface pointer. Exceptions thrown NS_ERROR_NO_INTERFACE The requested interface is not available. ...
...he uuid of the requested interface result The resulting interface pointer. Exceptions thrown NS_ERROR_NO_INTERFACE The requested interface is not available. Violates the XPCOM interface guidelines Release
() Notifies the object that an interface pointer has been destroyed and any resources the object held on behalf of the client can be released. nsrefcnt Release
(); Parameters None. Return value An integer value that is generally ignored. Remarks The method descriptions above were taken from Essential COM by Don Box. The point of those descriptions is to highlight the fact that AddRef
() and Release
() do not necessarily correspond to incrementing and decrementing a counter, respectively, even though that is how they are usually implemented. On Win32 systems...
nsITaskbarTabPreview
a window will automatically hide that window's nsITaskbarWindowPreview; this is done by Windows and cannot be prevented. When there are no more tab previews left for a window, the window preview is automatically made visible again. An application may have as many tab previews as memory allows. You can't directly instantiate this interface; instead, call the nsIWinTaskbar.createTaskbarTabPreview
(). Method overview void EnsureRegistration
(); Violates the XPCOM interface guidelines nativeWindow GetHWND
(); Violates the XPCOM interface guidelines void move(in nsITaskbarTabPreview aNext); Attributes Attribute Type Description icon imgIContainer The icon displayed next to the title in the preview. This is null by default. ...
...d move(in nsITaskbarTabPreview aNext); Attributes Attribute Type Description icon imgIContainer The icon displayed next to the title in the preview. This is null by default. title DOMString The title displayed above the thumbnail. By default, this is an empty string. ...
...d next to the title in the preview. This is null by default. title DOMString The title displayed above the thumbnail. By default, this is an empty string. Methods Violates the XPCOM interface guidelines EnsureRegistration
() Used internally to ensure that the taskbar knows about this preview. If a preview is not registered, the API call to set its sibling (via the move
() method) will fail silently. This method is only invoked when it's safe to make taskbar API calls. void EnsureRegistration
(); Parameters None. ...
...PCOM interface guidelines EnsureRegistration
() Used internally to ensure that the taskbar knows about this preview. If a preview is not registered, the API call to set its sibling (via the move
() method) will fail silently. This method is only invoked when it's safe to make taskbar API calls. void EnsureRegistration
(); Parameters None. Violates the XPCOM interface guidelines GetHWND
() Used internally to obtain the handle to the proxy window for the preview. nativeWindow GetHWND
(); Parameters None. Return value The HWND for the preview's proxy window. move
() Relocates the preview relative to another tab preview from the same window. void move( in nsITaskbarTabPreview aNext ); Parameters aNext The preview that this preview should be placed to the left of. A va...
nsIThreadInternal
The nsIThreadInternal interface is implemented by the XPCOM thread object to let consumers observe dispatch activity on a thread. xpcom/threads/nsIThreadInternal.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Inherits from: nsIThread Method overview void popEventQueue
(); void pushEventQueue(in nsIThreadEventFilter filter); Attributes Attribute Type Description observer nsIThreadObserver Get/set the current thread observer; set to null to disable observing. This attribute may be read from any thread but must only be set on the thread corresponding to this thread object. The observer will be released on the thread corresponding to this thread object after all other events have been ...
... observer nsIThreadObserver Get/set the current thread observer; set to null to disable observing. This attribute may be read from any thread but must only be set on the thread corresponding to this thread object. The observer will be released on the thread corresponding to this thread object after all other events have been processed during a call to Shutdown. Methods popEventQueue
() Reverts a call to PushEventQueue
(). When an event queue is popped, any events remaining in the queue are appended to the elder queue. void popEventQueue
(); Parameters None. pushEventQueue
() Causes any events currently enqueued on the thread to be suppressed until PopEventQueue
() is called. In addition, any new events dispatched to the thread are only processed if they are accepted by the s...
... void pushEventQueue( in nsIThreadEventFilter filter ); Parameters filter The nsIThreadEventFilter to apply to dispatched events, or null to accept all dispatched events. ...
... void pushEventQueue( in nsIThreadEventFilter filter ); Parameters filter The nsIThreadEventFilter to apply to dispatched events, or null to accept all dispatched events. ...
nsIThreadPool
9 Inherits from: nsIEventTarget Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) A thread pool provides a convenient way to process events off the main thread. When you send events to the thread pool, the pool creates a new thread to process the event, up to the number of threads specified by the threadLimit attribute. Method overview void shutdown
(); Attributes Attribute Type Description idleThreadLimit unsigned long Get/set the maximum number of idle threads that are kept alive. Once there are more than this many idle worker threads, the idle threads start getting destroyed. idleThreadTimeout unsigned long Get/set the amount of time in milliseconds that a thread must be idle before it bec...
...oolListener An optional listener that will be notified when a thread is created or destroyed in the course of the thread pool's operation. A listener will only receive notifications about threads created after the listener is set so it is recommended that the consumer set the listener before dispatching the first event. A listener that receives an nsIThreadPoolListener.onThreadCreated
() notification is guaranteed to always receive the corresponding nsIThreadPoolListener.onThreadShuttingDown
() notification. The thread pool takes ownership of the listener and releases it when the shutdown
() method is called. Threads created after the listener is set will also take ownership of the listener so that the listener will be kept alive long enough to receive the guaranteed nsIThreadP...
... You must not call this method from any thread within the thread pool. ...
... Threads created after the listener is set will also take ownership of the listener so that the listener will be kept alive long enough to receive the guaranteed nsIThreadPoolListener.onThreadShuttingDown
() notification. threadLimit unsigned long The maximum number of threads allowed at once in the pool; you may change this value by altering this attribute. Methods shutdown
() Shuts down the thread pool. You must not call this method from any thread within the thread pool. Instead, you should call it from another thread (typically the one that created the thread pool). When this method returns, the thread pool and all its threads will have been shut down, and it is no longer be possible to dispatch events to the thread pool. void shutdown
(); Parameters None. Se...
nsIToolkitProfileService
eparate Profile Manager application. Warning: This service is synchronous so it is recommended that you use OS.File to find the profile directory via OS.Constants.Path.profileDir. OS.File is available from Gecko 18 (Firefox 18.0 / Thunderbird 18.0 / SeaMonkey 2.15). Method overview nsIToolkitProfile createProfile(in nsILocalFile aRootDir, in AUTF8String aName); void flush
(); nsIToolkitProfile getProfileByName(in AUTF8String aName); nsIProfileLock lockProfilePath(in nsILocalFile aDirectory, in nsILocalFile aTempDirectory); Attributes Attribute Type Description profileCount unsigned long The number of user profiles currently in existence. This will always return 0, 1, or 2; if there are more than 2 profiles, 2 is a...
...le currently in use.) Not sure what happens if you change this setting but someone said: You can change profiles by setting this attribute's value. This may throw an NS_ERROR_FAILURE (0x80004005) when trying to get the current profile if it's unavailable or if permissions restrict access. startOffline boolean startWithLastProfile boolean Methods createProfile
() Creates a new profile. The profile temporary directory will be chosen based on where the profile directory is located. nsIToolkitProfile createProfile( in nsILocalFile aRootDir, in AUTF8String aName ); Parameters aRootDir The profile directory. May be null, in which case a suitable default will be chosen based on the profile name. aName The name to give the new profile. Ret...
... aName The name to give the new profile. Return value An nsIToolkitProfile object representing the newly-created profile. Exceptions thrown NS_ERROR_UNEXPECTED An unexpected error condition occurred. NS_ERROR_FILE_NOT_DIRECTORY One of the specified directory files is not actually a directory. NS_ERROR_OUT_OF_MEMORY Unable to allocate the new profile object. flush
() Flushes the profile list to disk. The profile list file is constructed in memory, then written out as one large chunk, in order to reduce the risk of the profile list file being corrupted by disk errors. void flush
(); Parameters None. Exceptions thrown NS_ERROR_OUT_OF_MEMORY An error occurred trying to allocate the memory buffer used to construct the profile list. NS_ERROR_UNEXPECTE...
...y, then written out as one large chunk, in order to reduce the risk of the profile list file being corrupted by disk errors. void flush
(); Parameters None. Exceptions thrown NS_ERROR_OUT_OF_MEMORY An error occurred trying to allocate the memory buffer used to construct the profile list. NS_ERROR_UNEXPECTED An error occurred writing the profile list file to disk. getProfileByName
() Gets a profile, given the profile's name. nsIToolkitProfile getProfileByName( in AUTF8String aName ); Parameters aName The profile name to find. Return value An nsIToolkitProfile object describing the specified profile. Exceptions thrown NS_ERROR_FAILURE No matching profile was found. lockProfilePath
() Locks an arbitrary path as a profile. If the path does not exist, it is ...
nsIURIFixup
word (or search) operation if it is set. FIXUP_FLAGS_MAKE_ALTERNATE_URI 2 Tell the fixup to make an alternate URI from the input URI, for example to turn foo into www.foo.com. FIXUP_FLAG_USE_UTF8 4 Use UTF-8 to encode the URI instead of the platform character set. FIXUP_FLAG_FIX_SCHEME_TYPOS 8 Fix common scheme typos. Methods createExposableURI
() Converts an internal URI (for example a WYSIWYG URI) into one which we can expose to the user, for example on the URL bar. nsIURI createExposableURI( in nsIURI aURI ); Parameters aURI The URI to be converted. Return value The converted, exposable URI, as an nsIURI. Exceptions thrown NS_ERROR_UNKNOWN_PROTOCOL When we can not get a protocol handler service for the URI scheme. NS_...
... the user, for example on the URL bar. nsIURI createExposableURI( in nsIURI aURI ); Parameters aURI The URI to be converted. Return value The converted, exposable URI, as an nsIURI. Exceptions thrown NS_ERROR_UNKNOWN_PROTOCOL When we can not get a protocol handler service for the URI scheme. NS_ERROR_MALFORMED_URI When the exposable portion of aURI is malformed. createFixupURI
() Converts the specified string into a URI, first attempting to correct any errors in the syntax or other vagaries. Returns a well formed URI or nsnull if it cannot. nsIURI createFixupURI( in AUTF8String aURIText, in unsigned long aFixupFlags ); Parameters aURIText Candidate URI. aFixupFlags Flags that govern ways the URI may be fixed up. Return value The converted URI. keywordToU...
...Converts the specified string into a URI, first attempting to correct any errors in the syntax or other vagaries. Returns a well formed URI or nsnull if it cannot. nsIURI createFixupURI( in AUTF8String aURIText, in unsigned long aFixupFlags ); Parameters aURIText Candidate URI. aFixupFlags Flags that govern ways the URI may be fixed up. Return value The converted URI. ...
...whether we could rescue the URI or "just" generated a keyword search URI instead). nsIURI createFixupURI( in AUTF8String aURIText, in unsigned long aFixupFlags ); Parameters aURIText Candidate URI. ...
nsIUUIDGenerator
UID. 1.0 66 Introduced Gecko 1.8.1 Inherits from: nsISupports Last changed in Gecko 1.8.1 (Firefox 2 / Thunderbird 2 / SeaMonkey 1.1) Implemented by @mozilla.org/uuid-generator; as a service: var uuidGenerator = Components.classes["@mozilla.org/uuid-generator;1"] .getService(Components.interfaces.nsIUUIDGenerator); Method overview nsIDPtr generateUUID
(); void generateUUIDInPlace(in nsNonConstIDPtr id); Native code only! Methods generateUUID
() Obtains a new UUID using appropriate platform-specific methods to obtain a nsID that can be considered to be globally unique. nsIDPtr generateUUID
(); Parameters None. Return value This method returns a nsIDPtr containing a unique ID. Exceptions thrown NS_ERROR_FAILURE If a UUID cannot be generated (f...
...void generateUUIDInPlace( in nsNonConstIDPtr id ); Parameters id An existing nsID pointer where the UUID will be stored. ...
...n existing nsID pointer where the UUID will be stored. ...
...UUID will be stored. ...
nsIWindowsShellService
lScriptable Please add a summary to this article. Inherits from: nsIShellService Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview string getRegistryEntry(in long aHKeyConstant, in string aSubKeyName, in string aValueName); Obsolete since Gecko 1.8 void restoreFileSettings(in boolean aForAllUsers); Obsolete since Gecko 1.9 void shortcutMaintenance
(); Attributes Attribute Type Description desktopBackgroundColor unsigned long The desktop background color, visible when no background image is used, or if the background image is centered and does not fill the entire screen. A rgb value, where (r << 24 | g << 16 | b) Obsolete since Gecko 1.8 unreadMailCount unsigned long The number of unread mail messages for the current user. Read only...
...er. Read only. Constants Valid starting keys for the Windows Registry. Constant Value Description HKCR 0 HKEY_CLASSES_ROOT. Obsolete since Gecko 1.8 HKCC 1 HKEY_CURRENT_CONFIG. Obsolete since Gecko 1.8 HKCU 2 HKEY_CURRENT_USER. Obsolete since Gecko 1.8 HKLM 3 HKEY_LOCAL_MACHINE. Obsolete since Gecko 1.8 HKU 4 HKEY_USERS. Obsolete since Gecko 1.8 Methods getRegistryEntry
() Obsolete since Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Retrieves a Windows Registry entry value. string getRegistryEntry( in long aHKeyConstant, in string aSubKeyName, in string aValueName ); Parameters aHKeyConstant The starting key, using the constants defined above. aSubKeyName The sub key to locate. aValueName The value to locate in the sub key. The ...
...ong aHKeyConstant, in string aSubKeyName, in string aValueName ); Parameters aHKeyConstant The starting key, using the constants defined above. aSubKeyName The sub key to locate. aValueName The value to locate in the sub key. The empty string returns the default value of the sub key. Return value The value of the specified sub key/value, truncated to 4096 bytes. ...
... the specified sub key/value, truncated to 4096 bytes. restoreFileSettings
() Obsolete since Gecko 1.9 (Firefox 3) Restores system settings to what they were before Firefox modified them. void restoreFileSettings( in boolean aForAllUsers ); Parameters aForAllUsers Whether or not Firefox should restore settings for all users on a multi-user system. shortcutMaintenance
() Provides the shell service an opportunity to do some Win7+ shortcut maintenance needed on initial startup of the browser. void shortcutMaintenance
(); Parameters None. ...
nsIXmlRpcFault
extensions/xml-rpc/idl/nsIXmlRpcClient.idlScriptable An XML-RPC exception. XML-RPC server fault codes are returned wrapped in this; access it using nsIXPConnect.GetPendingException->data. ...
...dingException->data. ...
...SeaMonkey 1.0) Method overview void init(in PRInt32 faultCode, in string faultSring); string toString
(); Attributes Attribute Type Description faultCode PRInt32 Read only. faultString string Read only. ...
...thod overview void init(in PRInt32 faultCode, in string faultSring); string toString
(); Attributes Attribute Type Description faultCode PRInt32 Read only. faultString string Read only. ...
MailNews fakeserver
ing a handler to provide different mechanisms is a process not defined here; please check the documentation of the corresponding handler for instructions. Using fakeserver in xpcshell tests Since there are three different components of fakeserver, a total of four objects need to be set up in a fakeserver test on top of other testing. The outline of a test looks like this: var daemon = setupDaemon
(); // Check with your local fakeserver docs var handlers = [ /* Some set of handlers */ ]; for (var handler in handlers) { // This sets up the fake server var server = new nsMailServer(new handler(daemon)); // Port to use. I tend to like using 1024 + default port number myself. // Probably best to include as a constant somewhere. Also, use something // larger than 1024 for best results. ...
...n handlers) { // This sets up the fake server var server = new nsMailServer(new handler(daemon)); // Port to use. I tend to like using 1024 + default port number myself. // Probably best to include as a constant somewhere. Also, use something // larger than 1024 for best results. ...
...sets up the fake server var server = new nsMailServer(new handler(daemon)); // Port to use. I tend to like using 1024 + default port number myself. // Probably best to include as a constant somewhere. Also, use something // larger than 1024 for best results. ...
...o like using 1024 + default port number myself. // Probably best to include as a constant somewhere. Also, use something // larger than 1024 for best results. server.start(port); // Set up a nsIMsgIncomingServer locally localserver.someActionRequiringConnection
(); server.performTest
(); // Nothing will be executed until the connection is closed // localserver.closeCachedConnections
() is generally a good way to do so server.resetTest
(); // Set up second test server.performTest
(); transaction = server.playTransaction
(); // Finished with tests server.stop
(); } Currently, fakeserver provides no means to keep a persistent connection past a test, requiring connections to be closed, possibly forcibly. Alternatively, one can wait for the timeout, which occurs after 3 m...
Mail and RDF
urce, datasources answer with the results of the query. Asynchronously notifying RDF when the data itself changes, RDF needs to be notified. The details Answering Queries Mail uses RDF Resource Factories to attach mail-specific information to RDF resources. (The details of RDF Resource Factories will be left to RDF documentation for now.) From an RDF Resource, it is possible to QueryInterface
() to the appropriate mail/news object, and then access information from there. For example, the folder pane needs to display the number of messages in the INBOX. Information for this column is queried when the tree's RDF Template calls the folder datasource's GetTarget
() method. The query's target is the resource named mailbox://alecf@pop.myisp.com/INBOX and the property node is named http://home.
...OX and the property node is named http://home.netscape.com/NC-rdf#TotalMessages. This is basically what happens, behind the scenes: var target = RDF.GetResource("mailbox://alecf@pop.myisp.com/INBOX"); var property = RDF.GetResource("http://home.netscape.com/NC-rdf#TotalMessages"); var resultNode = dataSource.GetTarget(target, property, true); In the folder datasource's GetTarget
(), target would be QueryInterfaced to a nsIMsgFolder. To get the total messages, the datasource would then call nsIMsgFolder.GetTotalMessages
(). Finally, it would convert the result of this call to an RDF Literal, and pass it back through the return parameter of GetTarget
(). An example of how this might work inside the datasource: var msgCountArc = RDF.GetResource("http://home.netscape.com/NC...
... In the example of mail folders, each folder datasource first registers itself with the mail session as a nsIFolderListener because it wants information about when a folder c...
...folder datasource first registers itself with the mail session as a nsIFolderListener because it wants information about when a folder changes. Each template registers itself as an RDF observer. When a folder's contents or properties change, it tells the mail session to notify the folder listeners that the data has changed. The folder datasource then translates these property changes into OnAssert
() or OnUnassert
() calls to the observers. The calling chain essentially looks like this: Registration: Folder datasource registers itself with the mail session as a folder listener RDF Template registers itself with the datasource as a content observer. Notification: Folder data changes. Folder notifies mail session that it's data changed. Mail session notifies folder listeners that th...
Building a Thunderbird extension 6: Adding JavaScript
t date into our statusbar widget. The statusbar is usually displayed at the bottom of the Thunderbird window. Depending on the installed theme the result will look something like this: Modify XUL elements with JavaScript Save the following JavaScript code into the content/ folder next to your myhelloworld.xul file and name it overlay.js. ...
...ar is usually displayed at the bottom of the Thunderbird window. Depending on the installed theme the result will look something like this: Modify XUL elements with JavaScript Save the following JavaScript code into the content/ folder next to your myhelloworld.xul file and name it overlay.js. ...
...displayed at the bottom of the Thunderbird window. Depending on the installed theme the result will look something like this: Modify XUL elements with JavaScript Save the following JavaScript code into the content/ folder next to your myhelloworld.xul file and name it overlay.js. ...
... on the installed theme the result will look something like this: Modify XUL elements with JavaScript Save the following JavaScript code into the content/ folder next to your myhelloworld.xul file and name it overlay.js. window.addEventListener("load", function(e) { startup
(); }, false); window.setInterval( function
() { startup
(); }, 60000); //update date every minute function startup
() { var myPanel = document.getElementById("my-panel"); var date = new Date
(); var day = date.getDay
(); var dateString = date.getFullYear
() + "." + (date.getMonth
()+1) + "." + date.getDate
(); myPanel.label = "Date: " + dateString; } The first part registers a new event listener that will be executed automatically when Thunderbird loads. The event listener then calls our startup function which ...
Demo Addon
ton to show the demo overview. All three demos are explained in the following sections. Only the interesting parts are shown, it's recommended that you download the add-on and have a look at its files. The basics The interesting parts covered in this article are in the content folder. The toolbar button and its functionality are defined in overlay.xul and overlay.js. We make use of fixIterator
(). It is a handy library that keeps your code cleaner and simpler. It lets you iterate over any collection and transforms your collection elements in the given objects, To use fixIterator, you have to import it with Cu.import("resource:///modules/iteratorUtils.jsm");. Demo 1 - Iterate over all the accounts This demo is implemented in demo1.html in the content folder. It lists all your email accou...
...t server = account.incomingServer; if (server) { info.server = server.prettyName; info.type = server.type; } for each (let id in fixIterator(account.identities, Ci.nsIMsgIdentity)) { // We're only interested in identities that have a real email. ...
... Demo 2 - Find the Inbox This demo shows various information: It lists all folders of an account (in this case the first one) and marks the inbox folder with a *. Furthermore, it shows some messages in the inbox and lists a random attachment. ...
...i.nsMsgFolderFlags.Inbox) we check whether the folder is the inbox. Then we store the folder name in a string to display it later on the screen and mark it with an * if it is the inbox. Afterwards, we check every folder for subfolders. We then go into each subfolder and start over. To list some messages of the folder we use: for each (let msgHdr in fixIterator(inbox.msgDatabase.EnumerateMessages
(), Ci.nsIMsgDBHdr)) { if (++i >= 10 && lastMsgHdr != null) break; messages.push({ author: msgHdr.mime2DecodedAuthor, subject: msgHdr.mime2DecodedSubject, date: new Date(msgHdr.date/1000), }); //... } To get a collection of messages in the inbox, we use inbox.msgDatabase.EnumerateMessages
(). Each message is a nsIMsgDBHdr. We iterate over the first ten...
CType
UInt64 types provide access to 64-bit integer values, which JavaScript doesn't currently support. PointerType These represent pointers to data in memory. FunctionType These represent callable C functions. StructType These represent C structures. ArrayType These represent C arrays. Method overview Methods available on all CType objects CType array([n]) String toSource
() String toString
() Properties Properties of all CType objects These properties are available on all CType objects. Property Type Description name String The type's name. Read only. For primitive types, this is just the name of the corresponding C type. For structure and opaque pointer types, this is simply the string that was passed to the...
... type expression. ptr CType Returns a CType representing the data type "pointer to this type". This is the result of calling ctypes.PointerType(the_type). Read only. size Number The size of the type, in bytes. This is the same value as the C sizeof. Read only. Note: ctypes.void_t.size is undefined. Methods available on all CType objects array
() Returns a new CType representing an array of elements of the type on which it was called. CType array( [n] }; Parameters n Optional The number of elements in the declared array type. If this parameter is left out, the array's size is indeterminate. Return value A CType representing the data type "array of this type". This is the same as calling ctypes.ArrayType(the_type[, n]). toSou...
...eturns a new CType representing an array of elements of the type on which it was called. CType array( [n] }; Parameters n Optional The number of elements in the declared array type. If this parameter is left out, the array's size is indeterminate. Return value A CType representing the data type "array of this type". This is the same as calling ctypes.ArrayType(the_type[, n]). toSource
() Returns a JavaScript expression that evaluates to a CType describing the same C type as this object. String toSource
(); Parameters None. Return value A JavaScript expression that evaluates to a CType describing the same C type as this object. Example ctypes.uint32_t.toSource
() returns "ctypes.uint32_t". toString
() Returns a string identifying the type. The format of this string is "typ...
... Return value A string identifying the data type. ...
Int64
it's a string that is incorrectly formatted or contains a value outside the range that can be represented in 64 bits. This will also be thrown if the source value is a floating-point number that can't be precisely represented as a 64-bit integer. Method overview Number compare(a, b); Number hi(a); Int64 join(high, low); Number lo(a); String toSource
(); String toString([radix]); Methods compare
() Compares two 64-bit integer values. Number compare( a, b ); Parameters a The first value to compare. b The second value to compare. Return value The returned value is: -1 if a < b, 0 if a == b, and 1 if a > b. Exceptions thrown TypeError One or both of the specified values is not a 64-bit integer (either sign...
...tring([radix]); Methods compare
() Compares two 64-bit integer values. Number compare( a, b ); Parameters a The first value to compare. b The second value to compare. Return value The returned value is: -1 if a < b, 0 if a == b, and 1 if a > b. Exceptions thrown TypeError One or both of the specified values is not a 64-bit integer (either signed or unsigned). hi
() Returns the high 32 bits of the specified value. Number hi( num ); Parameters num The value whose high 32 bits are to be returned. Return value The high 32 bits of num are returned. This is essentially num >> 32. Exceptions thrown TypeError num is not a 64-bit integer object. lo
() Returns the low 32 bits of the specified value. Number lo( num ); Parameters num The In...
... Int64 join( high, low ); Parameters high The high-order 32 bits of the value to create. low The low-order 32 bits of the value to create. ...
... high, low ); Parameters high The high-order 32 bits of the value to create. low The low-order 32 bits of the value to create. Return value A new 64-bit integer object comprised of the two values merged together. The returned value is (high << 32) + low. Exceptions thrown TypeError One or both of the specified numbers is not a JavaScript number with an integral value. toSource
() This method is for internal debugging use only. Warning: Do not rely on the value returned by this method, as it's subject to change at any time, depending on the debugging needs of the developers. toString
() Returns a string representation of the object's numeric value. String toString( [radix] ); Parameters radix Optional The radix (base) to use when constructing the string. If you...
UInt64
it's a string that is incorrectly formatted or contains a value outside the range that can be represented in 64 bits. This will also be thrown if the source value is a floating-point number that can't be precisely represented as a 64-bit integer. Method overview Number compare(a, b); Number hi(a); UInt64 join(high, low); Number lo(a); String toSource
(); String toString([radix]); Methods compare
() Compares two 64-bit integer values. Number compare( a, b ); Parameters a The first value to compare. b The second value to compare. Return value The returned value is -1 if a < b, 0 if a == b, and 1 if a > b. Exceptions thrown TypeError One or both of the specified values is not a 64-bit integer (either signed or ...
... toString([radix]); Methods compare
() Compares two 64-bit integer values. Number compare( a, b ); Parameters a The first value to compare. b The second value to compare. Return value The returned value is -1 if a < b, 0 if a == b, and 1 if a > b. Exceptions thrown TypeError One or both of the specified values is not a 64-bit integer (either signed or unsigned). hi
() Returns the high 32 bits of the specified value. Number hi( num ); Parameters num The value whose high 32 bits are to be returned. Return value The high 32 bits of num are returned. This is essentially num >> 32. Exceptions thrown TypeError num is not a 64-bit integer object. lo
() Returns the low 32 bits of the specified value. Number lo( num ); Parameters num The ...
... UInt64 join( high, low ); Parameters high The high-order 32 bits of the value to create. low The low-order 32 bits of the value to create. ...
...high, low ); Parameters high The high-order 32 bits of the value to create. low The low-order 32 bits of the value to create. Return value A new 64-bit integer object comprised of the two values merged together. The returned value is (high << 32) + low. Exceptions thrown TypeError One or both of the specified numbers is not a JavaScript number with an integral value. toSource
() This method is for internal debugging use only. Warning: Do not rely on the value returned by this method, as it's subject to change at any time, depending on the debugging needs of the developers. toString
() Returns a string representation of the object's numeric value. String toString( [radix] ); Parameters radix Optional The radix (base) to use when constructing the string. If y...
Browser Console - Firefox Developer Tools
ws access to the Browse Console. The module is available at Mozilla DXR. We see we can not only access the Browser Console but also Web Console. Here is an example on how to clear the contents of the Browser console: Components.utils.import("resource://devtools/shared/Loader.jsm"); var HUDService = devtools.require("devtools/client/webconsole/hudservice"); var hud = HUDService.getBrowserConsole
(); hud.jsterm.clearOutput(true); If you would like to access the content document of the Browser Console this can be done with the HUDService. This example here makes it so that when you mouse over the "Clear" button it will clear the Browser Console: Components.utils.import("resource://devtools/shared/Loader.jsm"); var HUDService = devtools.require("devtools/client/webconsole/hudservice"); var ...
...f you would like to access the content document of the Browser Console this can be done with the HUDService. This example here makes it so that when you mouse over the "Clear" button it will clear the Browser Console: Components.utils.import("resource://devtools/shared/Loader.jsm"); var HUDService = devtools.require("devtools/client/webconsole/hudservice"); var hud = HUDService.getBrowserConsole
(); var clearBtn = hud.chromeWindow.document.querySelector('.webconsole-clear-console-button'); clearBtn.addEventListener('mouseover', function
() { hud.jsterm.clearOutput(true); }, false); Bonus Features Available For Add-on SDK add-ons, the console API is available automatically. Here's an example add-on that just logs an error when the user clicks a widget: widget = require("sdk/widget").Wid...
...ver', function
() { hud.jsterm.clearOutput(true); }, false); Bonus Features Available For Add-on SDK add-ons, the console API is available automatically. Here's an example add-on that just logs an error when the user clicks a widget: widget = require("sdk/widget").Widget({ id: "an-error-happened", label: "Error!", width: 40, content: "Error!", onClick: logError }); function logError
() { console.error("something went wrong!"); } If you build this as an XPI file, then open the Browser Console, then open the XPI file in Firefox and install it, you'll see a widget labeled "Error!" in the Add-on bar: Click the icon. You'll see output like this in the Browser Console: For Add-on SDK-based add-ons only, the message is prefixed with the name of the add-on ("log-error"), making ...
...reter gets access to the tabbrowser object, through the gBrowser global, and that enables you to control the browser through the command line. Try running this code in the Browser Console's command line (remember that to send multiple lines to the Browser Console, use Shift+Enter): var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab); newTabBrowser.addEventListener("load", function
() { newTabBrowser.contentDocument.body.innerHTML = "<h1>this page has been eaten</h1>"; }, true); newTabBrowser.contentDocument.location.href = "https://mozilla.org/"; It adds a listener to the currently selected tab's load event that will eat the new page, then loads a new page. Note: You can restart the browser with the command Ctrl + Alt + R (Windows, Linux) or Cmd + Alt + R (Mac) This comm...
DOM allocation example - Firefox Developer Tools
This article describes a very simple web page that we'll use to illustrate some features of the Memory tool. You can try out the site at https://mdn.github.io/performance-scenarios/dom-allocs/alloc.html. ...
... use to illustrate some features of the Memory tool. You can try out the site at https://mdn.github.io/performance-scenarios/dom-allocs/alloc.html. ...
...ar toolbarCount = 200; function getRandomInt(min, max) { return Math.floor(Math.random
() * (max - min + 1)) + min; } function createToolbarButton
() { var toolbarButton = document.createElement("span"); toolbarButton.classList.add("toolbarbutton"); // stop Spidermonkey from sharing instances toolbarButton[getRandomInt(0,5000)] = "foo"; return toolbarButton; } function createToolbar
() { var toolbar = document.createElement("div"); // stop Spidermonkey from sharing instances toolbar[getRandomInt(0,5000)] = "foo"; for (var i = 0; i < toolbarButtonCount; i++) { var toolbarButton = createToolbarButton
(); toolbar.appendChild(toolbarButton); } return toolbar; } function createToolbars
() { var container = document.getElementById("container"); for (var i = 0; ...
...top Spidermonkey from sharing instances toolbar[getRandomInt(0,5000)] = "foo"; for (var i = 0; i < toolbarButtonCount; i++) { var toolbarButton = createToolbarButton
(); toolbar.appendChild(toolbarButton); } return toolbar; } function createToolbars
() { var container = document.getElementById("container"); for (var i = 0; i < toolbarCount; i++) { var toolbar = createToolbar
(); container.appendChild(toolbar); } } createToolbars
(); A simple pseudocode representation of how this code operates looks like this: createToolbars
() -> createToolbar
() // called 200 times, creates 1 DIV element each time -> createToolbarButton
() // called 20 times per toolbar, creates 1 SPAN element each time In total, then, it creates 200 HTMLDivElement objects, and 4000 HT...
Allocations - Firefox Developer Tools
cludes the following columns: Self Count: the number of allocation-samples that were taken in this function (also shown as a percentage of the total) Self Bytes: the total number of bytes allocated in the allocation-samples in this function (also shown as a percentage of the total) Rows are sorted by the "Self Bytes" column. So in the example above: 8904 samples were taken in signalLater
(), which is 28.57% of the total number of samples taken those samples allocated 1102888 bytes, which is 30.01% of the total memory allocated in all samples Next to each function name is a disclosure arrow. Click this to see the places this function was called from: Here you can see that signalLater
() was called from two places: removeInner
() and setSelectionInner
(). In this way you can walk b...
...ken only in this function. "Total" records samples taken in this function or in functions called by this function. At the top level, these are always the same, since the view presents "leaf" functions at the top level (that is, it presents an inverted view of the call stack). But if you start walking back up the call stack, you'll see the difference: Here, 8904 samples were taken in signalLater
(). ...
...nction. "Total" records samples taken in this function or in functions called by this function. At the top level, these are always the same, since the view presents "leaf" functions at the top level (that is, it presents an inverted view of the call stack). But if you start walking back up the call stack, you'll see the difference: Here, 8904 samples were taken in signalLater
(). ...
...his function or in functions called by this function. At the top level, these are always the same, since the view presents "leaf" functions at the top level (that is, it presents an inverted view of the call stack). But if you start walking back up the call stack, you'll see the difference: Here, 8904 samples were taken in signalLater
(). But signalLater
() was called from two places: removeInner
() and setSelectionInner
(). Both these functions have 0 in Self Count, meaning that no allocations were seen directly in these functions. However, removeInner
() has 8901 in Total Count, while setSelectionInner
() has just 3 in Total Count. This is telling us that, of the 8904 allocations seen in signalLater
(), all but three came through the removeInner
() branch. Allocations and garbage collection O...
Web Console remoting - Firefox Developer Tools
console.js, and search for WebConsoleConnectionProxy. The new Web Console actors are: The WebConsoleActor allows JS evaluation, autocomplete, start/stop listeners, etc. The NetworkEventActor is used for each new network request. The client can request further network event details - like response body or request headers. To attach to the WebConsoleActor, follow these steps: connectToServer
() // the usual listTabs
() pickTheTabYouWant
() debuggerClient.attachConsole(tab.consoleActor, listeners, onAttachConsole) The listeners argument is an array which specifies listeners you want to start in the web console. These can be: page errors, window.console API messages, network activity, and file activity. For example: ["PageError", "ConsoleAPI", "NetworkActivity", "FileActivity"] The Web...
...teners by default. The client has the option to start each listener when needed. This approach allows for lower resource usage on the server - this is a potential issue if the server runs on devices with fewer resources. The onAttachConsole callback receives a new instance of the WebConsoleClient object. This object provides methods that abstract away protocol packets, things like startListeners
(), stopListeners
(), etc. Protocol packets look as follows: { "to": "root", "type": "listTabs" } { "from": "root", "consoleActor": "conn0.console9", "selected": 2, "tabs": [ { "actor": "conn0.tab2", "consoleActor": "conn0.console7", "title": "", "url": "https://tbpl.mozilla.org/?tree=Fx-Team" }, // ... ] } Notice that the consoleActor is also availab...
...to": "conn0.console9", "type": "evaluateJS", "text": "document", "bindObjectActor": null, "frameActor": null, "url": null, "selectedNodeActor": null, } The bindObjectActor property is an optional ObjectActor ID that points to a Debugger.Object. This option allows you to bind _self to the Debugger.Object of the given object actor, during string evaluation. See evalInGlobalWithBindings
() for information about bindings. The variable view needs to update objects and it does so by binding _self to the Debugger.Object of the ObjectActor that is being viewed. As such, variable view sends strings like these for evaluation: _self["prop"] = value; The frameActor property is an optional FrameActor ID. The FA holds a reference to a Debugger.Frame. This option allows you to evaluate...
...sult": { "type": "object", "className": "HTMLDocument", "actor": "conn0.consoleObj20" "extensible": true, "frozen": false, "sealed": false }, "timestamp": 1347306273605, "exception": null, "exceptionMessage": null, "helperResult": null } exception holds the JSON-ification of the exception thrown during evaluation. exceptionMessage holds the exception.toString
() result. result has the result ObjectActor instance. helperResult is anything that might come from a JSTerm helper result, JSON stuff (not content objects!). In Firefox 23: we renamed the error and errorMessage properties to exception and exceptionMessage respectively, to avoid conflict with the default properties used when protocol errors occur. Autocomplete and more The autocomplete requ...
Animation.playbackRate - Web APIs
ctor, so for example a value of 2 would double the playback rate. Setting an animation's playbackRate to 0 effectively pauses the animation (however, its playstate does not necessarily become paused). ...
...ack rate. Setting an animation's playbackRate to 0 effectively pauses the animation (however, its playstate does not necessarily become paused). Examples In the Growing/Shrinking Alice Game example, clicking or tapping the bottle causes Alice's growing animation (aliceChange) to reverse, causing her to shrink: var shrinkAlice = function
() { aliceChange.playbackRate = -1; aliceChange.play
(); } // On tap or click, Alice will shrink. bottle.addEventListener("mousedown", shrinkAlice, false); bottle.addEventListener("touchstart", shrinkAlice, false); Contrariwise, clicking on the cake causes her to "grow," playing aliceChange forwards again: var growAlice = function
() { aliceChange.playbackRate = 1; aliceChange.play
(); } // On tap or click, Alice will grow. cake.addEventListe...
...ow," playing aliceChange forwards again: var growAlice = function
() { aliceChange.playbackRate = 1; aliceChange.play
(); } // On tap or click, Alice will grow. ...
... Working Draft ...
AudioParam.value - Web APIs
you set it to. Consider this example: const source = new AudioBufferSourceNode(...); const rate = 5.3; source.playbackRate.value = rate; console.log(source.playbackRate.value === rate); The log output will be false, because the playback rate parameter, rate, was converted to the 32-bit floating-point number closest to 5.3, which yields 5.300000190734863. One solution is to use the Math.fround
() method, which returns the single-precision value equivalent to the 64-bit JavaScript value specified--when setting value, like this: const source = new AudioBufferSourceNode(...); const rate = Math.fround(5.3); source.playbackRate.value = rate; console.log(source.playbackRate.value === rate); In this case, the log output will be true. Value of a property which is changing over time The value ...
..., and will remain the parameter's value until the first render quantum in which the value is altered. During each render quantum, the browser does the following things related to managing the value of a parameter: If the value setter has been used, the parameter's value is changed to the value given. ...
...uantum in which the value is altered. During each render quantum, the browser does the following things related to managing the value of a parameter: If the value setter has been used, the parameter's value is changed to the value given. If the current time equals or exceeds the time specified by a previous call to setValueAtTime
(), the value is changed to the value passed into setValueAtTime
(). If any gradiated or ramped value changing methods have been called and the current time is within the time range over which the graduated change should occur, the value is updated based on the appropriate algorithm. These ramped or gradiated value-changing methods include linearRampToValueAtTime
(), setTargetAtTime
(), and setValueCurveAtTime
(). Thus, the value of a parameter is maintained to a...
...e value is updated based on the appropriate algorithm. These ramped or gradiated value-changing methods include linearRampToValueAtTime
(), setTargetAtTime
(), and setValueCurveAtTime
(). Thus, the value of a parameter is maintained to accurately reflect the state of the parameter over time. Example This example instantly changes the volume of a GainNode to 40%. const audioCtx = new AudioContext
(); const gainNode = audioCtx.createGain
(); gainNode.gain.value = 0.4; //which is identical to: gainNode.gain.setValueAtTime(0.4, audioCtx.currentTime); Specifications Specification Status Comment Web Audio APIThe definition of 'value' in that specification. Working Draft ...
AudioWorkletGlobalScope - Web APIs
tum) after the processing of each audio block. currentTime Read only Returns a double that represents the ever-increasing context time of the audio block being processed. It is equal to the currentTime property of the BaseAudioContext the worklet belongs to. sampleRate Read only Returns a float that represents the sample rate of the associated BaseAudioContext. Methods registerProcessor
() Registers a class derived from the AudioWorkletProcessor interface. The class can then be used by creating an AudioWorkletNode, providing its registered name. Examples In this example we output all global properties into the console in the constructor of a custom AudioWorkletProcessor. First we need to define the processor, and register it. Note that this should be done in a separate file. ...
...n be used by creating an AudioWorkletNode, providing its registered name. Examples In this example we output all global properties into the console in the constructor of a custom AudioWorkletProcessor. First we need to define the processor, and register it. Note that this should be done in a separate file. ...
...reating an AudioWorkletNode, providing its registered name. Examples In this example we output all global properties into the console in the constructor of a custom AudioWorkletProcessor. First we need to define the processor, and register it. Note that this should be done in a separate file. ...
...wavetable const usefulVariable = 42 console.log(usefulVariable) registerProcessor('test-processor', TestProcessor) Next, in our main scripts file we'll load the processor, create an instance of AudioWorkletNode -- passing the name of the processor to it -- and connect the node to an audio graph. We should see the output of console.log calls in the console: const audioContext = new AudioContext
() await audioContext.audioWorklet.addModule('test-processor.js') const testNode = new AudioWorkletNode(audioContext, 'test-processor') testNode.connect(audioContext.destination) Specifications Specification Status Comment Web Audio APIThe definition of 'AudioWorkletGlobalScope' in that specification. Working Draft ...
BasicCardRequest - Web APIs
the server to check support for the card given the information coded into the account number. Card network identifiers The W3C maintains an official list of approved card network identifier strings, which may be used in the supportedNetworks list. Those are: amex cartebancaire diners discover jcb mastercard mir unionpay visa Examples In the following example, the PaymentRequest
() constructor is used to create a new payment request, which takes three objects as parameters -- one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object that describes what data is needed to fullfil the payment (e.g., a shipping address). The first of these three ...
...mount', amount: {currency: 'USD', value: '65.00'} } ], shippingOptions: [ { id: 'standard', label: 'Standard shipping', amount: {currency: 'USD', value: '0.00'}, selected: true } ] }; var options = {requestShipping: true}; try { var request = new PaymentRequest(supportedInstruments, details, options); // Add event listeners here. ...
... } ], shippingOptions: [ { id: 'standard', label: 'Standard shipping', amount: {currency: 'USD', value: '0.00'}, selected: true } ] }; var options = {requestShipping: true}; try { var request = new PaymentRequest(supportedInstruments, details, options); // Add event listeners here. // Call show
() to trigger the browser's payment flow. ...
... }; var options = {requestShipping: true}; try { var request = new PaymentRequest(supportedInstruments, details, options); // Add event listeners here. // Call show
() to trigger the browser's payment flow. request.show
().then(function(instrumentResponse) { // Do something with the response from the UI. }) .catch(function(err) { // Do something with the error from request.show
(). }); } catch (e) { // Catch any other errors. } Once the payment flow has been triggered using PaymentRequest.show
() and the promise resolves successfully, the PaymentResponse object available inside the fulfilled promise (instrumentResponse above) will have a PaymentResponse.details property that will contain response details. This has to conform to the structure defined by the BasicCardRes...
BasicCardResponse - Web APIs
ext Optional Contains the expiry month of the card used to make the payment. BasicCardResponse.expiryYear Read only Secure context Optional Contains the expiry year of the card used to make the payment. BasicCardResponse.billingAddress Read only Secure context Optional Contains the billing address of the card used to make the payment. Examples In the following example, the PaymentRequest
() constructor is used to create a new payment request, which takes three objects as parameters -- one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options. The first of these three (supportedInstruments in the example below) contains a dat...
...mount', amount: {currency: 'USD', value: '65.00'} } ], shippingOptions: [ { id: 'standard', label: 'Standard shipping', amount: {currency: 'USD', value: '0.00'}, selected: true } ] }; var options = {requestShipping: true}; try { var request = new PaymentRequest(supportedInstruments, details, options); // Add event listeners here. ...
... } ], shippingOptions: [ { id: 'standard', label: 'Standard shipping', amount: {currency: 'USD', value: '0.00'}, selected: true } ] }; var options = {requestShipping: true}; try { var request = new PaymentRequest(supportedInstruments, details, options); // Add event listeners here. // Call show
() to trigger the browser's payment flow. ...
... }; var options = {requestShipping: true}; try { var request = new PaymentRequest(supportedInstruments, details, options); // Add event listeners here. // Call show
() to trigger the browser's payment flow. request.show
().then(function(instrumentResponse) { // Do something with the response from the UI. }) .catch(function(err) { // Do something with the error from request.show
(). }); } catch (e) { // Catch any other errors. } Once the payment flow has been triggered using PaymentRequest.show
() and the promise resolves successfully, the PaymentResponse object available inside the fulfilled promise (instrumentResponse above) will have a PaymentResponse.details property that will contain response details. This has to conform to the structure defined by the BasicCardRes...
Using the Beacon API - Web APIs
The Beacon interface schedules an asynchronous and non-blocking request to a web server. Beacon requests use HTTP POST and do not require a response. Beacon requests are guaranteed to be initiated before the page unloads. This document contains examples of the Beacon interfaces. See Beacon API for an overview. Navigator.sendBeacon
() The Beacon API's Navigator.sendBeacon
() method sends a beacon request to the server in the global browsing context. The method takes two arguments: the URL and the data to send. 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. The following example specifies a handler for the load...
...sing context. The method takes two arguments: the URL and the data to send. 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. The following example specifies a handler for the load and beforeunload events. The handler calls sendBeacon
() with the current URL. window.onload = window.onunload = function analytics(event) { if (!navigator.sendBeacon) return; var url = "https://example.com/analytics"; // Create the data to send var data = "state=" + event.type + "&location=" + location.href; // Send the beacon var status = navigator.sendBeacon(url, data); // Log the data and result console.log("sendBeacon: URL = ",...
...alytics"; // Create the data to send var data = "state=" + event.type + "&location=" + location.href; // Send the beacon var status = navigator.sendBeacon(url, data); // Log the data and result console.log("sendBeacon: URL = ", url, "; data = ", data, "; status = ", status); }; The following example creates a submit handler and when that event is fired, the handler calls sendBeacon
(). window.onsubmit = function send_analytics
() { var data = JSON.stringify({ location: location.href, time: Date
() }); navigator.sendBeacon('/analytics', data); }; WorkerNavigator.sendBeacon
() The Beacon API's WorkerNavigator.sendBeacon
() method works identically to the usual method, but is accessible from worker global scope. In the following example, a Worker sends a beacon us...
...url, data) { // Create the worker object var myWorker = new Worker("worker-using.js"); // Send the worker the URL and data to beacon myWorker.postMessage([url, data]); // Set up a message handler to receive the success/fail message from the worker myWorker.onmessage = function(event) { var msg = event.data; // Log worker's send status console.log("Worker reply: sendBeacon
() status = " + msg); }; } This code snippet is for the worker (worker-using.js): onmessage = function(event) { var msg = event.data; // Split the URL and data from the message var url = msg[0]; var data = msg[1]; // If the browser supports worker sendBeacon
(), then send the beacon; otherwise // return failure message to the global context if (self.navigator.sendBeacon) { var...
BluetoothDevice - Web APIs
BluetoothDev...
... BluetoothDevice.name Read only A DOMStrin...
...vices a human-readable name for the device. BluetoothDevice.gatt Read only A reference to the device's BluetoothRemoteGATTServer. BluetoothDevice.uuids Read only Lists the UUID's of GATT services provided by the device, that the current origin is allowed to access. BluetoothDevice.watchingAdvertisements Read only If advertisments were activated using BluetoothDevice.watchAdvertisements
(). Non-standard Chrome OS properties These properties were only implemented on Google's Chrome OS 45 and removed from Chrome 52. BluetoothDevice.adData Read only An instance of BluetoothAdvertisingData containing the most recent advertising data received for the device. BluetoothDevice.deviceClass Read only A number representing the Bluetooth devices "Class of Device". Bluetoot...
...ersion Read only The 16-bit Product Version field in the pnp_id characteristic in the device_information service. BluetoothDevice.paired Read only A Boolean value indicating whether the device is paired with the system. BluetoothDevice.gattServer Read only A reference to the device's GATT server or null if the device is disconnected. Methods BluetoothDevice.watchAdvertisments
() A Promise that resolves to undefined or is rejected with an error if advetisments can't shown for any reason. BluetoothDevice.unwatchAdvertisments
() Stops watching for advertisments. BluetoothDevice.connectGATT
() A Promise that resolves to an instance of BluetoothGATTRemoteServer. Specifications Specification Status Comment Web BluetoothThe definition of 'B...
CSSMathValue.operator - Web APIs
. Syntax var aString = CSSMathValue.operator; Value A String. ...
...athValue.operator; Value A String. Interface Value CSSMathSum "sum" CSSMathProduct "product" CSSMathMin "min" CSSMathMax "max" CSSMathClamp "clamp" CSSMathNegate "negate" CSSMathInvert "invert" Examples We create an element with a width determined using a calc
() function, then console.log
() the operator. ...
...nterface Value CSSMathSum "sum" CSSMathProduct "product" CSSMathMin "min" CSSMathMax "max" CSSMathClamp "clamp" CSSMathNegate "negate" CSSMathInvert "invert" Examples We create an element with a width determined using a calc
() function, then console.log
() the operator. ...
...CSSMathNegate "negate" CSSMathInvert "invert" Examples We create an element with a width determined using a calc
() function, then console.log
() the operator. ...
CSSStyleSheet - Web APIs
ed. Properties Inherits properties from its parent, StyleSheet. cssRules Read only Returns a live CSSRuleList which maintains an up-to-date list of the CSSRule objects that comprise the stylesheet. ...
...Inherits properties from its parent, StyleSheet. cssRules Read only Returns a live CSSRuleList which maintains an up-to-date list of the CSSRule objects that comprise the stylesheet. This is normally used to access individual rules like this: styleSheet.cssRules[i] // where i = 0..cssRules.length-1 To add or remove items in cssRules, use the CSSStyleSheet's insertRule
() and deleteRule
() methods. ...
... i = 0..cssRules.length-1 To add or remove items in cssRules, use the CSSStyleSheet's insertRule
() and deleteRule
() methods. ownerRule Read only If this stylesheet is imported into the document using an @import rule, the ownerRule property returns the corresponding CSSImportRule; otherwise, this property's value is null. Methods Inherits methods from its parent, StyleSheet. deleteRule
() Deletes the rule at the specified index into the stylesheet's rule list. insertRule
() Inserts a new rule at the specified position in the stylesheet, given the textual representation of the rule. Legacy properties These properties are legacy properties first introduced by Microsoft long ago; they shouldn't be used but are not likely to be removed anytime soon. rules Read only The rules...
... rules Read only The rules property is functionally identical to the standard cssRules property; it returns a live CSSRuleList which maintains an up-to-date list of all of the rules in the style sheet. Legacy methods These methods are legacy methods first introduced by Microsoft; they should not be used if they can be avoided, but are not in danger of being removed anytime soon. addRule
() Adds a new rule to the stylesheet given the selector to which the style applies and the style block to apply to the matching elements. This differs from insertRule
(), which simply takes the textual representation of the entire rule as a single string. removeRule
() Functionally identical to deleteRule
(); removes the rule at the specified index from the stylesheet's rule list. Notes In ...
Using dynamic styling information - Web APIs
css"> #p1 { border: solid blue 2px; } </style> </head> <body> <!-- passes a reference to the element's object as parameter 'this'. --> <p id="p1" onclick="alterStyle(this);"> Click here to change background color. </p> <!-- passes the 'p1' id of another element's style to modify. --> <button onclick="resetStyle('p1');">Reset background color</button> </body> </html> The getComputedStyle
() method on the document.defaultView object returns all styles that have actually been computed for an element. See Example 6: getComputedStyle in the examples chapter for more information on how to use this method. DOM Style Object The style object represents an individual style statement. Unlike the individual rules available from the document.styleSheets collection, the style object is accesse...
... that style is applied. It represents the in-line styles on a particular element. ...
... Using the setAttribute method Note that you can al...
...e Property Example</title> <link rel="StyleSheet" href="example.css" type="text/css"> <script type="text/javascript"> function stilo
() { document.getElementById('d').style.color = 'orange'; } function resetStyle
() { document.getElementById('d').style.color = 'black'; } </script> </head> <body> <div id="d" class="thunder">Thunder</div> <button onclick="stilo
()">Click here to change text color</button> <button onclick="resetStyle
()">Reset text color</button> </body> </html> The media and type of the style may or may not be given. Using the setAttribute method Note that you can also change style of an element by getting a reference to it and then use its setAttribute method to specify the CSS property and its value. var el = document.getElemen...
CanvasRenderingContext2D.lineDashOffset - Web APIs
The CanvasRenderingContext2D.lineDashOffset property of the Canvas 2D API sets the line dash offset, or "phase." Note: Lines are drawn by calling the stroke
() method. Syntax ctx.lineDashOffset = value; value A float specifying the amount of the line dash offset. The default value is 0.0. Examples Offsetting a line dash This example draws two dashed lines. The first has no dash offset. The second has a dash offset of 4. ...
...t of the line dash offset. The default value is 0.0. Examples Offsetting a line dash This example draws two dashed lines. The first has no dash offset. The second has a dash offset of 4. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.setLineDash([4, 16]); // Dashed line with no offset ctx.beginPath
(); ctx.moveTo(0, 50); ctx.lineTo(300, 50); ctx.stroke
(); // Dashed line with offset of 4 ctx.beginPath
(); ctx.strokeStyle = 'red'; ctx.lineDashOffset = 4; ctx.moveTo(0, 100); ctx.lineTo(300, 100); ctx.stroke
(); Result The line with a dash offset is drawn in red. Marching ants The marching ants effect is an animation technique often found in selection tools of computer graphics programs. It ...
...n red. Marching ants The marching ants effect is an animation technique often found in selection tools of computer graphics programs. It helps the user to distinguish the selection border from the image background by animating the border. ...
...h the selection border from the image background by animating the border. HTML <canvas id="canvas"></canvas> const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let offset = 0; function draw
() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.setLineDash([4, 2]); ctx.lineDashOffset = -offset; ctx.strokeRect(10, 10, 100, 100); } function march
() { offset++; if (offset > 16) { offset = 0; } draw
(); setTimeout(march, 20); } march
(); Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.lineDashOffset' in that specification. Living Standard ...
CharacterData - Web APIs
d element is the last one in the list. NonDocumentTypeChildNode.previousElementSibling Read only Returns the Element immediately prior to the specified one in its parent's children list, or null if the specified element is the first one in the list. Methods Inherits methods from its parent, Node, and implements the ChildNode and NonDocumentTypeChildNode interface. ...
...in its parent's children list, or null if the specified element is the first one in the list. Methods Inherits methods from its parent, Node, and implements the ChildNode and NonDocumentTypeChildNode interface. CharacterData.appendData
() Appends the given DOMString to the CharacterData.data string; when this method returns, data contains the concatenated DOMString. ...
...face. CharacterData.appendData
() Appends the given DOMString to the CharacterData.data string; when this method returns, data contains the concatenated DOMString. CharacterData.deleteData
() Removes the specified amount of characters, starting at the specified offset, from the CharacterData.data string; when this method returns, data contains the shortened DOMString. CharacterData.insertData
() Inserts the specified characters, at the specified offset, in the CharacterData.data string; when this method returns, data contains the modified DOMString. ChildNode.remove
() Removes the object from its parent children list. ...
...ified offset, from the CharacterData.data string; when this method returns, data contains the shortened DOMString. CharacterData.insertData
() Inserts the specified characters, at the specified offset, in the CharacterData.data string; when this method returns, data contains the modified DOMString. ChildNode.remove
() Removes the object from its parent children list. CharacterData.replaceData
() Replaces the specified amount of characters, starting at the specified offset, with the specified DOMString; when this method returns, data contains the modified DOMString. CharacterData.substringData
() Returns a DOMString containing the part of CharacterData.data of the specified length and starting at the specified offset. Specifications Specification Status Comment ...
Clients - Web APIs
The Clients interface provides access to Client objects. Access it via self.clients within a service worker. Methods Clients.get
() Returns a Promise for 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. ...
...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. ...
...ationclick', event => { event.waitUntil(async function
() { const allClients = await clients.matchAll({ includeUncontrolled: true }); let chatClient; // Let's see if we already have a chat window open: for (const client of allClients) { const url = new URL(client.url); if (url.pathname == '/chat/') { // Excellent, let's use it! ...
... Working Draft Initial definition ...
Clipboard - Web APIs
temporary data buffer, sometimes called the paste buffer, that can be accessed from most or all programs within the environment via defined programming interfaces. A typical application accesses clipboard functionality by mapping user input such as keybindings, menu selections, etc. to these interfaces. Methods Clipboard is based on the EventTarget interface, and includes its methods. ...
...rd functionality by mapping user input such as keybindings, menu selections, etc. to these interfaces. Methods Clipboard is based on the EventTarget interface, and includes its methods. read
() Requests arbitrary data (such as images) from the clipboard, returning a Promise. When the data has been retrieved, the promise is resolved with a DataTransfer object that provides the data. readText
() Requests text from the system clipboard; returns a Promise which is resolved with a DOMString containing the clipboard's text once it's available. write
() Writes arbitrary data to the system clipboard. ...
... Clipboard availability The asynchronous clipboard API is a relatively recent addition, and the process of implementing it in browsers is not yet complete. ...
...rocess of integrating this API is happening gradually in most browsers. For example, Firefox does not yet support the "clipboard-read" and "clipboard-write" permissions, so access to the methods that access and change the contents of the clipboard are restricted in other ways. For WebExtensions, you can request the clipboardRead and clipboardWrite permissions to be able to use clipboard.readText
() and clipboard.writeText
(). Content scripts applied on HTTP sites do not have access to the clipboard object. See extensions in Firefox 63. In addition, read
() and write
() are disabled by default and require changing a preference to enable them. Check the compatibility tables for each method before using it. Specifications Specification Status Comment Clipboard API and e...
ContentIndex - Web APIs
access to the content index interface. // reference registration const registration = await navigator.serviceWorker.ready; // feature detection if ('index' in registration) { // Content Index API functionality const contentIndex = registration.index; } Adding to the Content Index Here we're declaring an item in the correct format and creating an asynchronous function which uses the add
() method to register it with the content index. // 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' }; // our asynchronous function to add...
...return; } // register content try { await registration.index.add(data); } catch (e) { console.log('Failed to register content: ', e.message); } } Retrieving Items Within The Current Index The below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface. ...
...n The Current Index The below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface. ...
...) 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 Initial definition. ...
Content Index API - Web APIs
access to the content index interface. // reference registration const registration = await navigator.serviceWorker.ready; // feature detection if ('index' in registration) { // Content Index API functionality const contentIndex = registration.index; } Adding to the Content Index Here we're declaring an item in the correct format and creating an asynchronous function which uses the add
() method to register it with the content index. // 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' }; // our asynchronous function to add...
...return; } // register content try { await registration.index.add(data); } catch (e) { console.log('Failed to register content: ', e.message); } } Retrieving Items Within The Current Index The below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface. ...
...n The Current Index The below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface. ...
...) 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.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 }); The contentdelete event is only fired when the deletion happens due to int...
DOMTokenList - Web APIs
enList.replace(oldToken, newToken) Replaces token with newToken. DOMTokenList.supports(token) Returns true if a given token is in the associated attribute's supported tokens. DOMTokenList.toggle(token [, force]) Removes token from the list if it exists, or adds token to the list if it doesn't. Returns a boolean indicating whether token is in the list after the operation. ...
... from the list if it exists, or adds token to the list if it doesn't. Returns a boolean indicating whether token is in the list after the operation. DOMTokenList.entries
() Returns an iterator, allowing you to go through all key/value pairs contained in this object. DOMTokenList.forEach(callback [, thisArg]) Executes a provided callback function once per DOMTokenList element. DOMTokenList.keys
() Returns an iterator, allowing you to go through all keys of the key/value pairs contained in this object. DOMTokenList.values
() Returns an iterator, allowing you to go through all values of the key/value pairs contained in this object. Examples In the following simple example, we retrieve the list of classes set on a <p> element as a DOMTokenList using Element.classList, add a class using D...
...erator, allowing you to go through all keys of the key/value pairs contained in this object. DOMTokenList.values
() Returns an iterator, allowing you to go through all values of the key/value pairs contained in this object. Examples In the following simple example, we retrieve the list of classes set on a <p> element as a DOMTokenList using Element.classList, add a class using DOMTokenList.add
(), and then update the Node.textContent of the <p> to equal the DOMTokenList. First, the HTML: <p class="a b c"></p> Now the JavaScript: let para = document.querySelector("p"); let classes = para.classList; para.classList.add("d"); para.textContent = `paragraph classList is "${classes}"`; The output looks like this: Trimming of whitespace and removal of duplicates Methods that modify the D...
...t of the <p> to equal the DOMTokenList. First, the HTML: <p class="a b c"></p> Now the JavaScript: let para = document.querySelector("p"); let classes = para.classList; para.classList.add("d"); para.textContent = `paragraph classList is "${classes}"`; The output looks like this: Trimming of whitespace and removal of duplicates Methods that modify the DOMTokenList (such as DOMTokenList.add
()) automatically trim any excess Whitespace and remove duplicate values from the list. For example: <span class=" d d e f"></span> let span = document.querySelector("span"); let classes = span.classList; span.classList.add("x"); span.textContent = `span classList is "${classes}"`; The output looks like this: Specifications Specification Status Comment DOMThe ...
DedicatedWorkerGlobalScope - Web APIs
aScript 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. 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. WorkerLo...
...Worker.postMessage method.) DedicatedWorkerGlobalScope.onmessageerror Is an EventHandler representing the code to be called when the messageerror event is raised. Methods This interface inherits methods from the WorkerGlobalScope interface, and its parent EventTarget, and therefore implements methods from WindowTimers, WindowBase64, and WindowEventHandlers. DedicatedWorkerGlobalScope.close
() Discards any tasks queued in the WorkerGlobalScope's event loop, effectively closing this particular scope. DedicatedWorkerGlobalScope.postMessage
() Sends a message -- which can consist of any JavaScript object -- to the parent document that first spawned the worker. Inherited from WorkerGlobalScope WorkerGlobalScope.dump
() Writes a message to the console. WorkerGlobalScope.importScri...
...iscards any tasks queued in the WorkerGlobalScope's event loop, effectively closing this particular scope. DedicatedWorkerGlobalScope.postMessage
() Sends a message -- which can consist of any JavaScript object -- to the parent document that first spawned the worker. Inherited from WorkerGlobalScope WorkerGlobalScope.dump
() Writes a message to the console. WorkerGlobalScope.importScripts
() Imports one or more scripts into the worker's scope. You can specify as many as you'd like, separated by commas. For example: importScripts('foo.js', 'bar.js'); Implemented from other places WindowBase64.atob
() Decodes a string of data which has been encoded using base-64 encoding. WindowBase64.btoa
() Creates a base-64 encoded ASCII string from a string of binary data. WindowTimers.clea...
... one or more scripts into the worker's scope. You can specify as many as you'd like, separated by commas. For example: importScripts('foo.js', 'bar.js'); Implemented from other places WindowBase64.atob
() Decodes a string of data which has been encoded using base-64 encoding. WindowBase64.btoa
() Creates a base-64 encoded ASCII string from a string of binary data. WindowTimers.clearInterval
() Cancels the repeated execution set using WindowTimers.setInterval
(). WindowTimers.clearTimeout
() Cancels the repeated execution set using WindowTimers.setTimeout
(). WindowTimers.setInterval
() Schedules the execution of a function every X milliseconds. WindowTimers.setTimeout
() Sets a delay for executing a function. Events message Fired when the worker receives a message from its par...
DynamicsCompressorNode - Web APIs
on effect, which lowers the volume of the loudest parts of the signal in order to help prevent clipping and distortion that can occur when multiple sounds are played and multiplexed together at once. This is often used in musical production and game audio. DynamicsCompressorNode is an AudioNode that has exactly one input and one output; it is created using the AudioContext.createDynamicsCompressor
() method. Number of inputs 1 Number of outputs 1 Channel count mode "clamped-max" Channel count 2 Channel interpretation "speakers" Constructor DynamicsCompressorNode
() Creates a new instance of an DynamicsCompressorNode object. Properties Inherits properties from its parent, AudioNode. DynamicsCompressorNode.threshold R...
...ioParam representing the amount of time, in seconds, required to reduce the gain by 10 dB. DynamicsCompressorNode.release Read only Is a k-rate AudioParam representing the amount of time, in seconds, required to increase the gain by 10 dB. Methods No specific methods; inherits methods from its parent, AudioNode. ...
...rates a simple usage of createDynamicsCompressor
() to add compression to an audio track. For a more complete example, have a look at our basic Compressor example (view the source code). ...
...ValueAtTime(-50, audioCtx.currentTime); compressor.knee.setValueAtTime(40, audioCtx.currentTime); compressor.ratio.setValueAtTime(12, audioCtx.currentTime); compressor.attack.setValueAtTime(0, audioCtx.currentTime); compressor.release.setValueAtTime(0.25, audioCtx.currentTime); // connect the AudioBufferSourceNode to the destination source.connect(audioCtx.destination); button.onclick = function
() { var active = button.getAttribute('data-active'); if(active == 'false') { button.setAttribute('data-active', 'true'); button.innerHTML = 'Remove compression'; source.disconnect(audioCtx.destination); source.connect(compressor); compressor.connect(audioCtx.destination); } else if(active == 'true') { button.setAttribute('data-active', 'false'); button.innerHTML =...
EffectTiming.delay - Web APIs
The value of delay corresponds directly to EffectTiming.delay in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
...The value of delay corresponds directly to EffectTiming.delay in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
...The value of delay corresponds directly to EffectTiming.delay in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
...nds; Value A number specifying the delay, in milliseconds, from the start of the animation's play cycle to the beginning of its active interval (the time index at which actual animation begins). Defaults to 0. ...
EffectTiming.duration - Web APIs
The value of duration corresponds directly to AnimationEffectTimingReadOnly.duration in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
...The value of duration corresponds directly to AnimationEffectTimingReadOnly.duration in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
...The value of duration corresponds directly to AnimationEffectTimingReadOnly.duration in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
...nsider using "auto" rather than 0 if that makes sense. Exceptions TypeError The specified value is either a string other than "auto", a number less than zero, NaN, or some other type of object entirely. ...
Element: mousedown event - Web APIs
l use to draw. Drawing begins when the mousedown event fires. First we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isDrawing to true. As the mouse moves over the page, the mousemove event fires. If isDrawing is true, the event handler calls the drawLine function to draw a line from the stored x and y values to the current location. When the drawLine
() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. HTML <h1>Drawing with mouse events</h1> <canvas id="myPics" width="560" height="360"></canvas> CSS canvas { border: 1px solid black; width: 560px; height: 360px; } JavaScript // When tru...
... Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'mousedo...
... Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'mousedown' in that specification. Obsolete ...
... Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'mousedown' in that specification. Obsolete ...
Element: mousemove event - Web APIs
l use to draw. Drawing begins when the mousedown event fires. First we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isDrawing to true. As the mouse moves over the page, the mousemove event fires. If isDrawing is true, the event handler calls the drawLine function to draw a line from the stored x and y values to the current location. When the drawLine
() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. HTML <h1>Drawing with mouse events</h1> <canvas id="myPics" width="560" height="360"></canvas> CSS canvas { border: 1px solid black; width: 560px; height: 360px; } JavaScript // When tru...
... Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'mousemo...
... Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'mousemove' in that specification. Obsolete ...
... Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'mousemove' in that specification. Obsolete ...
Element: mouseup event - Web APIs
l use to draw. Drawing begins when the mousedown event fires. First we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isDrawing to true. As the mouse moves over the page, the mousemove event fires. If isDrawing is true, the event handler calls the drawLine function to draw a line from the stored x and y values to the current location. When the drawLine
() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. HTML <h1>Drawing with mouse events</h1> <canvas id="myPics" width="560" height="360"></canvas> CSS canvas { border: 1px solid black; width: 560px; height: 360px; } JavaScript // When tru...
... Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'mouseup' ...
... Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'mouseup' in that specification. Obsolete ...
... Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'mouseup' in that specification. Obsolete ...
Event.composed - Web APIs
l return false. For example, this includes synthetic events that are created without their composed option wil set to true. Propagation only occurs if the bubbles property is also true. However, capturing only composed events are also handled at host as if they were in AT_TARGET phase. You can determine the path the event will follow through the shadow root to the DOM root by calling composedPath
(). If this value is false, the shadow root will be the last node to be offered the event. Examples In our composed-composed-path example (see it live), we define two trivial custom elements, <open-shadow> and <closed-shadow>, both of which take the contents of their text attribute and insert them into the element's shadow DOM as the text content of a <p> element. The only difference between the ...
...of which take the contents of their text attribute and insert them into the element's shadow DOM as the text content of a <p> element. The only difference between the two is that their shadow roots are attached with their modes set to open and closed respectively. ...
...e contents of their text attribute and insert them into the element's shadow DOM as the text content of a <p> element. The only difference between the two is that their shadow roots are attached with their modes set to open and closed respectively. ...
... The composed property returns true beause the click event is always able to propagate across shadow boundaries. You'll notice a difference in the value of composedPath for the two elements. The <open-shadow> element's composed path is this: Array [ p, ShadowRoot, open-shadow, ...
Event.eventPhase - Web APIs
Event.NONE 0 No event is being processed at this time. Event.CAPTURING_PHASE 1 The event is being propagated through the target's ancestor objects. This process starts with the Window, then Document, then the HTMLHtmlElement, and so on through the elements until the target's parent is reached. Event listeners registered for capture mode when EventTarget.addEventListener
() was called are triggered during this phase. Event.AT_TARGET 2 The event has arrived at the event's target. Event listeners registered for this phase are called at this time. If Event.bubbles is false, processing the event is finished after this phase is complete. Event.BUBBLING_PHASE 3 The event is propagating back up through the target's ancestors in reverse order, ...
...d2">d2 <div id="d3">d3 <div id="d4">d4</div> </div> </div> </div> <div id="divInfo"></div> CSS div { margin: 20px; padding: 4px; border: thin black solid; } #divInfo { margin: 18px; padding: 8px; background-color:white; font-size:80%; } JavaScript let clear = false, divInfo = null, divs = null, useCapture = false; window.onload = function
() { divInfo = document.getElementById('divInfo') divs = document.getElementsByTagName('div') chCapture = document.getElementById('chCapture') chCapture.onclick = function
() { RemoveListeners
() AddListeners
() } Clear
() AddListeners
() } function RemoveListeners
() { for (let i = 0; i < divs.length; i++) { let d = divs[i] if (d.id != "divInfo") { d.removeEventLis...
...lementById('chCapture') chCapture.onclick = function
() { RemoveListeners
() AddListeners
() } Clear
() AddListeners
() } function RemoveListeners
() { for (let i = 0; i < divs.length; i++) { let d = divs[i] if (d.id != "divInfo") { d.removeEventListener("click", OnDivClick, true) d.removeEventListener("click", OnDivClick, false) } } } function AddListeners
() { for (let i = 0; i < divs.length; i++) { let d = divs[i] if (d.id != "divInfo") { if (chCapture.checked) { d.addEventListener("click", OnDivClick, true) } else { d.addEventListener("click", OnDivClick, false) d.onmousemove = function
() { clear = true } } } } } function OnDivClick(e) { if (clear) { Clear
()...
...ear) { Clear
() clear = false } if (e.eventPhase == 2) e.currentTarget.style.backgroundColor = 'red'; let level = e.eventPhase == 0 ? "none" : e.eventPhase == 1 ? "capturing" : e.eventPhase == 2 ? "target" : e.eventPhase == 3 ? "bubbling" : "error"; divInfo.innerHTML += e.currentTarget.id + "; eventPhase: " + level + "<br/>"; } function Clear
() { for (let i = 0; i < divs.length; i++) { if (divs[i].id != "divInfo") { divs[i].style.backgroundColor = (i & 1) ? "#f6eedb" : "#cceeff" } } divInfo.innerHTML = '' } Result Specifications Specification Status Comment DOMThe definition of 'Event.eventPhase' in that specification. Living Standard DOM4The definition of 'Event.eventPhas...
EventTarget - Web APIs
Additional methods in Mozilla chrome codebase Mozilla includes a couple of exten...
...oke="#D4DDE4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">EventTarget</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Constructor EventTarget
() Creates a new EventTarget object instance. Methods EventTarget.addEventListener
() Registers an event handler of a specific event type on the EventTarget. EventTarget.removeEventListener
() Removes an event listener from the EventTarget. EventTarget.dispatchEvent
() Dispatches an event to this EventTarget. Additional methods in Mozilla chrome codebase Mozilla includes a couple of extensions for use by JS-implemented event targets to implement onevent properties. See also...
...nt to this EventTarget. Additional methods in Mozilla chrome codebase Mozilla includes a couple of extensions for use by JS-implemented event targets to implement onevent properties. See also WebIDL bindings. ...
... Living Standard No change. Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'EventTarget' in that spe...
ExtendableEvent - Web APIs
The ExtendableEvent interface extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries. If waitUntil
() is called outside of the ExtendableEvent handler, the browser should throw an InvalidStateError; note also that multiple calls will stack up, and the resulting promises will be added to the list of extend lifetime promises. Note: The behaviour described in the above paragraph was fixed in Firefox 43 (see bug 1180274.) This interface inherits from the Event interface. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; paddin...
...onaco,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 be called in the install EventHandler for the installing worker and on the activate EventHandler for the active work...
...The promise resolves when all resources have been fetched and cached, or else when any exception occurs. ...
...https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif' ]; console.log('Handling install event. Resources to pre-fetch:', urlsToPrefetch); event.waitUntil( caches.open(CURRENT_CACHES['prefetch']).then(function(cache) { return cache.addAll(urlsToPrefetch.map(function(urlToPrefetch) { return new Request(urlToPrefetch, {mode: 'no-cors'}); })).then(function
() { console.log('All resources have been fetched and cached.'); }); }).catch(function(error) { console.error('Pre-fetching failed:', error); }) ); }); Important: When fetching resources, it's very important to use {mode: 'no-cors'} if there is any chance that the resources are served off of a server that doesn't support CORS. In this example, www.chromium.org doesn't ...
FileReader.result - Web APIs
the methods was used to initiate the read operation. Syntax var file = instanceOfFileReader.result Value An appropiate string or ArrayBuffer based on which of the reading methods was used to initiate the read operation. The value is null if the reading is not yet complete or was unsuccessful. The result types are described below. ...
...sult Value An appropiate string or ArrayBuffer based on which of the reading methods was used to initiate the read operation. The value is null if the reading is not yet complete or was unsuccessful. The result types are described below. Method Description readAsArrayBuffer
() The result is a JavaScript ArrayBuffer containing binary data. readAsBinaryString
() The result contains the raw binary data from the file in a string. readAsDataURL
() The result is a string with a data: URL representing the file's data. readAsText
() The result is text in a string. Example This example presents a function, read
(), which reads a file from a file input. It works by creating a FileReader object and creating a listener for load even...
... a string with a data: URL representing the file's data. readAsText
() The result is text in a string. Example This example presents a function, read
(), which reads a file from a file input. It works by creating a FileReader object and creating a listener for load events such that when then file is read, the result is obtained and passed to the callback function provided to read
(). The content is handled as raw text data. ...
...input. It works by creating a FileReader object and creating a listener for load events such that when then file is read, the result is obtained and passed to the callback function provided to read
(). The content is handled as raw text data. var fileInput = document.querySelector('input[type="file"]'); function read(callback) { var file = fileInput.files.item(0); var reader = new FileReader
(); reader.onload = function
() { callback(reader.result); } reader.readAsText(file); } Specifications Specification Status Comment File APIThe definition of 'result' in that specification. Working Draft Initial definition ...
FormDataEvent - Web APIs
The FormDataEvent interface represents a formdata event -- such an event is fired on an HTMLFormElement object after the entry list representing the form's data is constructed. This happens when the form is submitted, but can also be triggered by the invocation of a FormData
() constructor. This allows a FormData object to be quickly obtained in response to a formdata event firing, rather than needing to put it together yourself when you wish to submit form data via a method like XMLHttpRequest (see Using FormData objects). Constructor FormDataEvent
() Creates a new FormDataEvent object instance. Properties Inherits properties from its parent interface, Event. FormDataEvent.formData Contains the FormData object representing the data contained in the form when the event was fired.
... FormDataEvent.formData Contains the FormData object representing the data contained in the form when the event was fired. Methods Inherits methods from its parent interface, Event. ...
... Living Standard ...
... Living Standard ...
GainNode.gain - Web APIs
The gain property of the GainNode interface is an a-rate AudioParam representing the amount of gain to apply. Syntax var audioCtx = new AudioContext
(); var gainNode = audioCtx.createGain
(); gainNode.gain.value = 0.5; Value An AudioParam. Note: Though the AudioParam returned is read-only, the value it represents is not. Example The following example shows basic usage of an AudioContext to create a GainNode, which is then used to mute and unmute the audio when a Mute button is clicked by changing the gain property value. ...
...ntext to create a GainNode, which is then used to mute and unmute the audio when a Mute button is clicked by changing the gain property value. ...
...hen used to mute and unmute the audio when a Mute button is clicked by changing the gain property value. ...
...callback function(stream) { source = audioCtx.createMediaStreamSource(stream); }, // Error callback function(err) { console.log('The following gUM error occured: ' + err); } ); } else { console.log('getUserMedia not supported on your browser!'); } source.connect(gainNode); gainNode.connect(audioCtx.destination); ... mute.onclick = voiceMute; function voiceMute
() { if(mute.id == "") { // 0 means mute. If you still hear something, make sure you haven't // connected your source into the output in addition to using the GainNode. gainNode.gain.setValueAtTime(0, audioCtx.currentTime); mute.id = "activated"; mute.innerHTML = "Unmute"; } else { gainNode.gain.setValueAtTime(1, audioCtx.currentTime); mute.id = ""; mute.innerHTML...
GainNode - Web APIs
resulting audio. To prevent this from happening, never change the value directly but use the exponential interpolation methods on the AudioParam interface. Number of inputs 1 Number of outputs 1 Channel count mode "max" Channel count 2 (not used in the default count mode) Channel interpretation "speakers" Constructor GainNode
() Creates a new instance of a GainNode object. You shouldn't manually create a gain node; instead, use the method AudioContext.createGain
(). Properties Inherits properties from its parent, AudioNode. GainNode.gain Read only Is an a-rate AudioParam representing the amount of gain to apply. You have to set AudioParam.value or use the methods of AudioParam to change the effect of gain. Meth...
...ntext to create a GainNode, which is then used to mute and unmute the audio when a Mute button is clicked by changing the gain property value. ...
...hen used to mute and unmute the audio when a Mute button is clicked by changing the gain property value. ...
...callback function(stream) { source = audioCtx.createMediaStreamSource(stream); }, // Error callback function(err) { console.log('The following gUM error occured: ' + err); } ); } else { console.log('getUserMedia not supported on your browser!'); } source.connect(gainNode); gainNode.connect(audioCtx.destination); ... mute.onclick = voiceMute; function voiceMute
() { if(mute.id == "") { // 0 means mute. If you still hear something, make sure you haven't // connected your source into the output in addition to using the GainNode. gainNode.gain.setValueAtTime(0, audioCtx.currentTime); mute.id = "activated"; mute.innerHTML = "Unmute"; } else { gainNode.gain.setValueAtTime(1, audioCtx.currentTime); mute.id = ""; mute.innerHTML...
Geolocation API - Web APIs
I is accessed via a call to navigator.geolocation; this will cause the user's browser to ask them for permission to access their location data. If they accept, then the browser will use the best available functionality on the device to access this information (for example, GPS). The developer can now access this location information in a couple of different ways: Geolocation.getCurrentPosition
(): Retrieves the device's current location. Geolocation.watchPosition
(): Registers a handler function that will be called automatically each time the position of the device changes, returning the updated location. In both cases, the method call takes up to three arguments: A mandatory success callback: If the location retrieval is successful, the callback executes with a GeolocationPosition o...
...ll to one of the methods contained inside Geolocation, inside an error callback, and contains an error code and message. Navigator.geolocation The entry point into the API. Returns a Geolocation object instance, from which all other functionality can be accessed. Dictionaries PositionOptions Represents an object containing options to pass in as a parameter of Geolocation.getCurrentPosition
() and Geolocation.watchPosition
(). Examples In the following example the Geolocation API is used to retrieve the user's latitude and longitude. If sucessful, the available hyperlink is populated with an openstreetmap.org URL that will show their location. body { padding: 20px; background-color:#ffffc9 } button { margin: .5rem 0; } HTML <button id = "find-me">Show my location</button...
... retrieve the user's latitude and longitude. If sucessful, the available hyperlink is populated with an openstreetmap.org URL that will show their location. ...
...k'); mapLink.href = ''; mapLink.textContent = ''; function success(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; status.textContent = ''; mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`; mapLink.textContent = `Latitude: ${latitude} ?, Longitude: ${longitude} ?`; } function error
() { status.textContent = 'Unable to retrieve your location'; } if(!navigator.geolocation) { status.textContent = 'Geolocation is not supported by your browser'; } else { status.textContent = 'Locating...'; navigator.geolocation.getCurrentPosition(success, error); } } document.querySelector('#find-me').addEventListener('click', geoFindMe); Result Specifications ...
GlobalEventHandlers.onauxclick - Web APIs
omewhat inconsistent. Syntax target.onauxclick = functionRef; Value functionRef is a function name or a function expression. The function receives a MouseEvent object as its sole argument. Within the function, this will be the element upon which the event was triggered. Only one onauxclick handler can be assigned to an object at a time. You may prefer to use the EventTarget.addEventListener
() method instead, since it's more flexible. Example In this example we define functions for two event handlers -- onclick and onauxclick. The former changes the color of the button background, while the latter changes the button foreground (text) color. You can see the two functions in action by trying the demo out with a multi-button mouse (see it live on GitHub; also see the source code). var ...
...ormer changes the color of the button background, while the latter changes the button foreground (text) color. You can see the two functions in action by trying the demo out with a multi-button mouse (see it live on GitHub; also see the source code). ...
...ground, while the latter changes the button foreground (text) color. You can see the two functions in action by trying the demo out with a multi-button mouse (see it live on GitHub; also see the source code). ...
...e it live on GitHub; also see the source code). var button = document.querySelector('button'); var html = document.querySelector('html'); function random(number) { return Math.floor(Math.random
() * number); } button.onclick = function
() { var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; button.style.backgroundColor = rndCol; }; button.onauxclick = function
() { var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; button.style.color = rndCol; } Note: If you are using a three-button mouse, you'll notice that the onauxclick handler is run when either of the non-left mouse buttons are clicked. Specifications Specification Status Comment UI EventsThe definition of 'onauxclick' in that specificati...
GlobalEventHandlers.onformdata - Web APIs
The onformdata property of the GlobalEventHandlers mixin is the EventHandler for processing formdata events, fired after the entry list representing the form's data is constructed. This happens when the form is submitted, but can also be triggered by the invocation of a FormData
() constructor. onformdata is available on HTMLFormElement. Syntax target.onformdata = functionRef; Value functionRef is a function name or a function expression. The function receives a FormDataEvent object as its sole argument. ...
...LFormElement. Syntax target.onformdata = functionRef; Value functionRef is a function name or a function expression. The function receives a FormDataEvent object as its sole argument. ...
... Living Standard ...
... Living Standard ...
GlobalEventHandlers.onkeypress - Web APIs
ent.querySelector('input'); input.onkeypress = numbersOnly; // Prevent pasting (since pasted content might include non-number characters) input.onpaste = event => false; Result Capture the typing of a hidden word The following JavaScript function will do something after the user types the word "exit" in any point of a page. /* Type the word "exit" in any point of your page... ...
...will do something after the user types the word "exit" in any point of a page. /* Type the word "exit" in any point of your page... ...
...e. /* Type the word "exit" in any point of your page... */ (function
() { const sSecret = /* Choose your hidden word...: */ "exit"; let nOffset = 0; document.onkeypress = function(oPEvt) { let oEvent = oPEvt || window.event, nChr = oEvent.charCode, sNodeType = oEvent.target.nodeName.toUpperCase
(); if (nChr === 0 || oEvent.target.contentEditable.toUpperCase
() === "TRUE" || sNodeType === "TEXTAREA" || sNodeType === "INPUT" && oEvent.target.type.toUpperCase
() === "TEXT") { return true; } if (nChr !== sSecret.charCodeAt(nOffset)) { nOffset = nChr === sSecret.charCodeAt(0) ? 1 : 0; } else if (nOffset < sSecret.length - 1) { nOffset++; } else { nOffset = 0; /* Do something here... */ aler...
... Specifications Specification Status Comment HTML Living StandardThe definition of 'onkeypress' in that specification. ...
GlobalEventHandlers.onpointerdown - Web APIs
own is used to specify the event handler for the pointerdown event, which is fired when the pointing device is initially pressed. This event can be sent to Window, Document, and Element objects. This is functionally equivalent to the mousedown event when generated due to user activity with a mouse or mouse-compatible device. If the pointerdown event isn't canceled through a call to preventDefault
(), most user agents will fire a mousedown event, so that sites not using pointer events will work. You can also use addEventListener
() to add a listener for pointerdown events. Syntax target.onpointerdown = downHandler; var downHandler = target.onpointerdown; Value A Function to handle the pointerdown event for the target Element, Document, or Window. It receives as input the PointerEvent de...
...ts. Syntax target.onpointerdown = downHandler; var downHandler = target.onpointerdown; Value A Function to handle the pointerdown event for the target Element, Document, or Window. It receives as input the PointerEvent describing the pointerdown event. Example This example demonstrates how to watch for and act upon pointerdown events using onpointerdown. You could also use addEventListener
(), of course. JavaScript First, let's look at the JavaScript code that handles the pointerdown event. var targetBox = document.getElementById("target"); targetBox.onpointerdown = handleDown; function handleDown(evt) { var action; switch(evt.pointerType) { case "mouse": action = "clicking"; break; case "pen": action = "tapping"; break; case "touch": ...
...unction handleDown(evt) { var action; switch(evt.pointerType) { case "mouse": action = "clicking"; break; case "pen": action = "tapping"; break; case "touch": action = "touching"; break; default: action = "interacting with"; break; } targetBox.innerHTML = "<strong>Thanks for " + action + " me!</strong>"; evt.preventDefault
(); } This simply uses onpointerdown to establish the function handleDown
() as the event handler for pointer down events. The handleDown
() function, in turn, looks at the value of pointerType to determine what kind of pointing device was used, then uses that information to customize a string to replace the contents of the target box. Then the event's preventDefault
() method is called to ensure th...
...'s preventDefault
() method is called to ensure that the mousedown event isn't triggered, potentially causing events to be handled twice if we had a handler for those events in case Pointer Event support is missing. We also have a handler for pointerup events: targetBox.onpointerup = handleUp; function handleUp(evt) { targetBox.innerHTML = "Tap me, click me, or touch me!"; evt.preventDefault
(); } This code's job is to just restore the original text into the target box after the user's interaction with the element ends (for example, when they release the mouse button, or when they lift the stylus or finger from the screen). In addition, the event's preventDefault
() method is called to ensure that the mouseup event isn't triggered unnecessarily. HTML The HTML is extremely simple: ...
HTMLElement: animationend event - Web APIs
from the element, the animationend event is not fired. ...
...d Examples This example gets an element that's being animated and listens for the animationend event: const animated = document.querySelector('.animated'); animated.addEventListener('animationend',
() => { console.log('Animation ended'); }); The same, but using the onanimationend event handler property: const animated = document.querySelector('.animated'); animated.onanimationend =
() => { console.log('Animation ended'); }; Live example HTML <div class="animation-example"> <div class="container"> <p class="animation">You chose a cold night to visit our planet.</p> </div> <button class="activate" type="button">Activate animation</button> <div class="event-log"></div> </div> CSS .container { height: 3rem; } .event-log { width: 25rem; height...
... { margin-left: 100%; width: 300%; } to { margin-left: 0%; width: 100%; } } JS const animation = document.querySelector('p.animation'); const animationEventLog = document.querySelector('.animation-example>.event-log'); const applyAnimation = document.querySelector('.animation-example>button.activate'); let iterationCount = 0; animation.addEventListener('animationstart',
() => { animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `; }); animation.addEventListener('animationiteration',
() => { iterationCount++; animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `; }); animation.addEventListener('animationend',
() => { animationEventLog.textContent = `${animationEventLog...
... animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `; }); animation.addEventListener('animationend',
() => { animationEventLog.textContent = `${animationEventLog.textContent}'animation ended'`; animation.classList.remove('active'); applyAnimation.textContent = "Activate animation"; }); animation.addEventListener('animationcancel',
() => { animationEventLog.textContent = `${animationEventLog.textContent}'animation canceled'`; }); applyAnimation.addEventListener('click',
() => { animation.classList.toggle('active'); animationEventLog.textContent = ''; iterationCount = 0; let active = animation.classList.contains('active'); if (active) { applyAnimation.textContent = "Cancel animation"; } else { applyAnimat...
HTMLElement: animationiteration event - Web APIs
one. ...
...animated = document.querySelector('.animated'); let iterationCount = 0; animated.addEventListener('animationiteration',
() => { iterationCount++; console.log(`Animation iteration count: ${iterationCount}`); }); The same, but using the onanimationiteration event handler property: const animated = document.querySelector('.animated'); let iterationCount = 0; animated.onanimationiteration =
() => { iterationCount++; console.log(`Animation iteration count: ${iterationCount}`); }; Live example HTML <div class="animation-example"> <div class="container"> <p class="animation">You chose a cold night to visit our planet.</p> </div> <button class="activate" type="button">Activate animation</button> <div class="event-log"></div> </div> CSS .container { heigh...
... transform: translateX(100%) scaleX(3); } to { transform: translateX(0) scaleX(1); } } JS const animation = document.querySelector('p.animation'); const animationEventLog = document.querySelector('.animation-example>.event-log'); const applyAnimation = document.querySelector('.animation-example>button.activate'); let iterationCount = 0; animation.addEventListener('animationstart',
() => { animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `; }); animation.addEventListener('animationiteration',
() => { iterationCount++; animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `; }); animation.addEventListener('animationend',
() => { animationEventLog.textContent = `${animationEventLog...
... animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `; }); animation.addEventListener('animationend',
() => { animationEventLog.textContent = `${animationEventLog.textContent}'animation ended'`; animation.classList.remove('active'); applyAnimation.textContent = "Activate animation"; }); animation.addEventListener('animationcancel',
() => { animationEventLog.textContent = `${animationEventLog.textContent}'animation canceled'`; }); applyAnimation.addEventListener('click',
() => { animation.classList.toggle('active'); animationEventLog.textContent = ''; iterationCount = 0; let active = animation.classList.contains('active'); if (active) { applyAnimation.textContent = "Cancel animation"; } else { applyAnimat...
HTMLElement: animationstart event - Web APIs
ation will begin playing at that time index into the sequence). ...
...er property onanimationstart Examples This listens for the animationstart event and logs a message when it is fired: const animated = document.querySelector('.animated'); animated.addEventListener('animationstart',
() => { console.log('Animation started'); }); The same, but using onanimationstart: const animated = document.querySelector('.animated'); animated.onanimationstart =
() => { console.log('Animation started'); }; Live example HTML <div class="animation-example"> <div class="container"> <p class="animation">You chose a cold night to visit our planet.</p> </div> <button class="activate" type="button">Activate animation</button> <div class="event-log"></div> </div> CSS .container { height: 3rem; } .event-log { width: 25rem; hei...
... transform: translateX(100%) scaleX(3); } to { transform: translateX(0) scaleX(1); } } JS const animation = document.querySelector('p.animation'); const animationEventLog = document.querySelector('.animation-example>.event-log'); const applyAnimation = document.querySelector('.animation-example>button.activate'); let iterationCount = 0; animation.addEventListener('animationstart',
() => { animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `; }); animation.addEventListener('animationiteration',
() => { iterationCount++; animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `; }); animation.addEventListener('animationend',
() => { animationEventLog.textContent = `${animationEventLog...
... animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `; }); animation.addEventListener('animationend',
() => { animationEventLog.textContent = `${animationEventLog.textContent}'animation ended'`; animation.classList.remove('active'); applyAnimation.textContent = "Activate animation"; }); animation.addEventListener('animationcancel',
() => { animationEventLog.textContent = `${animationEventLog.textContent}'animation canceled'`; }); applyAnimation.addEventListener('click',
() => { animation.classList.toggle('active'); animationEventLog.textContent = ''; iterationCount = 0; let active = animation.classList.contains('active'); if (active) { applyAnimation.textContent = "Cancel animation"; } else { applyAnimat...
HTMLElement: transitionstart event - Web APIs
The transitionstart event is fired when a CSS transition has actually started, i.e., after any transition-delay has ended. ...
...s ended. ...
...es Cancelable No Interface TransitionEvent Event handler property ontransitionstart Examples This code adds a listener to the transitionstart event: element.addEventListener('transitionstart',
() => { console.log('Started transitioning'); }); The same, but using the ontransitionstart property instead of addEventListener
(): element.ontransitionrun =
() => { console.log('Started transitioning'); }; Live example In the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition">Hover over me</div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; tra...
...nsition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate where the transitionstart and transitionrun events fire. const transition = document.querySelector('.transition'); const message = document.querySelector('.message'); transition.addEventListener('transitionrun', function
() { message.textContent = 'transitionrun fired'; }); transition.addEventListener('transitionstart', function
() { message.textContent = 'transitionstart fired'; }); transition.addEventListener('transitionend', function
() { message.textContent = 'transitionend fired'; }); The difference is that: transitionrun fires when the transition is created (i.e. at the start of any delay). trans...
HTMLElement - Web APIs
touchleave Returns the event handling code for the touchleave event. TouchEventHandlers.ontouchcancel Returns the event handling code for the touchcancel event. Methods Inherits methods from its parent, Element, and implements those from DocumentAndElementEventHandlers, ElementCSSInlineStyle, GlobalEventHandlers, HTMLOrForeignElement and TouchEventHandlers. HTMLElement.attachInternals
() Attaches an ElementInternals instance to the custom element. HTMLOrForeignElement.blur
() Removes keyboard focus from the currently focused element. HTMLElement.click
() Sends a mouse click event to the element. HTMLOrForeignElement.focus
() Makes the element the current keyboard focus. HTMLElement.forceSpellCheck
() Runs the spell checker on the element's contents. Events Listen to t...
... invalid Fired when an element does not satisfy its constraints during constraint validation. Also available via the oninvalid property. Animation events animationcancel Fired when an animation unexpectedly aborts. ...
...lement has been changed. Also available via the oninput property. change Fired when the value of an <input>, <select>, or <textarea> element has been changed and committed by the user. Unlike the input event, the change event is not necessarily fired for each alteration to an element's value. Pointer events gotpointercapture Fired when an element captures a pointer using setPointerCapture
(). Also available via the ongotpointercapture property. lostpointercapture Fired when a captured pointer is released. Also available via the onlostpointercapture property. pointercancel Fired when a pointer event is canceled. Also available via the onpointercancel property. pointerdown Fired when a pointer becomes active. Also available via the onpointerdown property. pointerenter Fired...
...ication. 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, draggable, dropzone, contentEditable, isContentEditable, contextMenu, spellcheck, commandType, commandLabel, commandIcon...
HTMLFormElement: formdata event - Web APIs
The formdata event fires after the entry list representing the form's data is constructed. This happens when the form is submitted, but can also be triggered by the invocation of a FormData
() constructor. ...
...a
() constructor. ...
...('submit', (e) => { // on form submission, prevent default e.preventDefault
(); // construct a FormData object, which fires the formdata event new FormData(formElem); }); // formdata handler to retrieve data formElem.addEventListener('formdata', (e) => { console.log('formdata fired'); // Get the form data from the event object let data = e.formData; for (var value of data.values
()) { console.log(value); } // submit the data via XHR var request = new XMLHttpRequest
(); request.open("POST", "/formHandler"); request.send(data); }); The onformdata version would look like this: formElem.onformdata = (e) => { console.log('formdata fired'); // Get the form data from the event object let data = e.formData; for (var value of data.values
()) { console.log...
... new XMLHttpRequest
(); request.open("POST", "/formHandler"); request.send(data); }); The onformdata version would look like this: formElem.onformdata = (e) => { console.log('formdata fired'); // Get the form data from the event object let data = e.formData; for (var value of data.values
()) { console.log(value); } // submit the data via XHR var request = new XMLHttpRequest
(); request.open("POST", "/formHandler"); request.send(data); }; Specifications Specification Status Comment HTML Living StandardThe definition of 'formdata' in that specification. Unknown ...
HTMLMediaElement: pause event - Web APIs
The pause event is sent when a request to pause an activity is handled and the activity has entered its paused state, most commonly after the media has been paused through a call to the element's pause
() method. The event is sent once the pause
() method returns and after the media element's paused property has been changed to true. ...
... Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onpause Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's pause event, then post a message when that event handler has reacted to the event firing. ...
...Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's pause event, then post a message when that event handler has reacted to the event firing. Using addEventListener
(): const video = document.querySelector('video'); video.addEventListener('pause', (event) => { console.log('The Boolean paused property is now true. ...
...ideo'); video.addEventListener('pause', (event) => { console.log('The Boolean paused property is now true. Either the ' + 'pause
() method was called or the autoplay attribute was toggled.'); }); Using the onpause event handler property: const video = document.querySelector('video'); video.onpause = (event) => { console.log('The Boolean paused property is now true. Either the ' + 'pause
() method was called or the autoplay attribute was toggled.'); }; Specifications Specification Status HTML Living StandardThe definition of 'pause media event' in that specification. Living Standard HTML5The definition of 'pause media event' in that specification. Recommendation ...
HTMLMediaElement.srcObject - Web APIs
ns the object which serves as the source of the media associated with the HTMLMediaElement. The object can be a MediaStream, a MediaSource, a Blob, or a File (which inherits from Blob). Note: As of March 2020, only Safari supports setting objects other than MediaStream. ...
...Now you can just set srcObject to the MediaStream directly. Examples Basic example In this example, a MediaStream from a camera is assigned to a newly-created <video> element. ...
...ly. Examples Basic example In this example, a MediaStream from a camera is assigned to a newly-created <video> element. const mediaStream = await navigator.mediaDevices.getUserMedia({video: true}); const video = document.createElement('video'); video.srcObject = mediaStream; In this example, a new MediaSource is assigned to a newly-created <video> element. const mediaSource = new MediaSource
(); const video = document.createElement('video'); video.srcObject = mediaSource; Supporting fallback to the src property The examples below support older browser versions that require you to create an object URL and assign it to src if srcObject isn't supported. First, a MediaStream from a camera is assigned to a newly-created <video> element, with fallback for older browsers. const mediaStream...
...); if ('srcObject' in video) { video.srcObject = mediaStream; } else { // Avoid using this in new browsers, as it is going away. video.src = URL.createObjectURL(mediaStream); } Second, a new MediaSource is assigned to a newly-created <video> element, with fallback for older browsers and browsers that don't yet support assignment of MediaSource directly. ...
HTMLOrForeignElement - Web APIs
The focused element is the element which will receive keyboard and similar events by default. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLOrForeignEleme...
...The focused element is the element which will receive keyboard and similar events by default. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLOrForeignElement' in that specificat...
...The focused element is the element which will receive keyboard and similar events by default. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLOrForeignElement' in that specification. Living Standard Initial definition. ...
...gnElement interface returns the cryptographic number used once that is used by Content Security Policy to determine whether a given fetch will be allowed to proceed.tabIndexThe tabIndex property of the HTMLOrForeignElement interface represents the tab order of the current element.Methodsblur
()The HTMLElement.blur
() method removes keyboard focus from the current element.focus
()The HTMLElement.focus
() method sets focus on the specified element, if it can be focused. The focused element is the element which will receive keyboard and similar events by default. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLOrForeignElement' in that specification. Living Standard Initial definition. ...
The HTML DOM API - Web APIs
to expand upon the functionality of the core HTMLElement interface to provide the features needed by a specific element, the HTMLElement class is subclassed to add the needed properties and methods. For example, the <canvas> element is represented by an object of type HTMLCanvasElement. HTMLCanvasElement augments the HTMLElement type by adding properties such as height and methods like getContext
() to provide canvas-specific features. The overall inheritance for HTML element classes looks like this: As such, an element inherits the properties and methods of all of its ancestors. For example, consider a <a> element, which is represented in the DOM by an object of type HTMLAnchorElement. The element, then, includes the anchor-specific properties and methods described in that class's docum...
...o update the state of a form's "submit" button based on whether or not a given field currently has a value. ...
... With these, we can access the properties and methods that provide information about and grant control over these elements. ...
...elements whose IDs are userName and sendButton. With these, we can access the properties and methods that provide information about and grant control over these elements. The HTMLInputElement object for the "Send" button's disabled property is set to true, which disables the "Send" button so it can't be clicked. In addition, the user name input field is made the active focus by calling the focus
() method it inherits from HTMLElement. Then addEventListener
() is called to add a handler for the input event to the user name input. This code looks at the length of the current value of the input; if it's zero, then the "Send" button is disabled if it's not already disabled. Otherwise, the code ensures that the button is enabled. With this in place, the "Send" button is always enabled whenever ...
File drag and drop - Web APIs
get element uses the following styling: #drop_zone { border: 5px solid blue; width: 200px; height: 100px; } Note that dragstart and dragend events are not fired when dragging a file into the browser from the OS. Process the drop The drop event is fired when the user drops the file(s). In the following drop handler, if the browser supports DataTransferItemList interface, the getAsFile
() method is used to access each file; otherwise the DataTransfer interface's files property is used to access each file. This example shows how to write the name of each dragged file to the console. In a real application, an application may want to process a file using the File API. Note that in this example, any drag item that is not a file is ignored. function dropHandler(ev) { console.log(...
...ccess each file. This example shows how to write the name of each dragged file to the console. In a real application, an application may want to process a file using the File API. Note that in this example, any drag item that is not a file is ignored. function dropHandler(ev) { console.log('File(s) dropped'); // Prevent default behavior (Prevent file from being opened) ev.preventDefault
(); if (ev.dataTransfer.items) { // Use DataTransferItemList interface to access the file(s) for (var i = 0; i < ev.dataTransfer.items.length; i++) { // If dropped items aren't files, reject them if (ev.dataTransfer.items[i].kind === 'file') { var file = ev.dataTransfer.items[i].getAsFile
(); console.log('... file[' + i + '].name = ' + file.name); } } ...
... console.log('... file[' + i + '].name = ' + file.name); } } } else { // Use DataTransfer interface to access the file(s) for (var i = 0; i < ev.dataTransfer.files.length; i++) { console.log('... ...
...le.log('... file[' + i + '].name = ' + ev.dataTransfer.files[i].name); } } } Prevent the browser's default drag behavior The following dragover event handler calls preventDefault
() to turn off the browser's default drag and drop handler. ...
IDBDatabaseSync - Web APIs
ion of the connected database. name readonly DOMString The name of the connected database. objectStores readonly DOMStringList The names of the object stores that exist in the connected database. version readonly DOMString The version of the connected database. Has the null value when the database is first created. Methods createObjectStore
() Creates and returns a new object store with the given name in the connected database. IDBObjectStoreSync createObjectStore( in DOMString name, in DOMString keypath, in optional boolean autoIncrement ) raises (IDBDatabaseException); Parameters name The name of a new object store. keypath The key path used by the new object store. If a null path is specified, then the object store...
... true, the object store uses a key generator; if false, it does not use one. Returns IDBObjectStoreSync An object to access the newly created object store. Exceptions This method can raise an IDBDatabaseException with the following code: CONSTRAINT_ERR If an object store with the same name (based on case-sensitive comparison) already exists in the connected database. openObjectStore
() Opens the object store with the given name in the connected database using the specified mode. IDBObjectStoreSync openObjectStore ( in DOMString name, in optional unsigned short mode ) raises (IDBDatabaseException); Parameters name The name of the object store to open. mode The mode that is used to access the object store. Returns IDBObjectStoreSync An object to access the ope...
...he object store to open. mode The mode that is used to access the object store. Returns IDBObjectStoreSync An object to access the opened object store. Exceptions This method can raise an IDBDatabaseException with the following code: NOT_FOUND_ERR If an object store with the given name (based on case-sensitive comparison) already exists in the connected database. removeObjectStore
() Destroys an object store with the given name, as well as all indexes that reference that object store. void removeObjectStore ( in DOMString storeName ) raises (IDBDatabaseException); Parameters storeName The name of an existing object store to remove. Returns void Exceptions This method can raise an IDBDatabaseException with the following code: NOT_FOUND_ERR If the object s...
...eObjectStore ( in DOMString storeName ) raises (IDBDatabaseException); Parameters storeName The name of an existing object store to remove. Returns void Exceptions This method can raise an IDBDatabaseException with the following code: NOT_FOUND_ERR If the object store with the given name (based on case-sensitive comparison) does not exist in the connected database. setVersion
() Sets the version of the connected database. void setVersion ( in DOMString version ); Parameters Returns void version The version 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 o...
IDBIndex.isAutoLocale - Web APIs
The isAutoLocale read-only property of the IDBIndex interface returns a Boolean indicating whether the index had a locale value of auto specified upon its creation (see createIndex
()'s optionalParameters.) Syntax var myIndex = objectStore.index('index'); console.log(myIndex.isAutoLocale); Value A Boolean. Example In the following example we open a transaction and an object store, then get the index lName from a simple contacts database. ...
...ct store, then get the index lName from a simple contacts database. We then open a basic cursor on the index using IDBIndex.openCursor -- this works the same as opening a cursor directly on an ObjectStore using IDBObjectStore.openCursor except that the returned records are sorted based on the index, not the primary key. The isAutoLocale value is logged to the console. ...
...cords are sorted based on the index, not the primary key. The isAutoLocale value is logged to the console. ...
... ...
IDBIndex.locale - Web APIs
Syntax var myIndex = objectStore.index('index'); console.log(myIndex.locale); Value A DOMString. Example In the following example we open a transaction and an object store, then get the index lName from a simple contacts database. ...
...n object store, then get the index lName from a simple contacts database. We then open a basic cursor on the index using IDBIndex.openCursor -- this works the same as opening a cursor directly on an ObjectStore using IDBObjectStore.openCursor except that the returned records are sorted based on the index, not the primary key. The locale value is logged to the console. ...
... returned records are sorted based on the index, not the primary key. The locale value is logged to the console. ...
... ...
IDBIndex.name - Web APIs
g upgrade transactions; that is, when the mode is "versionchange". TransactionInactiveError The current transaction is not active. ConstraintError An index is already using the specified name. Example In the following example we open a transaction and an object store, then get the index lName from a simple contacts database. We then open a basic cursor on the index using IDBIndex.openCursor
() -- this works the same as opening a cursor directly on an IDBObjectStore using openCursor
() except that the returned records are sorted based on the index, not the primary key. The name of the index is logged to the console: it should be returned as lName. Finally, we iterate through each record, inserting the data into an HTML table. For a complete working example, see our IDBIndex-example dem...
...DBObjectStore using openCursor
() except that the returned records are sorted based on the index, not the primary key. The name of the index is logged to the console: it should be returned as lName. Finally, we iterate through each record, inserting the data into an HTML table. For a complete working example, see our IDBIndex-example demo repo (View the example live). ...
...ata into an HTML table. For a complete working example, see our IDBIndex-example demo repo (View the example live). ...
... Recommendation Indexed Database API DraftThe definition of 'name' in that specification. Recommendation Browser compatibility The compatibility table o...
IDBKeyRange - Web APIs
Workers. Properties IDBKeyRange.lower Read only Lower bound of the key range. IDBKeyRange.upper Read only Upper bound of the key range. IDBKeyRange.lowerOpen Read only Returns false if the lower-bound value is included in the key range. IDBKeyRange.upperOpen Read only Returns false if the upper-bound value is included in the key range. Methods Static methods IDBKeyRange.bound
() Creates a new key range with upper and lower bounds. IDBKeyRange.only
() Creates a new key range containing a single value. IDBKeyRange.lowerBound
() Creates a new key range with only a lower bound. IDBKeyRange.upperBound
() Creates a new upper-bound key range. Instance methods IDBKeyRange.includes
() Returns a boolean indicating whether a specified key is inside the key range. Example...
... range includes the values "A" and "F", as we haven't declared that they should be open bounds. If we used IDBKeyRange.bound("A", "F", true, true);, then the range would not include "A" and "F", only the values between them. ...
... Br...
... 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. ...
IDBLocaleAwareKeyRange - Web APIs
The IDBLocaleAwareKeyRange interface of the IndexedDB API is a Firefox-specific version of IDBKeyRange -- it functions in exactly the same fashion, and has the same properties and methods, but it is intended for use with IDBIndex objects when the original index had a locale value specified upon its creation (see createIndex
()'s optionalParameters) -- that is, it has locale aware sorting enabled. ...
...With locale-aware indexes, the meaning of < depends on the locale, so for example in Lithuanian Y is sorted between I and K. The only difference between IDBKeyRange and IDBLocaleAwareKeyRange is that the latter doesn't do the aforementioned check. ...
...ion if that's not the case. With locale-aware indexes, the meaning of < depends on the locale, so for example in Lithuanian Y is sorted between I and K. The only difference between IDBKeyRange and IDBLocaleAwareKeyRange is that the latter doesn't do the aforementioned check. Developers should always use IDBLocaleAwareKeyRange when dealing with locale-aware indexes. ...
... ...
IDBObjectStore.autoIncrement - Web APIs
re is available in Web Workers. Syntax var myAutoIncrement = objectStore.autoIncrement; Value A Boolean: Value Meaning true The object store auto increments. false The object store does not auto increment. Example In the following code snippet, we open a read/write transaction on our database and add some data to an object store using add
(). After the object store has been created, we log objectStore.autoIncrement to the console. For a full working example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the dat...
...king example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...xample live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
... open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBObjectStore.indexNames - Web APIs
he indexNames read-only property of the IDBObjectStore interface returns a list of the names of indexes on objects in this object store. Note: This feature is available in Web Workers. Syntax var myindexNames = objectStore.indexNames; Value A DOMStringList. Example In the following code snippet, we open a read/write transaction on our database and add some data to an object store using add
(). After the object store has been created, we log objectStore.indexNames to the console. For a full working example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the databa...
... full working example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...p (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...// Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBObjectStore.keyPath - Web APIs
rface returns the key path of this object store. If this property is null, the application must provide a key for each modification operation. Note: This feature is available in Web Workers. Syntax var mykeyPath = objectStore.keyPath; Value Any value type. Example In the following code snippet, we open a read/write transaction on our database and add some data to an object store using add
(). After the object store has been created, we log objectStore.keyPath to the console. For a full working example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database ...
...king example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...xample live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
... open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBObjectStore.name - Web APIs
t an upgrade transaction; you can only rename indexes during upgrade transactions; that is, when the mode is "versionchange". TransactionInactiveError The current transaction is not active. ConstraintError An object store is already using the specified name. Example In the following code snippet, we open a read/write transaction on our database and add some data to an object store using add
(). After the object store has been created, we log objectStore.name to the console. For a full working example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in ...
...king example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...xample live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
... open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBObjectStore.transaction - Web APIs
saction read-only property of the IDBObjectStore interface returns the transaction object to which this object store belongs. Note: This feature is available in Web Workers. Syntax var myTransaction = objectStore.transaction; Value An IDBTransaction object. Example In the following code snippet, we open a read/write transaction on our database and add some data to an object store using add
(). After the object store has been created, we log objectStore.transaction to the console. For a full working example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the datab...
...king example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...xample live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
... open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBOpenDBRequest: blocked event - Web APIs
The blocked handler is executed when an open connection to a database is blocking a versionchange transaction on the same database. ...
...hange transaction on the same database. ...
...{ unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; DBOpenRequest.onsuccess = (event) => { // Let's try to open the same database with a higher revision version const req2 = indexedDB.open('toDoList', 5); // In this case the onblocked handler will be executed req2.addEventListener('blocked',
() => { console.log('Request was blocked'); }); }; Using the onblocked property: // Open the database const DBOpenRequest = window.indexedDB.open('toDoList', 4); DBOpenRequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror =
() => { console.log('Error creating database'); }; // Create an objectStore for this database var objectStore = db.createObj...
...x('day', 'day', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; DBOpenRequest.onsuccess = (event) => { // Let's try to open the same database with a higher revision version const req2 = indexedDB.open('toDoList', 5); // In this case the onblocked handler will be executed req2.onblocked =
() => { console.log('Request was blocked'); }; }; ...
IDBRequest: error event - Web APIs
The error handler is executed when an error caused a request to fail. ...
... Examples This example opens a database and tries to add a record, listening for the error event for the add
() operation (this will occur if, for example, a record with the given taskTitle already exists): // Open the database const DBOpenRequest = window.indexedDB.open('toDoList', 4); DBOpenRequest.addEventListener('upgradeneeded', event => { const db = event.target.result; db.onerror =
() => { console.log('Error creating database'); }; // Create an objectStore for this database var objectStore = db.createObjectStore('toDoList', { keyPath: 'taskTitle' }); // define what data items the objectStore will contain objectStore.createIndex('hours', 'hours', { unique: false }); objectStore.createIndex('minutes', 'minutes', { unique: false }); objectStore.createIndex('da...
... // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); const objectStore = transaction.objectStore('toDoList'); const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2020 }; const objectStoreRequest = objectStore.add(newItem); objectStoreRequest.addEventListener('error',
() => { console.log(`Error adding new item: ${newItem.taskTitle}`); }); }); The same example, using the onerror property instead of addEventListener
(): // Open the database const DBOpenRequest = window.indexedDB.open('toDoList', 4); DBOpenRequest.onupgradeneeded = event => { const db = event.target.result; db.onerror =
() => { console.log('Error creating database'); }; // Cre...
...Request.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); const objectStore = transaction.objectStore('toDoList'); const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2020 }; const objectStoreRequest = objectStore.add(newItem); objectStoreRequest.onerror =
() => { console.log(`Error adding new item: ${newItem.taskTitle}`); }; }; ...
IDBRequest.readyState - Web APIs
r console. ...
... Recommendation Indexed Database API DraftThe definition of 'readyState' in that specification. Recommendation ...
... Recommendation Indexed Database API DraftThe definition of 'readyState' in that specification. Recommendation Browser compatibility The compatibility table on this page is generated from s...
... Recommendation Indexed Database API DraftThe definition of 'readyState' in that specification. Recommendation Browser compatibility The compatibility table on this page is generated from structured data. If y...
IDBRequest.source - Web APIs
er console. ...
... Recommendation Indexed Database API DraftThe definition of 'source' in that specification. Recommendation Browse...
... Recommendation Indexed Database API DraftThe definition of 'source' in that specification. Recommendation Browser compatibility The compatibility table on this page is generated from structured da...
... Recommendation Indexed Database API DraftThe definition of 'source' in that specification. Recommendation Browser compatibility The compatibility table on this page is generated from structured data. If you'd lik...
IDBTransaction: abort event - Web APIs
The abort event is fired when an IndexedDB transaction is aborted. Bubbles Yes Cancelable No Interface Event Event handler property onabort This can happen for any of the following reasons: bad requests, (for example, trying to add the same key twice, or put the same index key when the key has a uniqueness constraint), an explicit abort
() call an uncaught exception in the request's success/error handler, an I/O error (an actual failure to write to disk, for example disk detached, or other OS/hardware failure) quota exceeded. Examples This example opens a database (creating the database if it does not exist), then opens a transaction, adds a listener to the abort event, then aborts the transaction to trigger the event. // Ope...
...ilure) quota exceeded. Examples This example opens a database (creating the database if it does not exist), then opens a transaction, adds a listener to the abort event, then aborts the transaction to trigger the event. ...
...ctStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; DBOpenRequest.onsuccess = event => { const db = DBOpenRequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); // add a listener for `abort` transaction.addEventListener('abort',
() => { console.log('Transaction was aborted'); }); // abort the transaction transaction.abort
(); }; The same example, but assigning the event handler to the onabort property: // Open the database const DBOpenRequest = window.indexedDB.open('toDoList', 4); DBOpenRequest.onupgradeneeded = event => { const db = event.target.result; db.onerror =
() => { console.log('Error creati...
...year', { unique: false }); }; DBOpenRequest.onsuccess = event => { const db = DBOpenRequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); // add a listener for `abort` transaction.onabort = (event) => { console.log('Transaction was aborted'); }; // abort the transaction transaction.abort
(); }; ...
IDBTransaction.mode - Web APIs
on readonly Allows data to be read but not changed. readwrite Allows reading and writing of data in existing data stores to be changed. versionchange Allows any operation to be performed, including ones that delete and create object stores and indexes. This mode is for updating the version number of transactions that were started using IDBDatabase.setVersion
(). Transactions of this mode cannot run concurrently with other transactions. Transactions in this mode are known as "upgrade transactions." 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 even...
...king example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...xample live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
... open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransactionSync - Web APIs
se its need was questionable. It may however be reintroduced in the future if there is enough demand from web developers. The IDBTransactionSync interface of the IndexedDB API provides a synchronous transaction on a database. When an application creates an IDBTransactionSync object, it blocks until the browser is able to reserve the require database objects. Method overview void abort
() raises (IDBDatabaseException); void commit
() raises (IDBDatabaseException); IDBObjectStoreSync objectStore(in DOMString name) raises (IDBDatabaseException); Attributes Attribute Type Description db IDBDatabaseSync The database connection that this transaction is associated with. static boolean If true, this transaction is...
...tabaseException); IDBObjectStoreSync objectStore(in DOMString name) raises (IDBDatabaseException); Attributes Attribute Type Description db IDBDatabaseSync The database connection that this transaction is associated with. static boolean If true, this transaction is static; if false, this transaction is dynamic. Methods abort
() Call this method to signal a need to cancel the effects of the operations performed by this transaction. When this method is called, the browser ignores all the changes performed to the objects of this database since this transaction was created. void abort( ) raises (IDBDatabaseException); Exceptions This method can raise an IDBDatabaseException with the following code: NON_TRANSIENT_ERR...
...ations performed by this transaction. When this method is called, the browser ignores all the changes performed to the objects of this database since this transaction was created. void abort( ) raises (IDBDatabaseException); Exceptions This method can raise an IDBDatabaseException with the following code: NON_TRANSIENT_ERR If this transaction has already been committed or aborted. commit
() Call this method to signal that the transaction has completed normally and satisfactorily. When this method is called, the browser durably stores all the changes performed to the objects of the database since this transaction was created. void commit( ) raises (IDBDatabaseException); Exceptions This method can raise an IDBDatabaseException with the following codes: NON_TRANSIENT_ERR If t...
...e 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 the requested object store. Exceptions The method can raise an IDBDatabaseException with the following c...
Keyboard - Web APIs
The Keyboard interface of the the Keyboard API provides functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard. A list of valid code values is found in the UI Events KeyboardEvent code Values spec. Properties None. Methods Keyboard.getLayoutMap
() Returns a Promise that resolves with an instance of KeyboardLayoutMap which is a map-like object with functions for retrieving the strings associated with specific physical keys. Keyboard.lock
() Returns a Promise after enabling the capture of keypresses for any or all of the keys on the physical keyboard. Keyboard.unlock
() Unlocks all keys captured by the lock
() method and returns synchronously. Example The following example demonstrates how to get the location- or ...
...} Specifications Specification Status Comment Keyboard MapThe definition of 'Keyboard' in that specification. Editor's Draft Initial definition. ...
... ...
... ...
KeyboardEvent - Web APIs
Constants The KeyboardEvent interface defines the following constants. Keyboard locations The following constants identify which part of the keyboard the key event originates from. They are accessed as KeyboardEvent.DOM_KEY_LOCATION_STANDARD and so forth. Keyboard location identifiers Constant Value Description DOM_KEY_LOCATI...
...ent was generated. KeyboardEvent.repeat Read only Returns a Boolean that is true if the key is being held down such that it is automatically repeating. KeyboardEvent.shiftKey Read only Returns a Boolean that is true if the Shift key was active when the key event was generated. Methods This interface also inherits methods of its parents, UIEvent and Event. ...
...tKey Read only Returns a Boolean that is true if the Shift key was active when the key event was generated. Methods This interface also inherits methods of its parents, UIEvent and Event. KeyboardEvent.getModifierState
() Returns a Boolean indicating if a modifier key such as Alt, Shift, Ctrl, or Meta, was pressed when the event was created. Obsolete methods KeyboardEvent.initKeyEvent
() Initializes a KeyboardEvent object. This was implemented only by Firefox, and is no longer supported even there; instead, you should use the KeyboardEvent
() constructor. KeyboardEvent.initKeyboardEvent
() Initializes a KeyboardEvent object. This is now deprecated. You should instead use the KeyboardEvent
() constructor. Obsolete properties KeyboardEvent.char Read only Returns a DOMS...
...finition of 'KeyboardEvent' in that specification. Working Draft The KeyboardEvent interface specification went through numerous draft versions, first under DOM Events Level 2 where it was dropped as no consensus arose, then under DOM Events Level 3. This led to the implementation of non-standard initialization methods, the early DOM Events Level 2 version, KeyboardEvent.initKeyEvent
() by Gecko browsers and the early DOM Events Level 3 version, KeyboardEvent.initKeyboardEvent
() by others. Both have been superseded by the modern usage of a constructor: KeyboardEvent
(). ...
Location - Web APIs
ore, :target:before {background:black; color:yellow;} [title] [title]:before {margin-top:1.5em;} [title] [title] [title]:before {margin-top:3em;} [title]:hover, :target {position:relative; z-index:1; outline:50em solid rgba(255,255,255,.8);} JavaScript [].forEach.call(document.querySelectorAll('[title][id]'), function (node) { node.addEventListener("click", function(e) { e.preventDefault
(); e.stopPropagation
(); window.location.hash = '#' + $(this).attr('id'); }); }); [].forEach.call(document.querySelectorAll('[title]'), function (node) { node.addEventListener("click", function(e) { e.preventDefault
(); e.stopPropagation
(); window.location.hash = ''; }); }); Result Properties Location.ancestorOrigins Is a static DOMStringList containing, in reverse o...
... or "querystring" of the URL. Modern browsers provide URLSearchParams and URL.searchParams to make it easy to parse out the parameters from the querystring. Location.hash Is a USVString containing a '#' followed by the fragment identifier of the URL. Location.origin Read only Returns a USVString containing the canonical form of the origin of the specific location. ...
... URL.searchParams to make it easy to parse out the parameters from the querystring. Location.hash Is a USVString containing a '#' followed by the fragment identifier of the URL. Location.origin Read only Returns a USVString containing the canonical form of the origin of the specific location. Methods Location.assign
() Loads the resource at the URL provided in parameter. Location.reload
() Reloads the current URL, like the Refresh button. Location.replace
() Replaces the current resource with the one at the provided URL (redirects to the provided URL). The difference from the assign
() method and setting the href property is that after using replace
() the current page will not be saved in session History, meaning the user won't be able to use the back button to navigate to it. Lo...
...It is a synonym for HTMLHyperlinkElementUtils.href, though it can't be used to modify the value. ...
Lock - Web APIs
LockManager is the object returned by navigator.locks. ...
...LockManager is the object returned by navigator.locks. ...
...LockManager is the object returned by navigator.locks. ...
...LockManager is the object returned by navigator.locks. ...
MediaDeviceInfo.groupId - Web APIs
devices which are part of the same group as a given device. This might be used to produce a user interface that gathers associated devices together for presentation purposes, or to make it easy for the user to choose to use the built-in camera and microphone on the same display at the same time. const getDeviceGroup = mainDevInfo => { let devList = []; navigator.mediaDevices.enumerateDevices
() .then(devices => { devices.forEach(device => { if (device.groupId === mainDevInfo.groupId) { devList.push(device); } }); }); return devList; }; The getDeviceGroup
() function takes as input the MediaDeviceInfo object describing the device for which a group list is to be built. The function starts by initializing the result array, devList, to be an empty array. ...
...For each device, if its groupId matches the main device's groupId, we push the MediaDeviceInfo object onto the list. ...
...For each device, if its groupId matches the main device's groupId, we push the MediaDeviceInfo object onto the list. Finally, the list, which now contains a MediaDeviceInfo object for each device in the same group, is returned to the caller. ...
...ce it at the top of the list, by comparing the two objects' deviceId values, only pushing the device onto the result list if it doesn't match. ...
MediaDeviceInfo - Web APIs
Properties MediaDeviceInfo.deviceIdRead only Returns a DOMString that is an identifier for the represented device that is persisted across sessions. It is un-guessable by other applications and unique to the origin of the calling application. ...
...cribing this device (for example "External USB Webcam"). For security reasons, the label field is always blank unless an active media stream exists or the user has granted persistent permission for media device access. The set of device labels could otherwise be used as part of a fingerprinting mechanism to identify a user. Methods None. ...
... stream exists or the user has granted persistent permission for media device access. The set of device labels could otherwise be used as part of a fingerprinting mechanism to identify a user. Methods None. Example Here's an example that uses enumerateDevices
() to get a list of devices. if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) { console.log("enumerateDevices
() not supported."); return; } // List cameras and microphones. ...
...els could otherwise be used as part of a fingerprinting mechanism to identify a user. Methods None. Example Here's an example that uses enumerateDevices
() to get a list of devices. if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) { console.log("enumerateDevices
() not supported."); return; } // List cameras and microphones. ...
MediaDevices - Web APIs
ssence, it lets you obtain access to any hardware source of media data. Properties Inherits properties from its parent interface, EventTarget. Events devicechange Fired when a media input or output device is attached to or removed from the user's computer. Also available via the ondevicechange property. Methods Inherits methods from its parent interface, EventTarget. enumerateDevices
() Obtains an array of information about the media input and output devices available on the system. getSupportedConstraints
() Returns an object conforming to MediaTrackSupportedConstraints indicating which constrainable properties are supported on the MediaStreamTrack interface. See Capabilities and constraints in Media Capture and Streams API (Media Stream) to learn more about constraints and h...
...n about the media input and output devices available on the system. getSupportedConstraints
() Returns an object conforming to MediaTrackSupportedConstraints indicating which constrainable properties are supported on the MediaStreamTrack interface. See Capabilities and constraints in Media Capture and Streams API (Media Stream) to learn more about constraints and how to use them. getDisplayMedia
() Prompts the user to select a display or portion of 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. ...
...t. Example 'use strict'; // Put variables in global scope to make them available to the browser console. ...
...onstraints = 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); console.log('Using video device: ' + videoTracks[0].label); stream.onremovetrack = function
() { console.log('Stream ended'); }; window.stream = stream; // make variable available to browser console video.srcObject = stream; }) .catch(function(error) { if (error.name === 'ConstraintNotSatisfiedError') { errorMsg('The resolution ' + constraints.video.width.exact + 'x' + constraints.video.height.exact + ' px is not supported by your device.'); } else if (error.name ...
MediaRecorder: error event - Web APIs
ing wasn't allowed or was attempted using an unsupported codec. Bubbles No Cancelable No Interface MediaRecorderErrorEvent Event handler property onerror For details of the all the possible errors see the documentation for the event handler property: onerror. ...
...r the event handler property: onerror. ...
...andler property: onerror. ...
...nts: async function record
() { const stream = await navigator.mediaDevices.getUserMedia({audio: true}); const recorder = new MediaRecorder(stream); recorder.addEventListener('error', (event) => { console.error(`error recording stream: ${event.error.name}`) }); recorder.start
(); } record
(); The same, but using the onerror event handler property: async function record
() { const stream = await navigator.mediaDevices.getUserMedia({audio: true}); const recorder = new MediaRecorder(stream); recorder.onerror = (event) => { console.error(`error recording stream: ${event.error.name}`) }; recorder.start
(); } record
(); Specifications Specification Status MediaStream Recording Working Draft ...
MediaRecorder.ondataavailable - Web APIs
to Blob data being made available for use. The dataavailable event is fired when the MediaRecorder delivers media data to your application for its use. The data is provided in a Blob object that contains the data. This occurs in four situations: When the media stream ends, any media data not already delivered to your ondataavailable handler is passed in a single Blob. ...
...the data. This occurs in four situations: When the media stream ends, any media data not already delivered to your ondataavailable handler is passed in a single Blob. When MediaRecorder.stop
() is called, all media data which has been captured since recording began or the last time a dataavailable event occurred is delivered in a Blob; after this, capturing ends. When MediaRecorder.requestData
() is called, all media data which has been captured since recording began or the last time a dataavailable event occurred is delivered; then a new Blob is created and media capture continues into that blob. If a timeslice property was passed into the MediaRecorder.start
() method that started media capture, a dataavailable event is fired every timeslice milliseconds. That means that each blob will ...
... (except the last blob, which might be shorter, since it would be whatever is left over since the last event). So if the method call looked like this -- recorder.start(1000); -- the dataavailable event would fire after each second of media capture, and our event handler would be called every second with a blob of media data that's one second long. You can use timeslice alongside MediaRecorder.stop
() and MediaRecorder.requestData
() to produce multiple same-length blobs plus other shorter blobs as well. The Blob containing the media data is available in the dataavailable event's data property. Syntax MediaRecorder.ondataavailable = function(event) { ... } MediaRecorder.addEventListener('dataavailable', function(event) { ... }) Example ... var chunks = []; mediaRecorder.onstop = f...
...s plus other shorter blobs as well. The Blob containing the media data is available in the dataavailable event's data property. Syntax MediaRecorder.ondataavailable = function(event) { ... } MediaRecorder.addEventListener('dataavailable', function(event) { ... }) Example ... var chunks = []; mediaRecorder.onstop = function(e) { console.log("data available after MediaRecorder.stop
() called."); var audio = document.createElement('audio'); audio.controls = true; var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audioURL = window.URL.createObjectURL(blob); audio.src = audioURL; console.log("recorder stopped"); } mediaRecorder.ondataavailable = function(e) { chunks.push(e.data); } ... Specifications Specifica...
MediaSettingsRange - Web APIs
The MediaSettingsRange interface of the the MediaStream Image Capture API provides the possible range and value size of PhotoCapabilities.imageHeight and PhotoCapabilities.imageWidth. A PhotoCapabilities object can be retrieved by calling ImageCapture.PhotoCapabilities
(). Properties MediaSettingsRange.max Returns the maximum value of this settings. MediaSettingsRange.min Returns the minimum value of this setting. MediaSettingsRange.step Returns the minimum difference between consecutive values of this setting. Example The following example, extracted from Chrome's Image Capture / Photo Resolution Sample, uses the results from getPhotoCapabilities
().imageWidth to modify the size of an input range. const input = document.querySelector('input[type="range"]'); var imageCap...
...me's Image Capture / Photo Resolution Sample, uses the results from getPhotoCapabilities
().imageWidth to modify the size of an input range. ...
...mageWidth to modify the size of an input range. ...
...or('input[type="range"]'); var imageCapture; navigator.mediaDevices.getUserMedia({video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream; const track = mediaStream.getVideoTracks
()[0]; imageCapture = new ImageCapture(track); return imageCapture.getPhotoCapabilities
(); }) .then(photoCapabilities => { const settings = imageCapture.track.getSettings
(); input.min = photoCapabilities.imageWidth.min; input.max = photoCapabilities.imageWidth.max; input.step = photoCapabilities.imageWidth.step; return imageCapture.getPhotoSettings
(); }) .then(photoSettings => { input.value = photoSettings.imageWidth; }) .catch(error => console.log('Argh!', error.name || error)); Specifications Specification Status Comment Media...
MediaStreamAudioSourceNode - Web APIs
The MediaStreamAudioSourceNode interface is a type of AudioNode which operates as an audio source whose media is received from a MediaStream obtained using the WebRTC or Media Capture and Streams APIs. This media could be from a microphone (through getUserMedia
()) or from a remote peer on a WebRTC call (using the RTCPeerConnection's audio tracks). A MediaStreamAudioSourceNode has no inputs and exactly one output, and is created using the AudioContext.createMediaStreamSource
() method. The MediaStreamAudioSourceNode takes the audio from the first MediaStreamTrack whose kind attribute's value is audio. See Track ordering for more information about the order of tracks. The number of channels output by the node matches the number of tracks found in the selected audio track. Number...
...ck whose kind attribute's value is audio. See Track ordering for more information about the order of tracks. The number of channels output by the node matches the number of tracks found in the selected audio track. Number of inputs 0 Number of outputs 1 Channel count defined by the first audio MediaStreamTrack passed to the AudioContext.createMediaStreamSource
() method that created it. Constructor new MediaStreamAudioSourceNode
() Creates a new MediaStreamAudioSourceNode object instance with the specified options. Properties In addition to the following properties, MediaStreamAudioSourceNode inherits the properties of its parent, AudioNode. mediaStream Read only The MediaStream used when constructing this MediaStreamAudioSourceNode. M...
...etUserMedia block - grab stream // put it into a MediaStreamAudioSourceNode // also output the visuals into a video element if (navigator.mediaDevices) { console.log('getUserMedia supported.'); navigator.mediaDevices.getUserMedia ({audio: true, video: true}) .then(function(stream) { video.srcObject = stream; video.onloadedmetadata = function(e) { video.play
(); video.muted = true; }; // Create a MediaStreamAudioSourceNode // Feed the HTMLMediaElement into it var audioCtx = new AudioContext
(); var source = audioCtx.createMediaStreamSource(stream); // Create a biquadfilter var biquadFilter = audioCtx.createBiquadFilter
(); biquadFilter.type = "lowshelf"; biquadFilter.fre...
...nect the AudioBufferSourceNode to the gainNode // and the gainNode to the destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(biquadFilter); biquadFilter.connect(audioCtx.destination); // Get new mouse pointer coordinates when mouse is moved // then set new gain value range.oninput = function
() { biquadFilter.gain.value = range.value; } }) .catch(function(err) { console.log('The following gUM error occured: ' + err); }); } else { console.log('getUserMedia not supported on your browser!'); } // dump script to pre element pre.innerHTML = myScript.innerHTML; Note: As a consequence of calling createMediaStreamSource
(), audio playback from the m...
MediaStreamTrackAudioSourceNode - Web APIs
en from a specific MediaStreamTrack obtained through the WebRTC or Media Capture and Streams APIs. The audio itself might be input from a microphone or other audio sampling device, or might be received through a RTCPeerConnection, among other posible options. A MediaStreamTrackAudioSourceNode has no inputs and exactly one output, and is created using the AudioContext.createMediaStreamTrackSource
() method. This interface is similar to MediaStreamAudioSourceNode, except it lets you specifically state the track to use, rather than assuming the first audio track on a stream. Number of inputs 0 Number of outputs 1 Channel count defined by the first audio MediaStreamTrack passed to the AudioContext.createMediaStreamTrackSource
() method that created it. ...
...dioSourceNode, except it lets you specifically state the track to use, rather than assuming the first audio track on a stream. Number of inputs 0 Number of outputs 1 Channel count defined by the first audio MediaStreamTrack passed to the AudioContext.createMediaStreamTrackSource
() method that created it. Constructor new MediaStreamTrackAudioSourceNode
() Creates a new MediaStreamTrackAudioSourceNode object instance with the specified options. Properties The MediaStreamTrackAudioSourceNode interface has no properties of its own; however, it inherits the properties of its parent, AudioNode. Methods Inherits methods from its parent, AudioNode. Example In this example, we grab a media (audio + video) stream from navigator.getUserMedia, feed t...
...etUserMedia block - grab stream // put it into a MediaStreamAudioSourceNode // also output the visuals into a video element if (navigator.mediaDevices) { console.log('getUserMedia supported.'); navigator.mediaDevices.getUserMedia ({audio: true, video: true}) .then(function(stream) { video.srcObject = stream; video.onloadedmetadata = function(e) { video.play
(); video.muted = true; }; // Create a MediaStreamAudioSourceNode // Feed the HTMLMediaElement into it var audioCtx = new AudioContext
(); var source = audioCtx.createMediaStreamSource(stream); // Create a biquadfilter var biquadFilter = audioCtx.createBiquadFilter
(); biquadFilter.type = "lowshelf"; biquadFilter.fre...
...nect the AudioBufferSourceNode to the gainNode // and the gainNode to the destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(biquadFilter); biquadFilter.connect(audioCtx.destination); // Get new mouse pointer coordinates when mouse is moved // then set new gain value range.oninput = function
() { biquadFilter.gain.value = range.value; } }) .catch(function(err) { console.log('The following gUM error occured: ' + err); }); } else { console.log('getUserMedia not supported on your browser!'); } // dump script to pre element pre.innerHTML = myScript.innerHTML; Note: As a consequence of calling createMediaStreamSource
(), audio playback from the m...
MediaStreamTrackAudioSourceOptions.mediaStreamTrack - Web APIs
The MediaStreamTrackAudioSourceOptions dictionary's mediaStreamTrack property must contain a reference to the MediaStreamTrack from which the MediaStreamTrackAudioSourceNode being created using the MediaStreamTrackAudioSourceNode
() constructor. Syntax mediaStreamTrackAudioSourceOptions = { mediaStreamTrack: audioSourceTrack; } mediaStreamTrackAudioSourceOptions.mediaStreamTrack = audioSourceTrack; Value A MediaStreamTrack from which the audio output of the new MediaStreamTrackAudioSourceNode will be taken. ...
...udioSourceNode being created using the MediaStreamTrackAudioSourceNode
() constructor. Syntax mediaStreamTrackAudioSourceOptions = { mediaStreamTrack: audioSourceTrack; } mediaStreamTrackAudioSourceOptions.mediaStreamTrack = audioSourceTrack; Value A MediaStreamTrack from which the audio output of the new MediaStreamTrackAudioSourceNode will be taken. Example This example uses getUserMedia
() to obtain access to the user's camera, then creates a new MediaStreamAudioSourceNode from the first audio track provided by the device. ...
....mediaStreamTrack = audioSourceTrack; Value A MediaStreamTrack from which the audio output of the new MediaStreamTrackAudioSourceNode will be taken. Example This example uses getUserMedia
() to obtain access to the user's camera, then creates a new MediaStreamAudioSourceNode from the first audio track provided by the device. ...
... then creates a new MediaStreamAudioSourceNode from the first audio track provided by the device. ...
MediaStream Image Capture API - Web APIs
they are currently set to. Conversely, the API allows the capabilities to be configured within the constraints what the device allows. MediaStream image capture concepts and usage The process of retrieving an image or video stream happens as described below. The example code is adapted from Chrome's Image Capture examples. First, get a reference to a device by calling MediaDevices.getUserMedia
(). The example below simply says give me whatever video device is available, though the getUserMedia
() method allows more specific capabilities to be requested. This method returns a Promise that resolves with a MediaStream object. navigator.mediaDevices.getUserMedia({ video: true }) .then(mediaStream => { // Do something with the stream. }) Next, isolate the visual part of the media str...
...ideo device is available, though the getUserMedia
() method allows more specific capabilities to be requested. This method returns a Promise that resolves with a MediaStream object. navigator.mediaDevices.getUserMedia({ video: true }) .then(mediaStream => { // Do something with the stream. }) Next, isolate the visual part of the media stream. Do this by calling MediaStream.getVideoTracks
(). This returns an array of MediaStreamTrack objects. The code below assumes that the first item in the MediaStreamTrack array is the one to use. You can use the properties of the MediaStreamTrack objects to select the one you need. const track = mediaStream.getVideoTracks
()[0]; At this point, you might want to configure the device capabilities before capturing an image. You can do this by callin...
...array of MediaStreamTrack objects. The code below assumes that the first item in the MediaStreamTrack array is the one to use. You can use the properties of the MediaStreamTrack objects to select the one you need. const track = mediaStream.getVideoTracks
()[0]; At this point, you might want to configure the device capabilities before capturing an image. You can do this by calling applyConstraints
() on the track object before doing anything else. let zoom = document.querySelector('#zoom'); const capabilities = track.getCapabilities
(); // Check whether zoom is supported or not. if(!capabilities.zoom) { return; } track.applyConstraints({ advanced : [{ zoom: zoom.value }] }); Finally, pass the MediaStreamTrack object to the ImageCapture
() constructor. Though a MediaStream holds several typ...
...if MediaStreamTrack.kind is not "video". let imageCapture = new ImageCapture(track); Interfaces ImageCapture An interface for capturing images from a photographic device referenced through a valid MediaStreamTrack. PhotoCapabilities Provides available configuration options for an attached photographic device. Retrieve a PhotoCapabilities object by calling ImageCapture.getPhotoCapabilities
(). Specifications Specification Status Comment MediaStream Image Capture Working Draft Initial definition. ...
MediaTrackConstraints.cursor - Web APIs
escribing the requested or mandatory constraints placed upon the value of the cursor constrainable property, which is used to specify whether or not the cursor should be included in the captured video. If needed, you can determine whether or not this constraint is supported by checking the value of MediaTrackSupportedConstraints.cursor as returned by a call to MediaDevices.getSupportedConstraints
(). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Syntax var constraintsObject = { cursor: constraint }; constraintsObject.cursor = constraint; Value A ConstrainDOMString which specifies whether or not the mouse cursor should be rendered into the video track in the MediaStream returned by the call to getDisplayMedia
(). See How...
...which specifies whether or not the mouse cursor should be rendered into the video track in the MediaStream returned by the call to getDisplayMedia
(). See How constraints are defined in Capabilities, constraints, and settings for an explanation of how to define constraints. Usage notes You can check the setting selected by the user agent after the display media has been created by getDisplayMedia
() by calling getSettings
() on the display media's video MediaStreamTrack, then checking the value of the returned MediaTrackSettings object's cursor object. For example, if your app needs to alter the stream by inserting a representation of the cursor position if the stream doesn't include the rendered cursor, you can determine the need to do so by using code like this: let insertFakeCursorFlag ...
...edia's video MediaStreamTrack, then checking the value of the returned MediaTrackSettings object's cursor object. For example, if your app needs to alter the stream by inserting a representation of the cursor position if the stream doesn't include the rendered cursor, you can determine the need to do so by using code like this: let insertFakeCursorFlag = false; if (displayStream.getVideoTracks
()[0].getSettings
().cursor === "never") { insertFakeCursorFlag = true; } Following this code, insertFakeCursorFlag is true if there's no cursor rendered into the stream already. Later code can detect this flag's value and if it's true, can manually look at some metadata that might be provided and insert a fake representation of the cursor at the correct position. Examples Here are some example...
... insertFakeCursorFlag = true; } Following this code, insertFakeCursorFlag is true if there's no cursor rendered into the stream already. Later code can detect this flag's value and if it's true, can manually look at some metadata that might be provided and insert a fake representation of the cursor at the correct position. Examples Here are some example constraints objects for getDisplayMedia
() that make use of the cursor property. In addition, see Example: Constraint exerciser in Capabilities, constraints, and settings for a complete example showing how constraints are used. Example: Cursor always visible This example sets up the constraints to request that the cursor always be visible. let displayMediaOptions = { cursor: "always" }; Example: Cursor visible during motion with fa...
MediaTrackConstraints.displaySurface - Web APIs
The MediaTrackConstraints dictionary's displaySurface property is a ConstrainDOMString describing the requested or mandatory constraints placed upon the value of the displaySurface constrainable property. This is used to specify the type or types of display surfaces which getDisplayMedia
() will let the user select among for sharing purposes. If needed, you can determine whether or not this constraint is supported by checking the value of MediaTrackSupportedConstraints.displaySurface as returned by a call to MediaDevices.getSupportedConstraints
(). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Syntax var constraintsObject = { displaySurface: constraint }; constraintsObject.displaySurface = constraint; Value A Constrain...
...specifies the type of display surface that's being captured. This value does not affect the list of display sources in the browser's user interface. See How constraints are defined in Capabilities, constraints, and settings for an explanation of how to define constraints. Usage notes You can check the setting selected by the user agent after the display media has been created by getDisplayMedia
() by calling getSettings
() on the display media's video MediaStreamTrack, then checking the value of the returned MediaTrackSettings object's displaySurface object. For example, if your app needs to know that the surface being shared is a monitor or application--meaning that there's possibly a non-content backdrop--it can use code similar to this: let mayHaveBackdropFlag = false; let displaySurf...
...isplay media's video MediaStreamTrack, then checking the value of the returned MediaTrackSettings object's displaySurface object. For example, if your app needs to know that the surface being shared is a monitor or application--meaning that there's possibly a non-content backdrop--it can use code similar to this: let mayHaveBackdropFlag = false; let displaySurface = displayStream.getVideoTracks
()[0].getSettings
().displaySurface; if (displaySurface === "monitor" || displaySurface ==="application") { mayHaveBackdropFlag = true; } Following this code, mayHaveBackdrop is true if the display surface contained in the stream is of type monitor or application; either of these may have non-content backdrop areas. Later code can use this flag to determine whether or not to perform special pro...
...urface contained in the stream is of type monitor or application; either of these may have non-content backdrop areas. Later code can use this flag to determine whether or not to perform special processing, such as to remove or replace the backdrop, or to "cut" the individual display areas out of the received frames of video. Examples Here are some example constraints objects for getDisplayMedia
() that make use of the displaySurface property. In addition, see Example: Constraint exerciser in Capabilities, constraints, and settings for a complete example showing how constraints are used. TBD Specifications Specification Status Comment Screen CaptureThe definition of 'MediaTrackConstraints.displaySurface' in that specification. Unknown Initial specificati...
MediaTrackConstraints.logicalSurface - Web APIs
The MediaTrackConstraints dictionary's logicalSurface property is a ConstrainDOMString describing the requested or mandatory constraints placed upon the value of the logicalSurface constrainable property. This is used to specify whether or not getDisplayMedia
() should allow the user to choose display surfaces which are not necessarily fully visible on the screen, such as occluded windows or the complete content of windows which are large enough to require scrolling to see their entire contents. If needed, you can determine whether or not this constraint is supported by checking the value of MediaTrackSupportedConstraints.logicalSurface as returned by a call to MediaDevices.getSupportedConstraints
(). However, typically this is unnecessary since browsers will simply ignore any constraints th...
...lSurface = constraint; Value A ConstrainBoolean which is true if logical surfaces should be permitted among the selections available to the user. See How constraints are defined in Capabilities, constraints, and settings for an explanation of how to define constraints. ...
...Value A ConstrainBoolean which is true if logical surfaces should be permitted among the selections available to the user. See How constraints are defined in Capabilities, constraints, and settings for an explanation of how to define constraints. ...
...ting selected by the user agent after the display media has been created by getDisplayMedia
() by calling getSettings
() on the display media's video MediaStreamTrack, then checking the value of the returned MediaTrackSettings object's logicalSurface object. For example, if your app needs to know if the selected display surface is a logical one: let isLogicalSurface = displayStream.getVideoTracks
()[0].getSettings
().logicalSurface; Following this code, isLogicalSurface is true if the display surface contained in the stream is a logical surface; that is, one which may not be entirely onscreen, or may even be entirely offscreen. Specifications Specification Status Comment Screen CaptureThe definition of 'MediaTrackConstraints.logicalSurface' in that specificati...
MediaTrackSupportedConstraints.cursor - Web APIs
The MediaTrackSupportedConstraints dictionary's cursor property indicates whether or not the cursor constraint is supported by the user agent and the device on which the content is being used. The supported constraints list is obtained by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax isCursorSupported = supportedConstraints.cursor; Value A Boolean value which is true if the cursor constraint is supported by the device and user agent. ...
...content is being used. The supported constraints list is obtained by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax isCursorSupported = supportedConstraints.cursor; Value A Boolean value which is true if the cursor constraint is supported by the device and user agent. Example This method sets up the constraints object specifying the options for the call to getDisplayMedia
(). It adds the cursor constraint only if it is known to be supported by the browser. Capturing is then started by calling getDisplayMedia
() and attaching the returned stream to the video element referenced by the variable videoElem. ...
...he device and user agent. Example This method sets up the constraints object specifying the options for the call to getDisplayMedia
(). It adds the cursor constraint only if it is known to be supported by the browser. Capturing is then started by calling getDisplayMedia
() and attaching the returned stream to the video element referenced by the variable videoElem. ...
...pecifying the options for the call to getDisplayMedia
(). It adds the cursor constraint only if it is known to be supported by the browser. Capturing is then started by calling getDisplayMedia
() and attaching the returned stream to the video element referenced by the variable videoElem. ...
MediaTrackSupportedConstraints.displaySurface - Web APIs
The MediaTrackSupportedConstraints dictionary's displaySurface property indicates whether or not the displaySurface constraint is supported by the user agent and the device on which the content is being used. The supported constraints list is obtained by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax isDisplaySurfaceSupported = supportedConstraints.displaySurface; Value A Boolean value which is true if the displaySurface constraint is supported by the device and user agent. Example This method sets up the constraints object specifying the options for the call to getDisplayMedia
(). It adds the displaySurface constraint (requesting that only full-screen sharing be allowed) only if it is known to be supported by the browser. Capturing is then started by calling getDis...
...ue which is true if the displaySurface constraint is supported by the device and user agent. Example This method sets up the constraints object specifying the options for the call to getDisplayMedia
(). It adds the displaySurface constraint (requesting that only full-screen sharing be allowed) only if it is known to be supported by the browser. Capturing is then started by calling getDisplayMedia
() and attaching the returned stream to the video element referenced by the variable videoElem. ...
... up the constraints object specifying the options for the call to getDisplayMedia
(). It adds the displaySurface constraint (requesting that only full-screen sharing be allowed) only if it is known to be supported by the browser. Capturing is then started by calling getDisplayMedia
() and attaching the returned stream to the video element referenced by the variable videoElem. ...
...a
(). It adds the displaySurface constraint (requesting that only full-screen sharing be allowed) only if it is known to be supported by the browser. Capturing is then started by calling getDisplayMedia
() and attaching the returned stream to the video element referenced by the variable videoElem. ...
MediaTrackSupportedConstraints.logicalSurface - Web APIs
The MediaTrackSupportedConstraints dictionary's logicalSurface property indicates whether or not the logicalSurface constraint is supported by the user agent and the device on which the content is being used. The supported constraints list is obtained by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax isLogicalSurfaceSupported = supportedConstraints.logicalSurface; Value A Boolean value which is true if the logicalSurface constraint is supported by the device and user agent. Example This method sets up the constraints object specifying the options for the call to getDisplayMedia
(). It adds the logicalSurface constraint (requesting that only logical display surfaces--those which may not be entirely visible onscreen--be included among the options available to the user...
...mple This method sets up the constraints object specifying the options for the call to getDisplayMedia
(). It adds the logicalSurface constraint (requesting that only logical display surfaces--those which may not be entirely visible onscreen--be included among the options available to the user) only if it is known to be supported by the browser. Capturing is then started by calling getDisplayMedia
() and attaching the returned stream to the video element referenced by the variable videoElem. ...
...logicalSurface constraint (requesting that only logical display surfaces--those which may not be entirely visible onscreen--be included among the options available to the user) only if it is known to be supported by the browser. Capturing is then started by calling getDisplayMedia
() and attaching the returned stream to the video element referenced by the variable videoElem. ...
...which may not be entirely visible onscreen--be included among the options available to the user) only if it is known to be supported by the browser. Capturing is then started by calling getDisplayMedia
() and attaching the returned stream to the video element referenced by the variable videoElem. ...
Media Session API - Web APIs
layback interactions. Dictionaries MediaImage A MediaImage object contains information describing an image associated with the media. This might be a CD or DVD cover, a movie poster, a poster frame, or the like. MediaPositionState Used to contain information about the current playback position, playback speed, and overall media duration when calling the MediaSession method setPositionState
() to establish the media's length, playback position, and playback speed. MediaSessionActionDetails Provides information needed in order to perform the action which has been requested, including the type of action to perform and any other information needed, such as seek distances or times. Examples The following example shows feature detection for the Media Session API. It then instantiates a...
...ttps://dummyimage.com/192x192', sizes: '192x192', type: 'image/png' }, { src: 'https://dummyimage.com/256x256', sizes: '256x256', type: 'image/png' }, { src: 'https://dummyimage.com/384x384', sizes: '384x384', type: 'image/png' }, { src: 'https://dummyimage.com/512x512', sizes: '512x512', type: 'image/png' }, ] }); navigator.mediaSession.setActionHandler('play', function
() { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler('pause', function
() { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler('seekbackward', function
() { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler('seekforward', function
() { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler('previoustrack', function
() { /* Code excerpte...
...*/ }); } Some user agents disable autoplay for media elements on mobile devices and require a user gesture to start media. ...
...disable autoplay for media elements on mobile devices and require a user gesture to start media. The following example adds a pointerup event to an on-page play button, which is then used to kick off the media session code: playButton.addEventListener('pointerup', function(event) { var audio = document.querySelector('audio'); // User interacted with the page. Let's play audio... audio.play
() .then(_ => { /* Set up media session controls, as shown above. */ }) .catch(error => { console.log(error) }); }); Specifications Specification Status Comment Media Session Standard Draft Initial definition. ...
MessagePort - Web APIs
The MessagePort interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. Note: This feature is available in Web Workers. Methods Inherits methods from its parent, EventTarget postMessage
() Sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts. start
() Starts the sending of messages queued on the port (only needed when using EventTarget.addEventListener; it is implied when using MessagePort.onmessage.) close
() Disconnects the port, so it is no longer active. Event handlers Inherits event handlers from its parent, EventTarget onmessage An EventListener called when MessageEvent of type message is fir...
...a message that cannot be deserialized. Events message Fired when a MessagePort object receives a message. Also available via the onmessage property. messageerror Fired when a MessagePort object receives a message that can't be deserialized. Also available via the onmessageerror property. ...
...nel being created using the MessageChannel
() constructor. When the IFrame has loaded, we register an onmessage handler for MessageChannel.port1 and transfer MessageChannel.port2 to the IFrame using the window.postMessage method along with a message. When a message is received back from the IFrame, the onMessage function simply outputs the message to a paragraph. ...
...rame using the window.postMessage method along with a message. When a message is received back from the IFrame, the onMessage function simply outputs the message to a paragraph. var channel = new MessageChannel
(); var output = document.querySelector('.output'); var iframe = document.querySelector('iframe'); // Wait for the iframe to load iframe.addEventListener("load", onLoad); function onLoad
() { // Listen for messages on port1 channel.port1.onmessage = onMessage; // Transfer port2 to the iframe iframe.contentWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } // Handle messages received on port1 function onMessage(e) { output.innerHTML = e.data; } For a full working example, see our channel messaging basic demo on Github (run it live too). Specifica...
MutationObserverInit.attributeFilter - Web APIs
Filter is included in the options object, all attributes' values are watched for changes. Syntax var options = { attributeFilter: [ "list", "of", "attribute", "names" ] } Value An array of DOMString objects, each specifying the name of one attribute whose value is to be monitored for changes. There is no default value. If this property exists on the options object when the MutationObserver
() constructor is used to create a new MutationObserver, attribute monitoring is enabled regardless of whether or not the attributes property is true. Example In this example, a Mutation Observer is set up to watch for changes to the status and username attributes in any elements contained within a subtree that displays the names of users in a chat room. This lets the code, for example, reflect ch...
...For any items representing an attribute change (which can be detected by the value of MutationRecord.type being "attributes"), we use the attribute's name, obtained using MutationRecord.attributeName, to identify the type of change that occurred and then d...
...For any items representing an attribute change (which can be detected by the value of MutationRecord.type being "attributes"), we use the attribute's name, obtained using MutationRecord.attributeName, to identify the type of change that occurred and then dispatch to the appropriate handler function. Note...
...f MutationRecord.type being "attributes"), we use the attribute's name, obtained using MutationRecord.attributeName, to identify the type of change that occurred and then dispatch to the appropriate handler function. Note the use of MutationRecord.oldValue to get the previous value of the "username" property so we have that information when doing lookups in our local array of users. When observe
() is called, the specified options include both attributeFilter and subtree, so that we monitor the attribute values for all of the nodes contained within the subtree rooted at the node with the ID "userlist". The attributeOldValue option is set to true because we want the prior value of the changed attributes recorded and reported in the mutation records we receive. Specifications Speci...
NodeFilter - Web APIs
A NodeFilter interface represents an object used to filter the nodes in a NodeIterator or TreeWalker. A NodeFilter knows nothing about the document or traversing nodes; it only knows how to evaluate a single node against the provided filter. Note: The browser doesn't provide any object implementing this interface. It is the user who is expected to write one, tailoring the acceptNode
() method to its needs, and using it with some TreeWalker or NodeIterator objects. Properties This interface neither implements nor inherits any properties. Methods This interface doesn't inherit any methods. NodeFilter.acceptNode
() Returns an unsigned short that will be used to tell if a given Node must be accepted or not by the NodeIterator or TreeWalker iteration algorithm. This method is expect...
...ethods. NodeFilter.acceptNode
() Returns an unsigned short that will be used to tell if a given Node must be accepted or not by the NodeIterator or TreeWalker iteration algorithm. This method is expected to be written by the user of a NodeFilter. Possible return values are: Constant Description FILTER_ACCEPT Value returned by the NodeFilter.acceptNode
() method when a node should be accepted. FILTER_REJECT Value to be returned by the NodeFilter.acceptNode
() method when a node should be rejected. For TreeWalker, child nodes are also rejected. For NodeIterator, this flag is synonymous with FILTER_SKIP. ...
... The children of skipped nodes are still considered. This is treated as "skip this node but not its children". ...
... Living Standard Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'NodeFilter' in that specification. Obsolete Initial definition. ...
NodeIterator - Web APIs
NodeIterator.root Read only Returns a Node representing the root node as specified when the NodeIterator was created. ...
...ded at the same time. NodeIterator.referenceNode Read only Returns the Node to which the iterator is anchored. NodeIterator.pointerBeforeReferenceNode Read only Returns a Boolean flag that indicates whether the NodeIterator is anchored before, the flag being true, or after, the flag being false, the anchor node. Methods This interface doesn't inherit any method. NodeIterator.detach
() This operation is a no-op. It doesn't do anything. Previously it was telling the engine that the NodeIterator was no more used, but this is now useless. NodeIterator.previousNode
() Returns the previous Node in the document, or null if there are none. NodeIterator.nextNode
() Returns the next Node in the document, or null if there are none. Specifications Specification Status ...
... Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'NodeIterator' in that specification. ...
...de in the document, or null if there are none. Specifications Specification Status Comment DOMThe definition of 'NodeIterator' in that specification. Living Standard Added the referenceNode and pointerBeforeReferenceNode properties. Removed the expandEntityReferences property. The method detach
() has been changed to be a no-op. The methods previousNode
() and nextNode
() don't raise an exception any more. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'NodeIterator' in that specification. Obsolete Initial definition. ...
Notifications API - Web APIs
The API is designed to be compatible with existing notification systems, across different platforms. Concepts and usage On supported platforms, showing a system notification generally involves two things. ...
...orms, showing a system notification generally involves two things. First, the user needs to grant the current origin permission to display system notifications, which is generally done when the app or site initialises, using the Notification.requestPermission
() method. This should be done in response to a user gesture, such as clicking a button, for example: btn.addEventListener('click', function
() { let promise = Notification.requestPermission
(); // wait for permission }) This is not only best practice -- you should not be spamming users with notifications they didn't agree to -- but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. Firefox is already doing this from version 72, for example. This will spawn a request dialog, al...
...es: From here the user can choose to allow notifications from this origin, or block them. Once a choice has been made, the setting will generally persist for the current session. Note: As of Firefox 44, the permissions for Notifications and Push have been merged. If permission is granted for notifications, push will also be enabled. Next, a new notification is created using the Notification
() constructor. This must be passed a title argument, and can optionally be passed an options object to specify options, such as text direction, body text, icon to display, notification sound to play, and more. In addition, the Notifications API spec specifies a number of additions to the ServiceWorker API, to allow service workers to fire notifications. Note: To find out more about using notific...
...spec specifies a number of additions to the ServiceWorker API, to allow service workers to fire notifications. Note: To find 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. Specification...
OES_vertex_array_object - Web APIs
The OES_vertex_array_object extension is part of the WebGL API and provides vertex array objects (VAOs) which encapsulate vertex array states. These objects keep pointers to vertex data and provide names for different sets of vertex data. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is only available to WebGL1 contexts. ...
...d. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default and the constants and methods are available without the "OES" suffix. ...
...ilable to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default and the constants and methods are available without the "OES" suffix. Constants This extension exposes one new constant, which can be used in the gl.getParameter
() method: ext.VERTEX_ARRAY_BINDING_OES Returns a WebGLVertexArrayObject object when used in the gl.getParameter
() method as the pname parameter. Methods This extension exposes four new methods. ext.createVertexArrayOES
() Creates a new WebGLVertexArrayObject. ext.deleteVertexArrayOES
() Deletes a given WebGLVertexArrayObject. ext.isVertexArrayOES
() Returns true if a given object is a WebGLVertexArrayObject. ext.bindVertexArrayOES
() Binds a given WebGLVertexArrayObject to the buffer. ...
...// calls to bindBuffer or vertexAttribPointer // which will be "recorded" in the VAO // ... ...
OscillatorNode - Web APIs
The OscillatorNode interface represents a periodic waveform, such as a sine wave. It is an AudioScheduledSourceNode audio-processing module that causes a specified frequency of a given wave to be created--in effect, a constant tone. An OscillatorNode is created using the BaseAudioContext.createOscillator
() method. It always has exactly one output and no inputs. ...
...aseAudioContext.createOscillator
() method. It always has exactly one output and no inputs. Its basic property defaults (see AudioNode for definitions) are: Number of inputs 0 Number of outputs 1 Channel count mode max Channel count 2 (not used in the default count mode) Channel interpretation speakers Constructor OscillatorNode
() Creates a new instance of an OscillatorNode object, optionally providing an object specifying default values for the node's properties. If the default values are acceptable, you can simply call the BaseAudioContext.createOscillator
() factory method. Properties Inherits properties from its parent, AudioScheduledSourceNode, and adds the following properties: OscillatorNode.frequency An a-r...
...nt waves will produce different tones. Standard values are "sine", "square", "sawtooth", "triangle" and "custom". The default is "sine". Event handlers OscillatorNode.onended Sets the event handler for the ended event, which fires when the tone has stopped playing. Methods Inherits methods from its parent, AudioScheduledSourceNode, and adds the following: OscillatorNode.setPeriodicWave
() Sets a PeriodicWave which describes a periodic waveform to be used instead of one of the standard waveforms; calling this sets the type to custom. This replaces the now-obsolete OscillatorNode.setWaveTable
() method. OscillatorNode.start
() Specifies the exact time to start playing the tone. OscillatorNode.stop
() Specifies the time to stop playing the tone. Examples The following example sh...
.... OscillatorNode.stop
() Specifies the time to stop playing the tone. Examples The following example shows basic usage of an AudioContext to create an oscillator node and to start playing a tone on it. For an applied example, check out our Violent Theremin demo (see app.js for relevant code). // create web audio api context var audioCtx = new (window.AudioContext || window.webkitAudioContext)
(); // create Oscillator node var oscillator = audioCtx.createOscillator
(); oscillator.type = 'square'; oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // value in hertz oscillator.connect(audioCtx.destination); oscillator.start
(); Specifications Specification Status Comment Web Audio APIThe definition of 'OscillatorNode' in that specification. Working ...
PaintWorklet.registerPaint - Web APIs
The PaintWorklet.registerPaint
() method of the PaintWorklet interface registers a class programmatically generate an image where a CSS property expects a file. Syntax registerPaint(name, class); Parameters name The name of the worklet class to register. class A reference to the class that implements the worklet. Return value undefined Exceptions TypeError Thrown when one of the arguments is invalid or missing. InvalidModificationError Thrown when the a worklet already exists with the specified name. Examples The following shows registering an example worklet module. This should be in a separate js file. Note that registerPaint
() is called without a reference to PaintWorklet. ...
...peError Thrown when one of the arguments is invalid or missing. InvalidModificationError Thrown when the a worklet already exists with the specified name. Examples The following shows registering an example worklet module. This should be in a separate js file. Note that registerPaint
() is called without a reference to PaintWorklet. The file itself is loaded through CSS.paintWorklet.addModule
() (documented here on the parent class of PaintWorklet, at Worklet.addModule
(). /* checkboardWorklet.js */ class CheckerboardPainter { paint(ctx, geom, properties) { // Use `ctx` as if it was a normal canvas const colors = ['red', 'green', 'blue']; const size = 32; for(let y = 0; y < geom.height/size; y++) { for(let x = 0; x < geom.width/size; x++) { const color = ...
... at Worklet.addModule
(). /* checkboardWorklet.js */ class CheckerboardPainter { paint(ctx, geom, properties) { // Use `ctx` as if it was a normal canvas const colors = ['red', 'green', 'blue']; const size = 32; for(let y = 0; y < geom.height/size; y++) { for(let x = 0; x < geom.width/size; x++) { const color = colors[(x + y) % colors.length]; ctx.beginPath
(); ctx.fillStyle = color; ctx.rect(x * size, y * size, size, size); ctx.fill
(); } } } } // Register our class under a specific name registerPaint('checkerboard', CheckerboardPainter); The first step in using a paintworket is defining the paint worklet using the registerPaint
() function, as done above. To use it, you register it with the CSS.paintWorklet.addModu...
... ctx.fillStyle = color; ctx.rect(x * size, y * size, size, size); ctx.fill
(); } } } } // Register our class under a specific name registerPaint('checkerboard', CheckerboardPainter); The first step in using a paintworket is defining the paint worklet using the registerPaint
() function, as done above. To use it, you register it with the CSS.paintWorklet.addModule
() method: <script> CSS.paintWorklet.addModule('checkboardWorklet.js'); </script> You can then use the paint
() CSS function in your CSS anywhere an <image> value is valid. li { background-image: paint(checkerboard); } Specifications Specification Status Comment CSS Painting API Level 1The definition of 'PaintWorklet.registerPaint' in that specification. Working ...
ParentNode - Web APIs
ldren of this ParentNode, omitting all of its non-element nodes. ParentNode.firstElementChild Read only Returns the first node which is both a child of this ParentNode and is also an Element, or null if there is none. ParentNode.lastElementChild Read only Returns the last node which is both a child of this ParentNode and is an Element, or null if there is none. ...
...d is also an Element, or null if there is none. ParentNode.lastElementChild Read only Returns the last node which is both a child of this ParentNode and is an Element, or null if there is none. Methods ParentNode.append
() Inserts a set of Node objects or DOMString objects after the last child of the ParentNode. DOMString objects are inserted as equivalent Text nodes. ParentNode.prepend
() Inserts a set of Node objects or DOMString objects before the first child of the ParentNode. DOMString objects are inserted as equivalent Text nodes. ...
... there is none. Methods ParentNode.append
() Inserts a set of Node objects or DOMString objects after the last child of the ParentNode. DOMString objects are inserted as equivalent Text nodes. ParentNode.prepend
() Inserts a set of Node objects or DOMString objects before the first child of the ParentNode. DOMString objects are inserted as equivalent Text nodes. ParentNode.querySelector
() Returns the first Element with the current element as root that matches the specified group of selectors. ParentNode.querySelectorAll
() Returns a NodeList representing a list of elements with the current element as root that matches the specified group of selectors. ParentNode.replaceChildren
() Replaces the existing children of a node with a specified new set of children. Specification ...
...pecification Status Comment DOMThe definition of 'ParentNode' in that specification. Living Standard Split the ElementTraversal interface into ChildNode and ParentNode. The ParentNode.firstElementChild, ParentNode.lastElementChild, and ParentNode.childElementCount properties are now defined on the latter. Added the ParentNode.children property, and the ParentNode.querySelector
(), ParentNode.querySelectorAll
(), ParentNode.append
(), and ParentNode.prepend
() methods. Element Traversal SpecificationThe definition of 'ElementTraversal' in that specification. Obsolete Added the initial definition of its properties to the ElementTraversal pure interface and used it on Element. ...
PaymentRequest: merchantvalidation event - Web APIs
payment handler. See Merchant validation in Payment processing concepts for details on how the merchant validation process works. Bubbles No Cancelable No Interface MerchantValidationEvent Event handler property onmerchantvalidation Examples In this example, an event handler is established for the merchantvalidation event. ...
... the fetch
() to send a request to its own server with an argument of the payment method's validation URL, obtained from the event's validationURL property. The merchant server should access the validation URL in accordance with the payment method documention. Typically, a client should not access the validation URL. ...
...on. Typically, a client should not access the validation URL. request.addEventListener("merchantvalidation", event => { event.complete(async
() => { const merchantServerUrl = window.location.origin + '/validate?url=' + encodeURIComponent(event.validationURL); // get validation data, and complete validation; return await fetch(merchantServerUrl).then(response => response.text
()); }, false); }; const response = await request.show
(); How merchant server handles the validation depends on the server implementation and payment method documentation. The content delivered by the validation server is forwarded to the merchant server and is then returned from the fetch
() call's fulfillment handler to the complete
() method on the event. This response lets the payment handler ...
...lidation server is forwarded to the merchant server and is then returned from the fetch
() call's fulfillment handler to the complete
() method on the event. This response lets the payment handler know if the merchant is validated. You can also use the onmerchantvalidation event handler property to set up the handler for this event: request.onmerchantvalidation = event => { event.complete(async
() => { const merchantServerUrl = window.location.origin + '/validate?url=' + encodeURIComponent(event.validationURL); // get validation data, and complete validation; return await fetch(merchantServerUrl).then(response => response.text
()); }); }; const response = await request.show
(); For more information, see Merchant Validation in Payment processing concepts. Related even...
PaymentResponse: payerdetailchange event - Web APIs
tailchange events are delivered by the Payment Request API to a PaymentResponse object when the user makes changes to their personal information while filling out a payment request form. The event handler for payerdetailchange should check each value in the form that has changed and ensure that the values are valid. If any are invalid, appropriate error messages should be configured and the retry
() method should be called on the PaymentResponse to ask the user to update the invalid entries. Bubbles No Cancelable No Interface PaymentRequestUpdateEvent Event handler property onpayerdetailchange Examples In the example below, onpayerdetailchange is used to set up a listener for the payerdetailchange event in order to validate the info...
... Bubbles No Cancelable No Interface PaymentRequestUpdateEvent Event handler property onpayerdetailchange Examples In the example below, onpayerdetailchange is used to set up a listener for the payerdetailchange event in order to validate the information entered by the user, requesting that any mistakes be corrected // Options for PaymentRequest
(), indicating that shipping address, // payer email address, name, and phone number all be collected. const options = { requestShipping: true, requestPayerEmail: true, requestPayerName: true, requestPayerPhone: true, }; const request = new PaymentRequest(methods, details, options); const response = request.show
(); // Get the data from the response let { payerName: oldPayerName, payer...
...} Specifications Specification Status Comment Pa...
...rrors); } else { // We have a good payment; send the data to the server await fetch("/pay-for-things/", { method: "POST", body: response.json
() }); response.complete("success"); } }; await response.retry({ payer: { email: "invalid domain.", phone: "invalid number.", }, }); addEventListener equivalent You could also set up the event handler using the addEventListener
() method: response.addEventListener("payerdetailchange", async ev => { ... } Specifications Specification Status Comment Payment Request APIThe definition of 'payerdetailchange event' in that specification. Candidate Recommendation ...
PerformanceEventTiming - Web APIs
eEventTiming.processingStart Returns the time at which event dispatch started. PerformanceEventTiming.processingEnd Returns the time at which the event dispatch ended. PerformanceEventTiming.cancelable Returns the associated event's cancelable attribute. PerformanceEventTiming.target Returns the associated event's last target, if it is not removed. ...
... event's cancelable attribute. PerformanceEventTiming.target Returns the associated event's last target, if it is not removed. Methods PerformanceEventTiming.toJSON
() Converts the PerformanceEventTiming object to JSON. Examples The following example shows how to use the API for all events: const observer = new PerformanceObserver(function(list) { const perfEntries = list.getEntries
().forEach(entry => { // Full duration const inputDuration = entry.duration; // Input delay (before processing event) const inputDelay = entry.processingStart - entry.startTime; // Synchronous event processing time (between start and end dispatch). const inputSyncProcessingTime = entry.processingEnd - entry.processingStart; }); }); // Register obse...
...tyState === 'hidden' ? 0 : Infinity; document.addEventListener('visibilitychange', (event) => { firstHiddenTime = Math.min(firstHiddenTime, event.timeStamp); }, {once: true}); // Sends the passed data to an analytics endpoint. This code // uses `/analytics`; you can replace it with your own URL. function sendToAnalytics(data) { const body = JSON.stringify(data); // Use `navigator.sendBeacon
()` if available, falling back to `fetch
()`. (navigator.sendBeacon && navigator.sendBeacon('/analytics', body)) || fetch('/analytics', {body, method: 'POST', keepalive: true}); } // Use a try/catch instead of feature detecting `first-input` // support, since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { function onFirstInputE...
...// page is loaded in a background tab. if (entry.startTime < firstHiddenTime) { const fid = entry.processingStart - entry.startTime; // Report the FID value to an analytics endpoint. sendToAnalytics({fid}); } } // Create a PerformanceObserver that calls `onFirstInputEntry` for each entry. const po = new PerformanceObserver((entryList) => { entryList.getEntries
().forEach(onFirstInputEntry); }); // Observe entries of type `first-input`, including buffered entries, // i.e. entries that occurred before calling `observe
()` below. po.observe({ type: 'first-input', buffered: true, }); } catch (e) { // Do nothing if the browser doesn't support this API. } Specifications Specification Status Comment UnknownThe defin...
PointerEvent - Web APIs
-enable surface). The pointer can target a specific coordinate (or set of coordinates) on the contact surface such as a screen. A pointer's hit test is the process a browser uses to determine the target element for a pointer event. Typically, this is determined by considering the pointer's location and also the visual layout of elements in a document on screen media. Constructors PointerEvent
() Creates a synthetic--and untrusted--PointerEvent. Properties This interface inherits properties from MouseEvent and Event. PointerEvent.pointerId Read only A unique identifier for the pointer causing the event. PointerEvent.width Read only The width (magnitude on the X axis), in CSS pixels, of the contact geometry of the pointer. PointerEvent.height Read only The height (magnitude ...
...y The clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range 0 to 359. PointerEvent.pointerType Read only Indicates the device type that caused the event (mouse, pen, touch, etc.) PointerEvent.isPrimary Read only Indicates if the pointer represents the primary pointer of this pointer type. Methods PointerEvent.getCoalescedEvents
() Returns a sequence of all PointerEvent instances that were coalesced into the dispatched pointermove event. PointerEvent.getPredictedEvents
() Returns a sequence of PointerEvent instances that the browser predicts will follow the dispatched pointermove event's coalesced events. Pointer event types The PointerEvent interface has several event types. To determine which event fired, look at...
...rmove event's coalesced events. Pointer event types The PointerEvent interface has several event types. To determine which event fired, look at the event's type property. Note: It's important to note that in many cases, both pointer and mouse events get sent (in order to let non-pointer-specific code still interact with the user). If you use pointer events, you should call event.preventDefault
() to keep the mouse event from being sent as well. pointerover This event is fired when a pointing device is moved into an element's hit test boundaries. pointerenter This event is fired when a pointing device is moved into the hit test boundaries of an element or one of its descendants, including as a result of a pointerdown event from a device that does not support hover (see pointerdown). ...
...lers.onpointerleave A global event handler for the pointerleave event. Example Examples of each property, event type, and global event handler are included in their respective reference pages. Specifications Specification Status Comment Pointer Events - Level 3The definition of 'PointerEvent' in that specification. Editor's Draft Added the getCoalescedEvents
() and getPredictedEvents
() methods and pointerrawupdate event. Pointer Events - Level 2The definition of 'PointerEvent' in that specification. Recommendation Added the twist and tangentialPressure properties. Pointer EventsThe definition of 'PointerEvent' in that specification. Obsolete Initial definition. ...
PushEvent - Web APIs
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. ...
...shSubscription. Methods Inherits methods from its parent, ExtendableEvent. Examples The following example takes data from a PushEvent and displays it on all of the service worker's clients. ...
... Working Draft Initial definition. ...
... Full support 17Firefox ...
PushMessageData - Web APIs
like the similar methods in the Fetch API, which only allow the method to be invoked once, these methods can be called multiple times. Messages received through the Push API are sent encrypted by push services and then automatically decrypted by browsers before they are made accessible through the methods of the PushMessageData interface. Properties None. ...
...d to be invoked once, these methods can be called multiple times. Messages received through the Push API are sent encrypted by push services and then automatically decrypted by browsers before they are made accessible through the methods of the PushMessageData interface. Properties None. Methods PushMessageData.arrayBuffer
() Extracts the data as an ArrayBuffer object. PushMessageData.blob
() Extracts the data as a Blob object. ...
...mes. Messages received through the Push API are sent encrypted by push services and then automatically decrypted by browsers before they are made accessible through the methods of the PushMessageData interface. Properties None. Methods PushMessageData.arrayBuffer
() Extracts the data as an ArrayBuffer object. PushMessageData.blob
() Extracts the data as a Blob object. PushMessageData.json
() Extracts the data as a JSON object. PushMessageData.text
() Extracts the data as a plain text string. ...
...geData interface. Properties None. Methods PushMessageData.arrayBuffer
() Extracts the data as an ArrayBuffer object. PushMessageData.blob
() Extracts the data as a Blob object. PushMessageData.json
() Extracts the data as a JSON object. PushMessageData.text
() Extracts the data as a plain text string. Examples self.addEventListener('push', function(event) { var obj = event.data.json
(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { fireNotification(obj, event); port.postMessage(obj); } else if(obj.action === 'init' || obj.action === 'chatMsg') { port.postMessage(obj); } }); Specifications Specification Status Comment Push APIThe definition of 'PushMessageData' in that specification. Working Draft Initial defi...
PushSubscription - Web APIs
ighResTimeStamp of the subscription expiration time associated with the push subscription, if there is one, or null otherwise. PushSubscription.options Read only An object containing the options used to create the subscription. PushSubscription.subscriptionId Read only A DOMString containing the subscription ID associated with the push subscription. ...
... object containing the options used to create the subscription. PushSubscription.subscriptionId Read only A DOMString containing the subscription ID associated with the push subscription. Methods PushSubscription.getKey
() Returns an ArrayBuffer which contains the client's public key, which can then be sent to a server and used in encrypting push message data. PushSubscription.toJSON
() Standard serializer -- returns a JSON representation of the subscription properties. ...
...MString containing the subscription ID associated with the push subscription. Methods PushSubscription.getKey
() Returns an ArrayBuffer which contains the client's public key, which can then be sent to a server and used in encrypting push message data. PushSubscription.toJSON
() Standard serializer -- returns a JSON representation of the subscription properties. PushSubscription.unsubscribe
() Starts the asynchronous process of unsubscribing from the push service, returning a Promise that resolves to a Boolean when the current subscription is successfully unregistered. ...
...JSON
() Standard serializer -- returns a JSON representation of the subscription properties. PushSubscription.unsubscribe
() Starts the asynchronous process of unsubscribing from the push service, returning a Promise that resolves to a Boolean when the current subscription is successfully unregistered. Example navigator.serviceWorker.ready.then(function(reg) { reg.pushManager.getSubscription
().then(function(subscription) { subscription.unsubscribe
().then(function(successful) { // You've successfully unsubscribed }).catch(function(e) { // Unsubscription failed }) }) }); Specifications Specification Status Comment Push APIThe definition of 'PushSubscription' in that specification. Working Draft Initial definition ...
RTCOfferOptions.iceRestart - Web APIs
The iceRestart property of the RTCOfferOptions dictionary is a Boolean value which, when true, tells the RTCPeerConnection to start ICE renegotiation. Note: Rather than manually creating and submitting an offer with iceRestart set to true, you should consider calling the RTCPeerConnection method restartIce
() instead. Syntax var options = { iceRestart: trueOrFalse }; Value A Boolean value indicating whether or not the RTCPeerConnection should generate new values for the connection's ice-ufrag and ice-pwd values, which will trigger ICE renegotiation on the next message sent to the remote peer. Usage notes When the RTCPeerConnection object's ICE connection state changes to failed, you should try to trigger an ICE restart. You should ideally do this by calling the RTCPeerConnection'...
...hether or not the RTCPeerConnection should generate new values for the connection's ice-ufrag and ice-pwd values, which will trigger ICE renegotiation on the next message sent to the remote peer. Usage notes When the RTCPeerConnection object's ICE connection state changes to failed, you should try to trigger an ICE restart. You should ideally do this by calling the RTCPeerConnection's restartIce
() method, if it's available. Fundamentally, this renegotiation is triggered by generating and using new values for the ICE username fragment ("ufrag")}} Example This example shows a handler for the iceconnectionstatechange event. It watches for the ICE connection state to transition to "failed", which indicates that an ICE restart should be tried in order to attempt to bring the connection back ...
...("ufrag")}} Example This example shows a handler for the iceconnectionstatechange event. It watches for the ICE connection state to transition to "failed", which indicates that an ICE restart should be tried in order to attempt to bring the connection back up. pc.oniceconnectionstatechange = function(evt) { if (pc.iceConnectionState === "failed") { if (pc.restartIce) { pc.restartIce
(); } else { pc.createOffer({ iceRestart: true }) .then(pc.setLocalDescription) .then(sendOfferToServer); } } } If the state changes to failed, this handler starts by looking to see if the RTCPeerConnection includes the restartIce
() method; if it does, we call that to request an ICE restart. Otherwise, we call back to the older technique: we manually create a new offer ...
... by looking to see if the RTCPeerConnection includes the restartIce
() method; if it does, we call that to request an ICE restart. Otherwise, we call back to the older technique: we manually create a new offer with iceRestart set to true, then that offer is set as the new local description for the connection. After that, the offer is sent to the server by calling a custom function sendOfferToServer
(). Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCOfferOptions.iceRestart' in that specification. Candidate Recommendation Initial definition. ...
RTCPeerConnection.canTrickleIceCandidates - Web APIs
The read-only RTCPeerConnection property canTrickleIceCandidates returns a Boolean which indicates whether or not the remote peer can accept trickled ICE candidates. ICE trickling is the process of continuing to send candidates after the initial offer or answer has already been sent to the other peer. This property is only set after having called RTCPeerConnection.setRemoteDescription
(). Ideally, your signaling protocol provides a way to detect trickling support, so that you don't need to rely on this property. A WebRTC browser will always support trickle ICE. If trickling isn't supported, or you aren't able to tell, you can check for a falsy value for this property and then wait until the value of iceGatheringState changes to "completed" before creating and sending the initial offer. Th...
... way, the offer contains all of the candidates. Syntax var canTrickle = RTCPeerConnection.canTrickleIceCandidates; Value A Boolean that is true if the remote peer can accept trickled ICE candidates and false if it cannot. If no remote peer has been established, this value is null. ...
...ccept trickled ICE candidates and false if it cannot. If no remote peer has been established, this value is null. Note: This property's value is determined once the local peer has called RTCPeerConnection.setRemoteDescription
(); the provided description is used by the ICE agent to determine whether or not the remote peer supports trickled ICE candidates. Example var pc = new RTCPeerConnection
(); // The following code might be used to handle an offer from a peer when // it isn't known whether it supports trickle ICE. ...
...PeerConnection.setRemoteDescription
(); the provided description is used by the ICE agent to determine whether or not the remote peer supports trickled ICE candidates. Example var pc = new RTCPeerConnection
(); // The following code might be used to handle an offer from a peer when // it isn't known whether it supports trickle ICE. ...
RTCPeerConnection: icecandidate event - Web APIs
The event handler should transmit the candidate to the remote peer over the signaling channel so the remote peer can add it to its set of remote candidates. Bubbles No Cancelable No Interface RTCPeerConnectionIceEvent Event handler property RTCPeerConnection.onicecandidate Description There are three reasons why the icecandidate event is fired on an RTCPeerConnection. ...
...ivered to the remote peer over the signaling channel your code manages. rtcPeerConnection.onicecandidate = (event) => { if (event.candidate) { sendCandidateToRemotePeer(event.candidate) } else { /* there are no more candidates coming during this negotiation */ } } The remote peer, upon receiving the candidate, will add the candidate to its candidate pool by calling addIceCandidate
(), passing in the candidate string you have passed along using the signaling server. Indicating the end of a generation of candidates When an ICE negotiation session runs out of candidates to propose for a given RTCIceTransport, it has completed gathering for a generation of candidates. That this has occurred is indicated by an icecandidate event whose candidate string is empty (""). You should ...
...he value of the RTCPeerConnection property iceGatheringState has been updated. If that value is now complete, you know that ICE gathering has just ended. This is a more reliable approach than looking at the individual ICE messages for one indicating that the ICE session is finished. ...
...hat ICE gathering has just ended. This is a more reliable approach than looking at the individual ICE messages for one indicating that the ICE session is finished. Examples This example creates a simple handler for the icecandidate event that uses a function called sendMessage
() to create and send a reply to the remote peer through the signaling server. ...
RTCPeerConnection.signalingState - Web APIs
e to verify that your code is in the expected state when messages arrive can help avoid unexpected and avoidable failures. For example, if you receive an answer while the signalingState isn't "have-local-offer", you know that something is wrong, since you should only receive answers after creating an offer but before an answer has been received and passed into RTCPeerConnection.setLocalDescription
(). Your code will be more reliable if you watch for mismatched states like this and handle them gracefully. This value may also be useful during debugging, for example. In addition, when the value of this property changes, a signalingstatechange event is sent to the RTCPeerConnection instance. Syntax var state = RTCPeerConnection.signalingState; Value The allowed values are those included in...
...cription "stable" There is no ongoing exchange of offer and answer underway. This may mean that the RTCPeerConnection object is new, in which case both the localDescription and remoteDescription are null; it may also mean that negotiation is complete and a connection has been established. "have-local-offer" The local peer has called RTCPeerConnection.setLocalDescription
(), passing in SDP representing an offer (usually created by calling RTCPeerConnection.createOffer
()), and the offer has been applied successfully. "have-remote-offer" The remote peer has created an offer and used the signaling server to deliver it to the local peer, which has set the offer as the remote description by calling RTCPeerConnection.setRemoteDescription
(). "have-loca...
... "have-remote-offer" The remote peer has created an offer and used the signaling server to deliver it to the local peer, which has set the offer as the remote description by calling RTCPeerConnection.setRemoteDescription
(). "have-local-pranswer" The offer sent by the remote peer has been applied and an answer has been created (usually by calling RTCPeerConnection.createAnswer
()) and applied by calling RTCPeerConnection.setLocalDescription
(). This provisional answer describes the supported media formats and so forth, but may not have a complete set of ICE candidates included. Further candidates will be delivered separately later. "have-remote-pranswer" A provisional answer has been received and successfully applied in response to an offer previously sent and ...
... "closed" The connection is closed. Note: This value moved into the RTCPeerConnectionState enum in the May 13, 2016 draft of the specification, as it reflects the state of the RTCPeerConnection, not the signaling connection. You now detect a closed connection by checking for connectionState to be "closed" instead. ...
RTCRtpReceiver - Web APIs
urrent RTCRtpReceiver instance. RTCRtpReceiver.transport Read only Returns the RTCDtlsTransport instance over which the media for the receiver's track is received. Obsolete properties rtcpTransport This property has been removed; the RTP and RTCP transports have been combined into a single transport. Use the transport property instead. ...
... This property has been removed; the RTP and RTCP transports have been combined into a single transport. Use the transport property instead. Methods RTCRtpReceiver.getContributingSources
() Returns an array of RTCRtpContributingSource instances for each unique CSRC (contributing source) identifier received by the current RTCRtpReceiver in the last ten seconds. RTCRtpReceiver.getParameters
() Returns an RTCRtpParameters object which contains information about how the RTC data is to be decoded. ...
...ty instead. Methods RTCRtpReceiver.getContributingSources
() Returns an array of RTCRtpContributingSource instances for each unique CSRC (contributing source) identifier received by the current RTCRtpReceiver in the last ten seconds. RTCRtpReceiver.getParameters
() Returns an RTCRtpParameters object which contains information about how the RTC data is to be decoded. RTCRtpReceiver.getStats
() Returns a Promise whose fulfillment handler receives a RTCStatsReport which contains statistics about the incoming streams and their dependencies. RTCRtpReceiver.getSynchronizationSources
() Returns an array including one RTCRtpSynchronizationSource instance for each unique SSRC (synchronization source) identifier received by the current RTCRtpReceiver in the last ten seconds. Static methods...
...ent handler receives a RTCStatsReport which contains statistics about the incoming streams and their dependencies. RTCRtpReceiver.getSynchronizationSources
() Returns an array including one RTCRtpSynchronizationSource instance for each unique SSRC (synchronization source) identifier received by the current RTCRtpReceiver in the last ten seconds. Static methods RTCRtpReceiver.getCapabilities
() Returns the most optimistic view of the capabilities of the system for receiving media of the given kind. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpReceiver' in that specification. Candidate Recommendation Initial definition. ...
RTCRtpSender - Web APIs
ssion of media and control data. This value is null until the transport is established. When bundling is in use, more than transceiver may be sharing the same transport object. Obsolete properties rtcpTransport This property has been removed; the RTP and RTCP transports have been combined into a single transport. Use the transport property instead. ...
...same transport object. Obsolete properties rtcpTransport This property has been removed; the RTP and RTCP transports have been combined into a single transport. Use the transport property instead. Methods RTCRtpSender.getParameters
() Returns a RTCRtpParameters object describing the current configuration for the encoding and transmission of media on the track. RTCRtpSender.getStats
() Returns a Promise which is fulfilled with a RTCStatsReport which provides statistics data for all outbound streams being sent using this RTCRtpSender. ...
...port property instead. Methods RTCRtpSender.getParameters
() Returns a RTCRtpParameters object describing the current configuration for the encoding and transmission of media on the track. RTCRtpSender.getStats
() Returns a Promise which is fulfilled with a RTCStatsReport which provides statistics data for all outbound streams being sent using this RTCRtpSender. RTCRtpSender.setParameters
() Applies changes to parameters which configure how the track is encoded and transmitted to the remote peer. RTCRtpSender.setStreams
() Sets the MediaStream(s) associated with the track being transmitted by this sender. RTCRtpSender.replaceTrack
() Attempts to replace the track currently being sent by the RTCRtpSender with another track, without performing renegotiation. This method can be used,...
... Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpSender' in that specification. ...
RTCSessionDescriptionCallback - Web APIs
Syntax RTCSessionDescriptionCallback(description); Parameters description An RTCSessionDescriptionInit (or RTCSessionDescription) object describing the session being offered or being accepted. ...
... Syntax RTCSessionDescriptionCallback(description); Parameters description An RTCSessionDescriptionInit (or RTCSessionDescription) object describing the session being offered or being accepted. ...
... Syntax RTCSessionDescriptionCallback(description); Parameters description An RTCSessionDescriptionInit (or RTCSessionDescription) object describing the session being offered or being accepted. ...
...tionCallback(description); Parameters description An RTCSessionDescriptionInit (or RTCSessionDescription) object describing the session being offered or being accepted. This object contains the type and sdp properties which are part of RTCSessionDescription. Return value The callback doesn't need to return anything, so the return value is undefined. Example var pc = new RTCPeerConnection
(); var descriptionCallback = function(offer) { pc.setLocalDescription(offer); } pc.createOffer(descriptionCallback); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCSessionDescriptionCallback' in that specification. Candidate Recommendation Initial definition. ...
Report - Web APIs
This contains the list of reports currently contained in the observer's report queue. By sending requests to the endpoints defined via the Report-To HTTP header. ...
...This contains the list of reports currently contained in the observer's report queue. By sending requests to the endpoints defined via the Report-To HTTP header. ...
... This interface has no methods defined on it. Events This interface has no events that fire on it. ...
... deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { reportBtn.onclick =
() => displayReports(reports); }, options); We then tell it to start observing reports using ReportingObserver.observe
(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe
(); Because of the event handler we set up inside the ReportingObserver
() constructor, we can now click the button to display the report details. The report details are displayed via the displayReports
() fuction, which takes the observer c...
ReportingObserver - Web APIs
The ReportingObserver interface of the Reporting API allows you to collect and access reports. Constructor ReportingObserver
() Creates a new ReportingObserver object instance, which can be used to collect and access reports. Properties This interface has no properties defined on it. Methods ReportingObserver.disconnect
() Stops a reporting observer that had previously started observing from collecting reports. ReportingObserver.observe
() Instructs a reporting observer to start collecting reports in its report queue. ReportingObserver.takeRecords
() Returns the current list of reports contained in the observer's report queue, and empties the queue. Events This interface has no events that fire on it. Examples In our deprecation_report.html example, we create a s...
...server's report queue, and empties the queue. Events This interface has no events that fire on it. ...
... deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { reportBtn.onclick =
() => displayReports(reports); }, options); We then tell it to start observing reports using ReportingObserver.observe
(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe
(); Later on in the example we deliberately use the deprecated version of MediaDevices.getUserMedia
(): if(navigator.mozGetUserMedia) { navigator.mozGetUserMedia( constraints, success, failure); } else { navigator.getUserMedia...
...r on in the example we deliberately use the deprecated version of MediaDevices.getUserMedia
(): if(navigator.mozGetUserMedia) { navigator.mozGetUserMedia( constraints, success, failure); } else { navigator.getUserMedia( constraints, success, failure); } This causes a deprecation report to be generated; because of the event handler we set up inside the ReportingObserver
() constructor, we can now click the button to display the report details. Note: If you look at the complete source code, you'll notice that we actually call the deprecated getUserMedia
() method twice. After the first time we call ReportingObserver.takeRecords
(), which returns the first generated report and empties the queue. Because of this, when the button is pressed only the second report is ...
Response.redirected - Web APIs
See the example Disallowing redirects, which shows this being done. ...
...tion. Note, however, that this isn't as safe as outright rejecting redirects if they're unexpected, as described under Disallowing redirects below. ...
... ...
... Living Standard Initial definition ...
SVGCircleElement - Web APIs
y This property defines the radius of the <circle> element. It is denoted by the r of the element. Methods This interface has no methods but inherits methods from its parent, SVGGeometryElement. ...
...t. It is denoted by the r of the element. Methods This interface has no methods but inherits methods from its parent, SVGGeometryElement. Example SVG content <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 250 250" width="250" height="250"> <circle cx="100" cy="100" r="50" fill="gold" id="circle" onclick="clickCircle
();"/> </svg> JavaScript content This function clickCircle
() is called when the circle is clicked. ...
...tryElement. Example SVG content <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 250 250" width="250" height="250"> <circle cx="100" cy="100" r="50" fill="gold" id="circle" onclick="clickCircle
();"/> </svg> JavaScript content This function clickCircle
() is called when the circle is clicked. It randomly increases or decreases the radius of the circle element. ...
...="50" fill="gold" id="circle" onclick="clickCircle
();"/> </svg> JavaScript content This function clickCircle
() is called when the circle is clicked. It randomly increases or decreases the radius of the circle element. function clickCircle
() { var circle = document.getElementById("circle"); // Randomly determine if the circle radius will increase or decrease var change = Math.random
() > 0.5 ? 10 : -10; // Clamp the circle radius to a minimum of 10 and a maximum of 250, // so it won't disappear or get bigger than the viewport var newValue = Math.min(Math.max(circle.r.baseVal.value + change, 10), 250); circle.setAttribute("r", newValue); } Click on the circle. Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The de...
SVGGeometryElement - Web APIs
In SVG 2 they were moved to this interface. Properties This interface also inherits properties from its parent, SVGGraphicsElement. SVGGeometryElement.pathLength Read only This property reflects the pathLength attribute. Methods This interface also inherits methods from its parent, SVGGraphicsElement. ...
...In SVG 2 they were moved to this interface. Properties This interface also inherits properties from its parent, SVGGraphicsElement. SVGGeometryElement.pathLength Read only This property reflects the pathLength attribute. Methods This interface also inherits methods from its parent, SVGGraphicsElement. SVGGeometryElement.i...
...e originally part of the SVGPathElement interface. In SVG 2 they were moved to this interface. Properties This interface also inherits properties from its parent, SVGGraphicsElement. SVGGeometryElement.pathLength Read only This property reflects the pathLength attribute. Methods This interface also inherits methods from its parent, SVGGraphicsElement. SVGGeometryElement.isPointInFill
() Determines whether a given point is within the fill shape of an element. Normal hit testing rules apply; the value of the pointer-events property on the element determines whether a point is considered to be within the fill. SVGGeometryElement.isPointInStroke
() Determines whether a given point is within the stroke shape of an element. Normal hit testing rules apply; the value of the pointer-ev...
...er-events property on the element determines whether a point is considered to be within the fill. SVGGeometryElement.isPointInStroke
() Determines whether a given point is within the stroke shape of an element. Normal hit testing rules apply; the value of the pointer-events property on the element determines whether a point is considered to be within the stroke. SVGGeometryElement.getTotalLength
() Returns the user agent's computed value for the total length of the path in user units. SVGGeometryElement.getPointAtLength
() Returns the point at a given distance along the path. Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGGeometryElement' in that specification. Candidate Recommendation Initial definition ...
Using server-sent events - Web APIs
t.createElement("li"); const eventList = document.getElementById("list"); newElement.innerHTML = "message: " + event.data; eventList.appendChild(newElement); } This code listens for incoming messages (that is, notices from the server that do not have an event field on them) and appends the message text to a list in the document's HTML. ...
...am"); $counter = rand(1, 10); while (true) { // Every second, send a "ping" event. echo "event: ping\n"; $curDate = date(DATE_ISO8601); echo 'data: {"time": "' . $curDate . '"}'; echo "\n\n"; // Send a simple message at random intervals. $counter--; if (!$counter) { echo 'data: This is a message at time ' . $curDate . "\n\n"; $counter = rand(1, 10); } ob_end_flush
(); flush
(); sleep(1); } The code above generates an event every second, with the event type "ping". Each event's data is a JSON object containing the ISO 8601 timestamp corresponding to the time at which the event was generated. At random intervals, a simple message (with no event type) is sent. Note: You can find a full example that uses the code shown in this article on GitHub -- see Simp...
... control), an error event is generated. You can take action on this programmatically by implementing the onerror callback on the EventSource object: evtSource.onerror = function(err) { console.error("EventSource failed:", err); }; Closing event streams By default, if the connection between the client and server closes, the connection is restarted. The connection is terminated with the .close
() method. evtSource.close
(); Event stream format The event stream is a simple stream of text data which must be encoded using UTF-8. Messages in the event stream are separated by a pair of newline characters. A colon as the first character of a line is in essence a comment, and is ignored. Note: The comment line can be used to prevent connections from timing out; a server can send a comment per...
...the field name, followed by a colon, followed by the text data for that field's value. Fields Each message received has some combination of the following fields, one per line: event A string identifying the type of event described. If this is specified, an event will be dispatched on the browser to the listener for the specified event name; the website source code should use addEventListener
() to listen for named events. The onmessage handler is called if no event name is specified for a message. data The data field for the message. When the EventSource receives multiple consecutive lines that begin with data:, it concatenates them, inserting a newline character between each one. Trailing newlines are removed. id The event ID to set the EventSource object's last event ID value. re...
ServiceWorkerContainer - Web APIs
The ServiceWorkerContainer interface of the Service Worker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations. Most importantly, it exposes the ServiceWorkerContainer.register
() method used to register service workers, and the ServiceWorkerContainer.controller property used to determine whether or not the current page is actively controlled. Properties ServiceWorkerContainer.controller Read only Returns a ServiceWorker object if its state is activated (the same object returned by ServiceWorkerRegistration.active). This property returns null during a force-refresh request (Shift + refresh) or if there ...
...ted ServiceWorkerRegistration acquires a new active worker. Also available via the ServiceWorkerContainer.oncontrollerchange property. error Fired whenever an error occurs in the associated service workers. Also available via the ServiceWorkerContainer.onerror property. message Occurs when incoming messages are received by the ServiceWorkerContainer object (e.g. via a MessagePort.postMessage
() call.) Also available via the ServiceWorkerContainer.onmessage property. Methods ServiceWorkerContainer.register
() Creates or 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...
...nmessage 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
() explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via Client.postMessage
()). This can be used to react t...
...ntroller changes. // First, do a one-off check if there's currently a // service worker in control. if (navigator.serviceWorker.controller) { console.log('This page is currently controlled by:', navigator.serviceWorker.controller); } // Then, register a handler to detect when a new or // updated service worker takes control. navigator.serviceWorker.oncontrollerchange = function
() { console.log('This page is now controlled by:', navigator.serviceWorker.controller); }; } else { console.log('Service workers are not supported.'); } Specifications Specification Status Comment Service WorkersThe definition of 'ServiceWorkerContainer' in that specification. Working Draft Initial definition. ...
ServiceWorkerGlobalScope: notificationclick event - Web APIs
The notificationclick event is fired to indicate that a system notification spawned by ServiceWorkerRegistration.showNotification
() has been clicked. ...
...n
() has been clicked. ...
...ion click: ', event.notification.tag); event.notification.close
(); // This looks to see if the current is already open and // focuses if it is event.waitUntil(clients.matchAll({ type: "window" }).then(function(clientList) { for (var i = 0; i < clientList.length; i++) { var client = clientList[i]; if (client.url == '/' && 'focus' in client) return client.focus
(); } if (clients.openWindow) return clients.openWindow('/'); })); }); Or use the onnotificationclick event handler property: self.onnotificationclick = function(event) { console.log('On notification click: ', event.notification.tag); event.notification.close
(); // This looks to see if the current is already open and // focuses if it is event.waitUntil(clients.matchAll(...
... Living Standard ...
SpeechSynthesis: voiceschanged event - Web APIs
The voiceschanged event of the Web Speech API is fired when the list of SpeechSynthesisVoice objects that would be returned by the SpeechSynthesis.getVoices
() method has changed (when the voiceschanged event fires.) Bubbles No Cancelable No Interface Event Event handler property onvoiceschanged Examples This could be used to repopulate a list of voices that the user can choose between when the event fires. ...
... Bubbles No Cancelable No Interface Event Event handler property onvoiceschanged Examples This could be used to repopulate a list of voices that the user can choose between when the event fires. ...
...able No Interface Event Event handler property onvoiceschanged Examples This could be used to repopulate a list of voices that the user can choose between when the event fires. ...
... for(i = 0; i < voices.length ; i++) { var option = document.createElement('option'); option.textContent = voices[i].name + ' (' + voices[i].lang + ')'; option.setAttribute('data-lang', voices[i].lang); option.setAttribute('data-name', voices[i].name); voiceSelect.appendChild(option); } }); Or use the onvoiceschanged event handler property: synth.onvoiceschanged = function
() { var voices = synth.getVoices
(); for(i = 0; i < voices.length ; i++) { var option = document.createElement('option'); option.textContent = voices[i].name + ' (' + voices[i].lang + ')'; option.setAttribute('data-lang', voices[i].lang); option.setAttribute('data-name', voices[i].name); voiceSelect.appendChild(option); } } Specifications Specification Status...
SpeechSynthesisUtterance.onerror - Web APIs
The onerror property of the SpeechSynthesisUtterance interface represents an event handler that will run when an error occurs that prevents the utterance from being succesfully spoken (when the error event fires.) Syntax speechSynthesisUtteranceInstance.onerror = function
() { ... ...
... error occurs that prevents the utterance from being succesfully spoken (when the error event fires.) Syntax speechSynthesisUtteranceInstance.onerror = function
() { ... }; Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices
(); ... ...
...when the error event fires.) Syntax speechSynthesisUtteranceInstance.onerror = function
() { ... }; Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices
(); ... ...
... Draft ...
SpeechSynthesisUtterance.onresume - Web APIs
The onresume property of the SpeechSynthesisUtterance interface represents an event handler that will run when a paused utterance is resumed (when the resume event fires.) This occurs when the SpeechSynthesis.resume
() method is invoked on a paused speech synthesis instance. Syntax speechSynthesisUtteranceInstance.onresume = function
() { ... ...
...is occurs when the SpeechSynthesis.resume
() method is invoked on a paused speech synthesis instance. Syntax speechSynthesisUtteranceInstance.onresume = function
() { ... }; Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices
(); ... ...
... speech synthesis instance. Syntax speechSynthesisUtteranceInstance.onresume = function
() { ... }; Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices
(); ... ...
... Draft ...
SpeechSynthesisVoice - Web APIs
zer service (true), or a remote speech synthesizer service (false.) SpeechSynthesisVoice.name Read only Returns a human-readable name that represents the voice. SpeechSynthesisVoice.voiceURI Read only Returns the type of URI and location of the speech synthesis service for this voice. Examples The following snippet is excerpted from our Speech synthesiser demo. ...
... speech synthesizer service (false.) SpeechSynthesisVoice.name Read only Returns a human-readable name that represents the voice. SpeechSynthesisVoice.voiceURI Read only Returns the type of URI and location of the speech synthesis service for this voice. Examples The following snippet is excerpted from our Speech synthesiser demo. ...
...0; i < voices.length ; i++) { var option = document.createElement('option'); option.textContent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textContent += ' -- DEFAULT'; } option.setAttribute('data-lang', voices[i].lang); option.setAttribute('data-name', voices[i].name); voiceSelect.appendChild(option); } } populateVoiceList
(); if (speechSynthesis.onvoiceschanged !== undefined) { speechSynthesis.onvoiceschanged = populateVoiceList; } inputForm.onsubmit = function(event) { event.preventDefault
(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedOp...
... Draft ...
StereoPannerNode - Web APIs
ue between -1 (full left pan) and 1 (full right pan). This interface was introduced as a much simpler way to apply a simple panning effect than having to use a full PannerNode. Number of inputs 1 Number of outputs 1 Channel count mode "clamped-max" Channel count 2 Channel interpretation "speakers" Constructor StereoPannerNode
() Creates a new instance of a StereoPannerNode object. Properties Inherits properties from its parent, AudioNode. StereoPannerNode.pan Read only Is an a-rate AudioParam representing the amount of panning to apply. Methods No specific method; inherits methods from its parent, AudioNode. Example In our StereoPannerNode example (see source code) HTML we have a simple <audio> element alon...
...g the amount of panning to apply. Methods No specific method; inherits methods from its parent, AudioNode. Example In our StereoPannerNode example (see source code) HTML we have a simple <audio> element along with a slider <input> to increase and decrease pan value. ...
...ther using the connect
() method. We then use an oninput event handler to change the value of the StereoPannerNode.pan parameter and update the pan value display when the slider is moved. Moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. ...
...Audio = document.querySelector('audio'); var panControl = document.querySelector('.panning-control'); var panValue = document.querySelector('.panning-value'); pre.innerHTML = myScript.innerHTML; // Create a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it var source = audioCtx.createMediaElementSource(myAudio); // Create a stereo panner var panNode = audioCtx.createStereoPanner
(); // Event handler function to increase panning to the right and left // when the slider is moved panControl.oninput = function
() { panNode.pan.setValueAtTime(panControl.value, audioCtx.currentTime); panValue.innerHTML = panControl.value; } // connect the MediaElementAudioSourceNode to the panNode // and the panNode to the destination, so we can play the // music and adjust the panning usin...
Using the Storage Access API - Web APIs
e-origin to allow it to call the API, and execute in an origin that can have cookies: <iframe sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"> ... </iframe> Now on to the code executed inside the embedded document. Since it does not know whether it currently has access to storage, it should first call Document.hasStorageAccess
(). ...
...ookies: <iframe sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"> ... </iframe> Now on to the code executed inside the embedded document. Since it does not know whether it currently has access to storage, it should first call Document.hasStorageAccess
(). ...
...executed inside the embedded document. Since it does not know whether it currently has access to storage, it should first call Document.hasStorageAccess
(). If that call returns false, we can then call Document.requestStorageAccess
(), returning the result so that then we can chain it onto the previous promise call. In the final then, we'll have first-party storage access. document.hasStorageAccess
().then(hasAccess => { if (!hasAccess) { return document.requestStorageAccess
(); } }).then(_ => { // Now we have first-party storage access! // Let's access some items from the first-party cookie jar document.cookie = "foo=bar"; // set a cookie localStorage.setItem("username", "John"); // access a localStorage entry }).catch(_ => { // error obtaining storage access. }...
...calStorage.setItem("username", "John"); // access a localStorage entry }).catch(_ => { // error obtaining storage access. }); Note that access requests are automatically denied unless the embedded content is currently processing a user gesture such as a tap or click -- so this code needs to be run inside some kind of user gesture-based event handler, for example: btn.addEventListener('click',
() => { // run code here }); ...
TextEncoder - Web APIs
TextEncoder takes a stream of code points as input and emits a stream of UTF-8 bytes. Note: There is a polyfill implementation to support non-UTF-8 text encodings on GitHub. Example const encoder = new TextEncoder
() const view = encoder.encode('EUR') console.log(view); // Uint8Array(3) [226, 130, 172] Constructor TextEncoder
() Returns a newly constructed TextEncoder that will generate a byte stream with UTF-8 encoding. Properties The TextEncoder interface doesn't inherit any property. TextEncoder.prototype.encodingRead only Always returns "utf-8". ...
...iew); // Uint8Array(3) [226, 130, 172] Constructor TextEncoder
() Returns a newly constructed TextEncoder that will generate a byte stream with UTF-8 encoding. Properties The TextEncoder interface doesn't inherit any property. TextEncoder.prototype.encodingRead only Always returns "utf-8". Methods The TextEncoder interface doesn't inherit any method. TextEncoder.prototype.encode
() Takes a USVString as input, and returns a Uint8Array containing UTF-8 encoded text. TextEncoder.prototype.encodeInto
() Takes a USVString to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. This is potentially more performant than the older encode
() method. Polyfill The below polyfill is com...
... those cases a polyfill might be impractical for large strings. Finally, note that you should run the below code through a minifier (especially closure compiler) to turn sequences like 0x1e << 3 into 0xf0. These sequences are not already precomputed because they serve to aesthetically illustrate how the polyfill works. if (typeof TextEncoder === "undefined") { TextEncoder=function TextEncoder
(){}; TextEncoder.prototype.encode = function encode(str) { "use strict"; var Len = str.length, resPos = -1; // The Uint8Array's length must be at least 3x the length of the string because an invalid UTF-16 // takes up the equivelent space of 3 UTF-8 characters to encode it properly. However, Array's // have an auto expanding length and 1.5x should be ju...
... | ((point>>>6)&0x3f/*0b00111111*/); resArr[resPos += 1] = (0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/); } } if (typeof Uint8Array !== "undefined") return resArr.subarray(0, resPos + 1); // else // IE 6-9 resArr.length = resPos + 1; // trim off extra weight return resArr; }; TextEncoder.prototype.toString = function
(){return "[object TextEncoder]"}; try { // Object.defineProperty only works on DOM prototypes in IE8 Object.defineProperty(TextEncoder.prototype,"encoding",{ get:function
(){if(TextEncoder.prototype.isPrototypeOf(this)) return"utf-8"; else throw TypeError("Illegal invocation");} }); } catch(e) { /*IE6-8 fallback*/ TextEncoder.prototype.e...
Supporting both TouchEvent and MouseEvent - Web APIs
to the same user input. This section describes the requirement that may affect an application. If the browser fires both touch and mouse events because of a single user input, the browser must fire a touchstart before any mouse events. ...
... mouse events because of a single user input, the browser must fire a touchstart before any mouse events. Consequently, if an application does not want mouse events fired on a specific touch target element, the element's touch event handlers should call preventDefault
() and no additional mouse events will be dispatched. Here is a code snippet of the touchmove event handler calling preventDefault
(). ...
...efore any mouse events. Consequently, if an application does not want mouse events fired on a specific touch target element, the element's touch event handlers should call preventDefault
() and no additional mouse events will be dispatched. Here is a code snippet of the touchmove event handler calling preventDefault
(). ...
...n does not want mouse events fired on a specific touch target element, the element's touch event handlers should call preventDefault
() and no additional mouse events will be dispatched. Here is a code snippet of the touchmove event handler calling preventDefault
(). ...
URL API - Web APIs
s://someguy@mysite.com/login. This is true for any of the writable properties. Queries The search property on a URL contains the query string portion of the URL. For example, if the URL is https://mysite.com/login?user=someguy&page=news, then the value of the search property is ?user=someguy&page=news. ...
...h only a couple of interfaces to its name: URL URLSearchParams Older versions of the specification included an interface called URLUtilsReadOnly, which has since been merged into the WorkerLocation interface. Examples If you want to process the parameters included in a URL, you could do it manually, but it's much easier to create a URL object to do it for you. The fillTableWithParameters
() function below takes as input a HTMLTableElement object representing a <table>. Rows are added to the table, one for each key found in the parameters, with the first column containing the key's name, and the second column having the value. Note the call to URLSearchParams.sort
() to sort the parameter list before generating the table. function fillTableWithParameters(tbl) { let url = new URL(d...
...nt object representing a <table>. Rows are added to the table, one for each key found in the parameters, with the first column containing the key's name, and the second column having the value. Note the call to URLSearchParams.sort
() to sort the parameter list before generating the table. ...
... are added to the table, one for each key found in the parameters, with the first column containing the key's name, and the second column having the value. Note the call to URLSearchParams.sort
() to sort the parameter list before generating the table. function fillTableWithParameters(tbl) { let url = new URL(document.location.href); url.searchParams.sort
(); let keys = url.searchParams.keys
(); for (let key of keys) { let val = url.searchParams.get(key); let row = document.createElement("tr"); let cell = document.createElement("td"); cell.innerText = key; row.appendChild(cell); cell = document.createElement("td"); cell.innerText = val; row.appendChild(cell); tbl.appendChild(row); }; } A working version of this example can be found on Glitch. Ju...
Vibration API - Web APIs
, and does nothing if the device doesn't support it. Describing vibrations Vibration is described as a pattern of on-off pulses, which may be of varying lengths. The pattern may consist of either a single integer, describing the number of milliseconds to vibrate, or an array of integers describing a pattern of vibrations and pauses. Vibration is controlled with a single method: Navigator.vibrate
(). A single vibration You may pulse the vibration hardware one time by specifying either a single value or an array consisting of only one value: window.navigator.vibrate(200); window.navigator.vibrate([200]); Both of these examples vibrate the device for 200 ms. Vibration patterns An array of values describes alternating periods in which the device is vibrating and not vibrating. Each value...
...ses for 100 ms before vibrating the device again for another 200 ms. You may specify as many vibration/pause pairs as you like, and you may provide either an even or odd number of entries; it's worth noting that you don't have to provide a pause as your last entry since the vibration automatically stops at the end of each vibration period. Canceling existing vibrations Calling Navigator.vibrate
() with a value of 0, an empty array, or an array containing all zeros will cancel any currently ongoing vibration pattern. Continued vibrations Some basic setInterval and clearInterval action will allow you to create persistent vibration: var vibrateInterval; // Starts vibration at passed in level function startVibrate(duration) { navigator.vibrate(duration); } // Stops vibration function ...
...ue of 0, an empty array, or an array containing all zeros will cancel any currently ongoing vibration pattern. ...
...ator.vibrate(duration); } // Stops vibration function stopVibrate
() { // Clear interval and stop persistent vibrating if(vibrateInterval) clearInterval(vibrateInterval); navigator.vibrate(0); } // Start persistent vibration at given duration and interval // Assumes a number value is given function startPersistentVibrate(duration, interval) { vibrateInterval = setInterval(function
() { startVibrate(duration); }, interval); } Of course, the snippet above doesn't take into account the array method of vibration; persistent array-based vibration will require calculating the sum of the array items and creating an interval based on that number (with an additional delay, probably). Specifications Specification Status Comment Vibration API ...
VisualViewport - Web APIs
ial containing block origin of the top edge in CSS pixels. VisualViewport.width Read only Returns the width of the visual viewport in CSS pixels. VisualViewport.height Read only Returns the height of the visual viewport in CSS pixels. VisualViewport.scale Read only Returns the pinch-zoom scaling factor applied to the visual viewport. Events Listen to these events using addEventListener
() or by assigning an event listener to the relevant oneventname property of this interface. resize Fired when the visual viewport is resized. Also available via the VisualViewport.onresize property. scroll Fired when the visual viewport is scrolled. Also available via the VisualViewport.onscroll property. Examples Hiding an overlaid box on zoom This example, taken from the Visual Viewpo...
...e, taken from the Visual Viewport README, shows how to write a simple bit of code that will hide an overlaid box (which might contain an advert, say) when the user zooms in. This is a nice way to improve the user experience when zooming in on pages. A live sample is also available. var bottomBar = document.getElementById('bottombar'); var viewport = window.visualViewport; function resizeHandler
() { if (viewport.scale > 1.3) bottomBar.style.display = "none"; else bottomBar.style.display = "block"; } window.visualViewport.addEventListener('resize', resizeHandler); Simulating position: device-fixed This example, also taken from the Visual Viewport README, shows how to use this API to simulate position: device-fixed, which fixes elements to the visual viewport. A live sampl...
...wport.addEventListener('resize', resizeHandler); Simulating position: device-fixed This example, also taken from the Visual Viewport README, shows how to use this API to simulate position: device-fixed, which fixes elements to the visual viewport. A live sample is also available. ...
...ttombar'); var viewport = window.visualViewport; function viewportHandler
() { var layoutViewport = document.getElementById('layoutViewport'); // Since the bar is position: fixed we need to offset it by the visual // viewport's offset from the layout viewport origin. var offsetLeft = viewport.offsetLeft; var offsetTop = viewport.height - layoutViewport.getBoundingClientRect
().height + viewport.offsetTop; // You could also do this by setting style.left and style.top if you // use width: 100% instead. bottomBar.style.transform = 'translate(' + offsetLeft + 'px,' + offsetTop + 'px) ' + 'scale(' + 1/viewport.scale + ')' } window.visualViewport.addEventListener('s...
Visual Viewport API - Web APIs
indow. A window's VisualViewport object provides information about the viewport's position and size, and receives the resize and event:VisualViewport:scroll events you can onitor to know when chances occur to the window's viewport. Example The code below is based on the sample the specification, though it adds a few things that make it function better. It shows a function called viewportHandler
(). When called it queries the offsetLeft and height properties for values it uses in a CSS translate
() method. You invoke this function by passing it to both event calls. One thing that may not be clear in this example is the use of the pendingUpdate flag and the call to requestAnimationFrame
(). The pendingUpdate flag serves to prevent multiple invocations of the transfrom that can occur when onre...
...lues it uses in a CSS translate
() method. You invoke this function by passing it to both event calls. One thing that may not be clear in this example is the use of the pendingUpdate flag and the call to requestAnimationFrame
(). The pendingUpdate flag serves to prevent multiple invocations of the transfrom that can occur when onresize and onscroll fire at the same time. Using requestAnimationFrame
() ensures that the transform ocurrs before the next render. ...
...o requestAnimationFrame
(). The pendingUpdate flag serves to prevent multiple invocations of the transfrom that can occur when onresize and onscroll fire at the same time. Using requestAnimationFrame
() ensures that the transform ocurrs before the next render. let pendingUpdate = false; function viewportHandler(event) { if (pendingUpdate) return; pendingUpdate = true; requestAnimationFrame(
() => { pendingUpdate = false; var layoutViewport = document.getElementById('layoutViewport'); // Since the bar is position: fixed we need to offset it by the // visual viewport's offset from the layout viewport origin. var viewport = event.target; var offsetLeft = viewport.offsetLeft; var offsetTop = viewport.height - layoutViewport.getBoundingClientRect...
... => { pendingUpdate = false; var layoutViewport = document.getElementById('layoutViewport'); // Since the bar is position: fixed we need to offset it by the // visual viewport's offset from the layout viewport origin. var viewport = event.target; var offsetLeft = viewport.offsetLeft; var offsetTop = viewport.height - layoutViewport.getBoundingClientRect
().height + viewport.offsetTop; // You could also do this by setting style.left and style.top if you // use width: 100% instead. bottomBar.style.transform = 'translate(' + offsetLeft + 'px,' + offsetTop + 'px) ' + 'scale(' + 1/viewport.scale + ')' }) } window.visualViewpo...
WebGLActiveInfo - Web APIs
The WebGLActiveInfo interface is part of the WebGL API and represents the information returned by calling the WebGLRenderingContext.getActiveAttrib
() and WebGLRenderingContext.getActiveUniform
() methods. Properties WebGLActiveInfo.name The read-only name of the requested variable. WebGLActiveInfo.size The read-only size of the requested variable. WebGLActiveInfo.type The read-only type of the requested variable. ...
...deringContext.getActiveAttrib
() and WebGLRenderingContext.getActiveUniform
() methods. Properties WebGLActiveInfo.name The read-only name of the requested variable. WebGLActiveInfo.size The read-only size of the requested variable. WebGLActiveInfo.type The read-only type of the requested variable. ...
...enderingContext.getActiveUniform
() methods. Properties WebGLActiveInfo.name The read-only name of the requested variable. WebGLActiveInfo.size The read-only size of the requested variable. WebGLActiveInfo.type The read-only type of the requested variable. ...
... WebGLActiveInfo.name The read-only name of the requested variable. WebGLActiveInfo.size The read-only size of the requested variable. WebGLActiveInfo.type The read-only type of the requested variable. Examples A WebGLActiveInfo object is returned by: WebGLRenderingContext.getActiveAttrib
() WebGLRenderingContext.getActiveUniform
() or WebGL2RenderingContext.getTransformFeedbackVarying
() WebGLActiveInfo? getActiveAttrib(WebGLProgram? program, GLuint index); WebGLActiveInfo? getActiveUniform(WebGLProgram? program, GLuint index); WebGLActiveInfo? getTransformFeedbackVarying(WebGLProgram? program, GLuint index) Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLActiveInfo' in that specification. Recommendation Initial defi...
WebGLShader - Web APIs
At this point the WebGLShader is still not in a usable form and must still be attached to a WebGLProgram. ...
...At this point the WebGLShader is still not in a usable form and must still be attached to a WebGLProgram. ...
... ); throw 'Could not compile WebGL program. \n\n' + info; } return shader; } See WebGLProgram for information on attaching the shaders. Examples Creating a vertex shader Note that there are many other strategies for writing and accessing shader source code strings. These example are for illustration purposes only. ...
...hader source code strings. These example are for illustration purposes only. var vertexShaderSource = 'attribute vec4 position;\n' + 'void main
() {\n' + ' gl_Position = position;\n' + '}\n'; //Use the createShader function from the example above var vertexShader = createShader(gl, vertexShaderSource, gl.VERTEX_SHADER) Creating a fragment shader var fragmentShaderSource = 'void main
() {\n' + ' gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n' + '}\n'; //Use the createShader function from the example above var fragmentShader = createShader(gl, fragmentShaderSource, gl.FRAGMENT_SHADER) Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLShader' in that specification. Recommendation Initial definition. ...
Canvas size and WebGL - Web APIs
The size of the first canvas is set to the styled Element size, determined by CSS. ...
... The size of the first canvas is set to the styled Element size, determined by CSS. ...
...e width and height properties of the canvas to the values of the clientWidth and clientHeight properties, respectively. In contrast, no such assignment is done for the second canvas. The internal width and height properties of the canvas remain at default values, which are different than the actual size of the canvas Element in the browser window. The effect is clearly visible when using scissor
() and clear
() to draw a square in the center of the canvas, by specifying its position and size in pixels. In the first canvas, we get the desired result. In the second, the square has the wrong shape, size, and position. <p>Compare the two canvases.</p> <canvas>Your browser does not seem to support HTML5 canvas.</canvas> <canvas>Your browser does not seem to support HTML5 canvas.</canva...
...Compare the two canvases.</p> <canvas>Your browser does not seem to support HTML5 canvas.</canvas> <canvas>Your browser does not seem to support HTML5 canvas.</canvas> body { text-align : center; } canvas { display : inline-block; width : 120px; height : 80px; margin : auto; padding : 0; border : none; background-color : black; } window.addEventListener("load", function
() { "use strict" var firstCanvas = document.getElementsByTagName("canvas")[0], secondCanvas = document.getElementsByTagName("canvas")[1]; firstCanvas.width = firstCanvas.clientWidth; firstCanvas.height = firstCanvas.clientHeight; [firstCanvas, secondCanvas].forEach(function(canvas) { var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl)...
Simple color animation - Web APIs
); function startAnimation(evt) { button.removeEventListener(evt.type, startAnimation, false); button.addEventListener("click", stopAnimation, false); verb.innerHTML="stop"; // Setup animation loop by redrawing every second. timer = setInterval(drawAnimation, 1000); // Give immediate feedback to user after clicking, by // drawing one animation frame. drawAnimation
(); } function stopAnimation(evt) { button.removeEventListener(evt.type, stopAnimation, false); button.addEventListener("click", startAnimation, false); verb.innerHTML="start"; // Stop animation by clearing the timer. clearInterval(timer); } // Call stopAnimation
() once to setup the initial event // handlers for canvas and button. stopAnimation({type: "click"}); va...
...evt) { button.removeEventListener(evt.type, stopAnimation, false); button.addEventListener("click", startAnimation, false); verb.innerHTML="start"; // Stop animation by clearing the timer. clearInterval(timer); } // Call stopAnimation
() once to setup the initial event // handlers for canvas and button. ...
... ||canvas.getContext("experimental-webgl"); if (!gl) { clearInterval(timer); alert("Failed to get WebGL context.\n" + "Your browser or device may not support WebGL."); return; } gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); } // Get a random color value using a helper function. ...
...awingBufferHeight); } // Get a random color value using a helper function. var color = getRandomColor
(); // Set the WebGLRenderingContext clear color to the // random color. gl.clearColor(color[0], color[1], color[2], 1.0); // Clear the context with the newly set color. gl.clear(gl.COLOR_BUFFER_BIT); } // Random color helper function. function getRandomColor
() { return [Math.random
(), Math.random
(), Math.random
()]; } }, false); The source code of this example is also available on GitHub. << PreviousNext >> ...
Using WebRTC data channels - Web APIs
your own code to negotiate the data transport and write your own code to signal to the other peer that it needs to connect to the new channel. Let's look at each of these cases, starting with the first, which is the most common. Automatic negotiation Often, you can allow the peer connection to handle negotiating the RTCDataChannel connection for you. ...
..., simply call createDataChannel
() without specifying a value for the negotiated property, or specifying the property with a value of false. This will automatically trigger the RTCPeerConnection to handle the negotiations for you, causing the remote peer to create a data channel and linking the two together across the network. The RTCDataChannel object is returned immediately by createDataChannel
(); you can tell when the connection has been made successfully by watching for the open event to be sent to the RTCDataChannel. let dataChannel = pc.createDataChannel("MyApp Channel"); dataChannel.addEventListener("open", (event) => { beginTransmission(dataChannel); }); Manual negotiation To manually negotiate the data channel connection, you need to first create a new RTCDataChannel object ...
...nection has been made successfully by watching for the open event to be sent to the RTCDataChannel. let dataChannel = pc.createDataChannel("MyApp Channel"); dataChannel.addEventListener("open", (event) => { beginTransmission(dataChannel); }); Manual negotiation To manually negotiate the data channel connection, you need to first create a new RTCDataChannel object using the createDataChannel
() method on the RTCPeerConnection, specifying in the options a negotiated property set to true. This signals to the peer connection to not attempt to negotiate the channel on your behalf. Then negotiate the connection out-of-band, using a web server or other means. This process should signal to the remote peer that it should create its own RTCDataChannel with the negotiated property also set to tr...
...e same id. This will link the two objects across the RTCPeerConnection. let dataChannel = pc.createDataChannel("MyApp Channel", { negotiated: true }); dataChannel.addEventListener("open", (event) => { beginTransmission(dataChannel); }); requestRemoteChannel(dataChannel.id); In this code snippet, the channel is created with negotiated set to true, then a function called requestRemoteChannel
() is used to trigger negotiation, to create a remote channel with the same ID as the local channel. Doing this lets you create data channels with each peer using different properties, and to create channels declaratively by simply using the same value for id. Buffering WebRTC data channels support buffering of outbound data. This is handled automatically. While there's no way to control the size...
WebRTC API - Web APIs
epresents the parameters of a session. Each RTCSessionDescription consists of a description type indicating which part of the offer/answer negotiation process it describes and of the SDP descriptor of the session. RTCStatsReport Provides information detailing statistics for a connection or for an individual track on the connection; the report can be obtained by calling RTCPeerConnection.getStats
(). Details about using WebRTC statistics can be found in WebRTC Statistics API. RTCIceCandidate Represents a candidate Interactive Connectivity Establishment (ICE) server for establishing an RTCPeerConnection. RTCIceTransport Represents information about an ICE transport. RTCPeerConnectionIceEvent Represents events that occur in relation to ICE candidates with the target, usually an RTCPeerCo...
...TCErrorEvent indicating that an error occurred on the RTCDtlsTransport. This error will be either dtls-failure or fingerprint-failure. gatheringstatechange The RTCIceTransport's gathering state has changed. icecandidate An RTCPeerConnectionIceEvent which is sent whenever the local device has identified a new ICE candidate which needs to be added to the local peer by calling setLocalDescription
(). icecandidateerror An RTCPeerConnectionIceErrorEvent indicating that an error has occurred while gathering ICE candidates. iceconnectionstatechange Sent to an RTCPeerConnection when its ICE connection's state--found in the iceconnectionstate property--changes. icegatheringstatechange Sent to an RTCPeerConnection when its ICE gathering state--found in the icegatheringstate property--changes.
...e--found in the iceconnectionstate property--changes. icegatheringstatechange Sent to an RTCPeerConnection when its ICE gathering state--found in the icegatheringstate property--changes. message A message has been received on the data channel. The event is of type MessageEvent. negotiationneeded Informs the RTCPeerConnection that it needs to perform session negotiation by calling createOffer
() followed by setLocalDescription
(). open The underlying data transport for the RTCDataChannel has been successfully opened or re-opened. selectedcandidatepairchange The currently-selected pair of ICE candidates has changed for the RTCIceTransport on which the event is fired. track The track event, of type RTCTrackevent is sent to an RTCPeerConnection when a new track is added to the connecti...
... changed for the RTCIceTransport on which the event is fired. track The track event, of type RTCTrackevent is sent to an RTCPeerConnection when a new track is added to the connection following the successful negotiation of the media's streaming. signalingstatechange Sent to the peer connection when its signalingstate has changed. This happens as a result of a call to either setLocalDescription
() or setRemoteDescription
(). statechange The state of the RTCDtlsTransport has changed. statechange The state of the RTCIceTransport has changed. statechange The state of the RTCSctpTransport has changed. Types RTCSctpTransportState Indicates the state of an RTCSctpTransport instance. RTCSessionDescriptionCallback The RTCSessionDescriptionCallback is passed into the RTCPeerConnection ...
Writing WebSocket client applications - Web APIs
you which protocol the server selected. Establishing a WebSocket relies on the HTTP Upgrade mechanism, so the request for the protocol upgrade is implicit when we address the web server as ws://www.example.com or wss://www.example.com. Sending data to the server Once you've opened your connection, you can begin transmitting data to the server. To do this, simply call the WebSocket object's send
() method for each message you want to send: exampleSocket.send("Here's some text that the server is urgently awaiting!"); You can send data as a string, Blob, or ArrayBuffer. As establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send
() method immediately after creating a WebSocket object will be successful. We can at least be sure that attempti...
...event) { exampleSocket.send("Here's some text that the server is urgently awaiting!"); }; Using JSON to transmit objects One handy thing you can do is use JSON to send reasonably complex data to the server. For example, a chat program can interact with a server using a protocol implemented using packets of JSON-encapsulated data: // Send text to all users through the server function sendText
() { // Construct a msg object containing the data the server needs to process the message from the chat client. var msg = { type: "message", text: document.getElementById("text").value, id: clientID, date: Date.now
() }; // Send the msg object as a JSON-formatted string. exampleSocket.send(JSON.stringify(msg)); // Blank the text input element, ready to receive the nex...
...packets the client might receive, such as: Login handshake Message text User list updates The code that interprets these incoming messages might look like this: exampleSocket.onmessage = function(event) { var f = document.getElementById("chatbox").contentDocument; var text = ""; var msg = JSON.parse(event.data); var time = new Date(msg.date); var timeStr = time.toLocaleTimeString
(); switch(msg.type) { case "id": clientID = msg.id; setUsername
(); break; case "username": text = "<b>User <em>" + msg.name + "</em> signed in at " + timeStr + "</b><br>"; break; case "message": text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>"; break; case "rejectusername": text = "<b>Your username has been s...
... name you chose is in use.</b><br>" break; case "userlist": var ul = ""; for (i=0; i < msg.users.length; i++) { ul += msg.users[i] + "<br>"; } document.getElementById("userlistbox").innerHTML = ul; break; } if (text.length) { f.write(text); document.getElementById("chatbox").contentWindow.scrollByPages(1); } }; Here we use JSON.parse
() to convert the JSON object back into the original object, then examine and act upon its contents. Text data format Text received over a WebSocket connection is in UTF-8 format. Closing the connection When you've finished using the WebSocket connection, call the WebSocket method close
(): exampleSocket.close
(); It may be helpful to examine the socket's bufferedAmount attribute before attempt...
Web Animations API - Web APIs
usage The Web Animations API provides a common language for browsers and developers to describe animations on DOM elements. To get more information on the concepts behind the API and how to use it, read Using the Web Animations API. Web Animations interfaces Animation Provides playback controls and a timeline for an animation node or source. Can take an object created with the KeyframeEffect
() constructor. KeyframeEffect Describes sets of animatable properties and values, called keyframes and their timing options. These can then be played using the Animation
() constructor. AnimationTimeline Represents the timeline of animation. This interface exists to define timeline features (inherited by DocumentTimeline and future timeline objects) and is not itself accessed by developers. Ani...
... the timeline of animation. This interface exists to define timeline features (inherited by DocumentTimeline and future timeline objects) and is not itself accessed by developers. AnimationEvent Actually part of CSS Animations. DocumentTimeline Represents animation timelines, including the default document timeline (accessed using the Document.timeline property). EffectTiming Element.animate
(), KeyframeEffectReadOnly.KeyframeEffectReadOnly
(), and KeyframeEffect.KeyframeEffect
() all accept an optional dictionary object of timing properties. Extensions to other interfaces The Web Animations API adds some new features to document and element. Extensions to the Document interface document.timeline The DocumentTimeline object representing the default document timeline. document.get...
...EffectReadOnly.KeyframeEffectReadOnly
(), and KeyframeEffect.KeyframeEffect
() all accept an optional dictionary object of timing properties. Extensions to other interfaces The Web Animations API adds some new features to document and element. Extensions to the Document interface document.timeline The DocumentTimeline object representing the default document timeline. document.getAnimations
() Returns an Array of Animation objects currently in effect on elements in the document. Extensions to the Element interface Element.animate
() A shortcut method for creating and playing an animation on an element. It returns the created Animation object instance. ...
...timeline The DocumentTimeline object representing the default document timeline. document.getAnimations
() Returns an Array of Animation objects currently in effect on elements in the document. Extensions to the Element interface Element.animate
() A shortcut method for creating and playing an animation on an element. It returns the created Animation object instance. Element.getAnimations
() Returns an Array of Animation objects currently affecting an element or which are scheduled to do so in future. Specifications Specification Status Comment Web Animations Working Draft Initial definition ...
Basic concepts behind Web Audio API - Web APIs
ful, because they are independent of the number of channels, and represent time, in a useful way for doing precise audio manipulation. Note: To get a time in seconds from a frame count, simply divide the number of frames by the sample rate. To get a number of frames from a number of samples, simply divide by the channel count. Here's a couple of simple examples: var context = new AudioContext
(); var buffer = context.createBuffer(2, 22050, 44100); Note: In digital audio, 44,100 Hz (alternately represented as 44.1 kHz) is a common sampling frequency. Why 44.1kHz? Firstly, because the hearing range of human ears is roughly 20 Hz to 20,000 Hz. Via the Nyquist-Shannon sampling theorem, the sampling frequency must be greater than twice the maximum frequency one wishes to reproduce. Ther...
... it is to make an anti-aliasing filter. The 44.1 kHz sampling frequency allows for a 2.05 kHz transition band. If you use this call above, you will get a stereo buffer with two channels, that when played back on an AudioContext running at 44100Hz (very common, most normal sound cards run at this rate), will last for 0.5 seconds: 22050 frames/44100Hz = 0.5 seconds. var context = new AudioContext
(); var buffer = context.createBuffer(1, 22050, 22050); If you use this call, you will get a mono buffer with just one channel), that when played back on an AudioContext running at 44100Hz, will be automatically resampled to 44100Hz (and therefore yield 44100 frames), and last for 1.0 second: 44100 frames/44100Hz = 1 second. Note: audio resampling is very similar to image resizing. Say you've got...
...in or frequency data, and then using a graphical technology to turn that into a visual output, such as a graph. The Web Audio API has an AnalyserNode available that doesn't alter the audio signal passing through it. Instead it outputs audio data that can be passed to a visualization technology such as <canvas>. ...
...eb Audio API has an AnalyserNode available that doesn't alter the audio signal passing through it. Instead it outputs audio data that can be passed to a visualization technology such as <canvas>. You can grab data using the following methods: AnalyserNode.getFloatFrequencyData
() Copies the current frequency data into a Float32Array array passed into it. AnalyserNode.getByteFrequencyData
() Copies the current frequency data into a Uint8Array (unsigned byte array) passed into it. AnalyserNode.getFloatTimeDomainData
() Copies the current waveform, or time-domain, data into a Float32Array array passed into it. AnalyserNode.getByteTimeDomainData
() Copies the current waveform, or time-domain, data into a Uint8Array (unsigned byte array) passed into it. Note: For more informatio...
Window.devicePixelRatio - Web APIs
xel to the size of one physical pixel. In simpler terms, this tells the browser how many of the screen's actual pixels should be used to draw a single CSS pixel. This is useful when dealing with the difference between rendering on a standard display versus a HiDPI or Retina display, which use more screen pixels to draw the same objects, resulting in a sharper image. You can use window.matchMedia
() to check if the value of devicePixelRatio changes (which can happen, for example, if the user drags the window to a display with a different pixel density). See the example below. Syntax value = window.devicePixelRatio; Value A double-precision floating-point value indicating the ratio of the display's resolution in physical pixels to the resolution in CSS pixels. A value of 1 indicates a cl...
... changes, so that we can check the value of devicePixelRatio to handle any updates we need to. JavaScript The JavaScript code creates the media query that monitors the device resolution and checks the value of devicePixelRatio any time it changes. let pixelRatioBox = document.querySelector(".pixel-ratio"); let mqString = `(resolution: ${window.devicePixelRatio}dppx)`; const updatePixelRatio =
() => { let pr = window.devicePixelRatio; let prString = (pr * 100).toFixed(0); pixelRatioBox.innerText = `${prString}% (${pr.toFixed(2)})`; } updatePixelRatio
(); matchMedia(mqString).addListener(updatePixelRatio); The string mqString is set up to be the media query itself. The media query, which begins as (resolution: 1dppx) (for standard displays) or (resolution: 2dppx) (for Retina/HiDPI...
...oFixed(2)})`; } updatePixelRatio
(); matchMedia(mqString).addListener(updatePixelRatio); The string mqString is set up to be the media query itself. The media query, which begins as (resolution: 1dppx) (for standard displays) or (resolution: 2dppx) (for Retina/HiDPI displays), checks to see if the current display resolution matches a specific number of device dots per px. The updatePixelRatio
() function fetches the current value of devicePixelRatio, then sets the innerText of the element pixelRatioBox to a string which displays the ratio both as a percentage and as a raw decimal value with up to two decimal places. ...
...or Retina/HiDPI displays), checks to see if the current display resolution matches a specific number of device dots per px. The updatePixelRatio
() function fetches the current value of devicePixelRatio, then sets the innerText of the element pixelRatioBox to a string which displays the ratio both as a percentage and as a raw decimal value with up to two decimal places. Then the updatePixelRatio
() function is called once to display the starting value, after which the media query is created using matchMedia
() and addEventListener
() is called to set up updatePixelRatio
() as a handler for the change event. HTML The HTML creates the boxes containing the instructions and the pixel-ratio box that will display the current pixel ratio information. <div class="container"> <div class="inner-con...
Window.screenX - Web APIs
o popularity. Syntax leftWindowPos = window.screenX Returns A number equal to the number of CSS pixels from the left edge of the browser viewport to the left edge of the screen. Examples In our screenleft-screentop (source code) example, you'll see a canvas onto which has been drawn a circle. ...
...l see a canvas onto which has been drawn a circle. In this example we are using Window.screenLeft/Window.screenTop plus Window.requestAnimationFrame
() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
... Also in the code we ...
... Also in the code we include a snippet that detects whether screenLeft is supported, and if not, polyfills in screenLeft/screenTop using s...
Window.screenY - Web APIs
everywhere due to popularity. Syntax topWindowPos = window.screenY Returns A number equal to the number of CSS pixels from the top edge of the browser viewport to the top edge of the screen. Examples In our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. ...
...l see a canvas onto which has been drawn a circle. In this example we are using Window.screenLeft/Window.screenTop plus Window.requestAnimationFrame
() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
... Also in the code we ...
... Also in the code we include a snippet that detects whether screenLeft is supported, and if not, polyfills in screenLeft/screenTop using s...
Window: unhandledrejection event - Web APIs
r providing fallback error handling for unexpected situations. Bubbles No Cancelable Yes Interface PromiseRejectionEvent Event handler property onunhandledrejection Usage notes Allowing the unhandledrejection event to bubble will eventually result in an error message being output to the console. You can prevent this by calling preventDefault
() on the PromiseRejectionEvent; see Preventing default handling below for an example. Examples Here we have a few examples showing ways you can make use of the unhandledrejection event. The event includes two useful pieces of information: promise The actual Promise which was rejected with no handler available to deal with the rejection. reason The reason that would have been passed into the...
...fault handling below for an example. Examples Here we have a few examples showing ways you can make use of the unhandledrejection event. The event includes two useful pieces of information: promise The actual Promise which was rejected with no handler available to deal with the rejection. reason The reason that would have been passed into the rejection handler if one had existed. See catch
() for details. Basic error logging This example simply logs information about the unhandled promise rejection to the console. window.addEventListener("unhandledrejection", event => { console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`); }); You can also use the onunhandledrejection event handler property to set up the event listener: window.onunhandledrejection = event => { conso...
...ndow.onunhandledrejection = event => { console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`); }; Preventing default handling Many environments (such as Node.js) report unhandled promise rejections to the console by default. ...
...eventDefault
() to cancel the event, preventing it from bubbling up to be handled by the runtime's logging code. This works because unhandledrejection is cancelable. window.addEventListener('unhandledrejection', function (event) { // ...your code here to handle the unhandled rejection... // Prevent the default handling (such as outputting the // error to the console) event.preventDefault
(); }); Specifications Specification Status Comment HTML Living StandardThe definition of 'unhandledrejection' in that specification. Living Standard Initial definition. ...
Worker - Web APIs
nted in WebKit). Not all interfaces and functions are available to scripts inside a Worker. Workers may use XMLHttpRequest for network communication, but its responseXML and channel attributes are always null. (fetch is also available, with no such restrictions.) In Firefox extensions, if you want to use workers with access to js-ctypes, use ChromeWorker object instead. Constructors Worker
() Creates a dedicated web worker that executes the script at the specified URL. This also works for Blob URLs. Properties Inherits properties from its parent, EventTarget, and implements properties from AbstractWorker. Event handlers AbstractWorker.onerror An EventListener called whenever an ErrorEvent of type error bubbles through to the worker. This is inherited from AbstractWorker. Wor...
...hen a message is sent to the parent document from the worker via DedicatedWorkerGlobalScope.postMessage. The message is stored in the event's data property. Worker.onmessageerror Is an EventHandler representing the code to be called when the messageerror event is raised. Methods Inherits methods from its parent, EventTarget, and implements methods from AbstractWorker. Worker.postMessage
() Sends a message -- consisting of any JavaScript object -- to the worker's inner scope. Worker.terminate
() Immediately terminates the worker. This does not let worker finish its operations; it is halted at once. ServiceWorker instances do not support this method. Events message Fires when the worker's parent receives a message from that worker. Also available via the onmessage property. ...
...romise rejects, regardless of whether or not there is a handler to catch the rejection. Also available through the onrejectionhandled event handler property. unhandledrejection Fires when a Promise rejects with no handler to catch the rejection. Also available using the onunhandledrejection event handler property. ...
...dler to catch the rejection. Also available using the onunhandledrejection event handler property. Example The following code snippet creates a Worker object using the Worker
() constructor, then uses the worker object: var myWorker = new Worker('/worker.js'); var first = document.querySelector('input#number1'); var second = document.querySelector('input#number2'); first.onchange = function
() { myWorker.postMessage([first.value, second.value]); console.log('Message posted to worker'); } For a full example, see ourBasic dedicated worker example (run dedicated worker). Specifications Specification Status Comment HTML Living StandardThe definition of 'Worker' in that specification. Living Standard ...
XMLHttpRequest.response - Web APIs
urns the response's body content as an ArrayBuffer, Blob, Document, JavaScript Object, or DOMString, depending on the value of the request's responseType property. Syntax var body = XMLHttpRequest.response; Value An appropriate object based on the value of responseType. You may attempt to request the data be provided in a specific format by setting the value of responseType after calling open
() to initialize the request but before calling send
() to send the request to the server. The value is null if the request is not yet complete or was unsuccessful, with the exception that when reading text data using a responseType of "text" or the empty string (""), the response can contain the response so far while the request is still in the LOADING readyState (3). The response types are descri...
...sing XHR to fetch HTML content. json The response is a JavaScript object created by parsing the contents of received data as JSON. text The response is a text in a DOMString object. ms-stream The response is part of a streaming download; this response type is only allowed for download requests, and is only supported by Internet Explorer. Example This example presents a function, load
(), which loads and processes a page from the server. It works by creating an XMLHttpRequest object and creating a listener for readystatechange events such that that when readyState changes to DONE (4), the response is obtained and passed into the callback function provided to load
(). The content is handled as raw text data (since nothing here is overriding the default responseType). var url = 's...
...bject and creating a listener for readystatechange events such that that when readyState changes to DONE (4), the response is obtained and passed into the callback function provided to load
(). The content is handled as raw text data (since nothing here is overriding the default responseType). ...
...tatechange events such that that when readyState changes to DONE (4), the response is obtained and passed into the callback function provided to load
(). The content is handled as raw text data (since nothing here is overriding the default responseType). ...
XMLHttpRequest.status - Web APIs
The read-only XMLHttpRequest.status property returns the numerical HTTP status code of the XMLHttpRequest's response. Before the request completes, the value of status is 0. Browsers also report a status of 0 in case of XMLHttpRequest errors. ...
...LHttpRequest.status property returns the numerical HTTP status code of the XMLHttpRequest's response. Before the request completes, the value of status is 0. Browsers also report a status of 0 in case of XMLHttpRequest errors. ...
...the XMLHttpRequest's response. Before the request completes, the value of status is 0. Browsers also report a status of 0 in case of XMLHttpRequest errors. ...
...pletes, the value of status is 0. Browsers also report a status of 0 in case of XMLHttpRequest errors. ...
XRInputSource.targetRaySpace - Web APIs
of their targetRayMode--have a valid targetRaySpace. The exact meaning of this space varies, however, depending on the mode: Every gaze input (targetRayMode value of gaze), shares the same XRSpace object as their target ray space, since the gaze input comes from the viewer's head. ...
... Example This fragment of code shows part of a function to be called once every frame. It looks for inputs which have a non-NULL targetRaySpace. Inputs which have a value for this property represent inputs that project a target ray outward from the user. ...
...Space. Inputs which have a value for this property represent inputs that project a target ray outward from the user. For each such input, this example looks for inputs whose targetRayMode is tracked-pointer, indicating that the input is in fact intended to represent a targeting device rather than a gazing device, screen tap, or mouse click. For tracked pointers, a function myRenderTargetRayAsBeam
() is called to render a beam from the input controller's virtual position outward in the direction it's pointing. The code should continue to perform tasks such as drawing controllers or any objects representative of the user's hands' positions in the virtual space, as well as any other input-related tasks. function updateInputSources(session, frame, refSpace) { for (let source of session.getIn...
... to render a beam from the input controller's virtual position outward in the direction it's pointing. The code should continue to perform tasks such as drawing controllers or any objects representative of the user's hands' positions in the virtual space, as well as any other input-related tasks. function updateInputSources(session, frame, refSpace) { for (let source of session.getInputSources
()) { let targetRayPose = frame.getPose(inputSource.targetRaySpace, refSpace); if (targetRayPose) { if (source.targetRayMode == "tracked-pointer") { myRenderTargetRayAsBeam(targetRayPose); } } /* ... */ } } See the article Inputs and input sources for more details and a more complete example. Specifications Specification Status Comment ...
XRInputSourceArray - Web APIs
XR input sources, and is used as the return value of the XRSession property inputSources. Each entry is an XRInputSource representing one input device connected to the WebXR system. ...
... brackets), methods are available to allow the use of iterators and the forEach
() method is also available. Properties The following properties are available on XRInputSourceArray objects. length Read only The number of XRInputSource objects in the list. Methods The following methods are available on XRInputSourceArray objects. You may also use the features of the Symbol type. entries
() Returns an iterator you can use to walk the list of key/value pairs in the list. Each item returned is an array whose first value is the index and whose second value is the XRInputSource at that index. forEach
() Iterates over each item in the list, in order from first to last. ...
...thods are available on XRInputSourceArray objects. You may also use the features of the Symbol type. entries
() Returns an iterator you can use to walk the list of key/value pairs in the list. Each item returned is an array whose first value is the index and whose second value is the XRInputSource at that index. forEach
() Iterates over each item in the list, in order from first to last. keys
() A list of the keys corresponding to the entries in the input source list. values
() Returns an iterator you can use to go through all the values in the list. Each item is a single XRInputSource object. ...
... let sources = xrSession.inputSources; if (sources.length > 0) { handleInput(sources[0]); } Examples Specifications Specification Status Comment WebXR Device APIThe definition of 'XRInputSourceArray' in that specification. ...
XRPermissionDescriptor - Web APIs
iving the names of the WebXR features for which permission must be obtained in order to use your app or site. Examples The example below demonstrates performing the permission request for an application that requires the local-floor reference space in an immersive-vr environment. ...
...the local-floor reference space in an immersive-vr environment. If the Permissions API is found to be available (by checking to see if navigator.permissions is defined), its query
() method is called, specifying the permission descriptor we've established, xrPermissionDesc. When the returned promise resolves, we check the returned status. If permission has been granted, we call a function setupXR
() that handles preparing the WebXR environment for use. If permission is conditional based on prompting, we call a function promptAndSetupXR
() that would handle asking for permission before enabling and starting up the environment. And for any other returned state--which is almost certainly denied, which is the only other option as of this article's writing--we do nothing, since we can't use WebXR.
... that would handle asking for permission before enabling and starting up the environment. And for any other returned state--which is almost certainly denied, which is the only other option as of this article's writing--we do nothing, since we can't use WebXR. If the permission request promise is rejected, the error is handled (currently by just dumping it to the console using domxref("console.log
()")}}). If the Permissions API isn't available at all, this example simply assumes that WebXR will report an appropriate error if permission isn't available, and tries to start up the WebXR session using the same setupXR
() function called by the granted case. let xrPermissionDesc = { name: "xr", mode: "immersive-vr", requiredFeatures: [ "local-floor" ] }; if (navigator.permissions) { nav...
... error if permission isn't available, and tries to start up the WebXR session using the same setupXR
() function called by the granted case. let xrPermissionDesc = { name: "xr", mode: "immersive-vr", requiredFeatures: [ "local-floor" ] }; if (navigator.permissions) { navigator.permissions.query(xrPermissionDesc).then(({state}) => { switch(state) { case "granted": setupXR
(); break; case "prompt": promptAndSetupXR
(); break; default: /* do nothing otherwise */ break; } .catch(err) { console.log(err); } } else { setupXR
(); } Specifications Specification Status Comment WebXR Device APIThe definition of 'XRPermissionDescriptor' in that specification. Working Draft Initial ...
XRPose.transform - Web APIs
The transform read-only attribute of the XRPose interface is a XRRigidTransform object providing the position and orientation of the pose relative to the base XRSpace as specified when the pose was obtained by calling XRFrame.getPose
(). Syntax let poseTransform = xrPose.transform; Value An XRRigidTransform which provides the position and orientation of the XRPose relative to the XRFrame to which this XRPose is aligned. This is the same pose that's returned by the frame's getPose
() method. ...
...igidTransform which provides the position and orientation of the XRPose relative to the XRFrame to which this XRPose is aligned. This is the same pose that's returned by the frame's getPose
() method. Example This handler for the XRSession event select handles events for tracked pointers. It determines the targeted object by passing the event frame's pose into a function called findTargetUsingRay
(), then dispatches the event differently depending on the user's handedness; this is done by comparing the value of the XRInputSource property handedness to a value in the variable user.handedness. If the source is a controller in the user's primary hand, a function is called on the targeted object called primaryAction
(); otherwise, it calls the targeted object's offHandAction
() function. xrSessio...
... Working Draft Initial definition. ...
... Working Draft Initial definition. ...
XRReferenceSpace - Web APIs
(of which there are none at this time), XRReferenceSpace also inherits the properties of EventTarget. XRReferenceSpace defines no additional properties. Methods In addition to the methods inherited from its parent interface, XRSpace (there are none at this time), XRReferenceSpace inherits methods from EventTarget. XRReferenceSpace also provides the following methods. getOffsetReferenceSpace
() Creates and returns a new reference space object as the same type as the one on which you call the method (so, either XRReferenceSpace or XRBoundedReferenceSpace). The new reference space can be used to transform a coordinate from the reference space of the object on which the method is called into a different coordinate space. This is useful for positioning objects while rendering, and to perf...
...et The reset event is sent to an XRReferenceSpace object when the browser detects a discontinuity has occurred wherein the tracked object's origin relative to the user's environment or location. This can happen, for example, after the user recalibrates their XR device, or if the device automatically adjusts its origin after losing and regaining tracking. In addition to using addEventListener
(), you can establish a reset event handler by setting the onreset event handler property. Reference space types The reference space returned by XRSession.requestReferenceSpace
() is either XRReferenceSpace or XRBoundedReferenceSpace. The "Interface" column in the table below indicates which of the two types is returned for each reference space type constant.. Reference space descriptors The t...
...space types will be used more often. XRReferenceSpace Usage notes Creating an XRReferenceSpace There are two situations in which you need to obtain an XRReferenceSpace. The first is when you set up your scene and need to obtain a reference space to represent the user's viewpoint on the world for the duration of the XRSession. To do that, call the XRSession method requestReferenceSpace
(), specifying the reference space type you wish to obtain. xrSession.requestReferenceSpace("local").then((refSpace) => { xrReferenceSpace = refSpace; /* ... */ }); The other situation in which you may need to acquire a new reference space is if you need to move the origin to a new position; this is commonly done, for example, when your project allows the user to move through the environment u...
... you need to change the origin to reflect their movement and any orientation changes they make. To move or rotate the user's view of the world, you need to change the XRReferenceSpace used to represent that viewpoint. However, XRReferenceSpace is immutable, so you need to instead create a new reference space representing the changed viewpoint. This is easily done using the getOffsetReferenceSpace
() method. let offsetTransform = new XRRigidTransform({x: 2, y: 0, z: 1}, {x: 0, y: 1, z: 0, w: 1}); xrReferenceSpace = xrReferenceSpace.getOffsetReferenceSpace(offsetTransform); This replaces the XRReferenceSpace with a new one whose origin and orientation are adjusted to place the new origin at (2, 0, 1) relative to the current origin and rotated given ...
XRRenderState.baseLayer - Web APIs
ption of how the image is to be rendered in the device. This property is read-only; however, you can indirectly change its value using XRSession.updateRenderState. Syntax var xrWebGLLayer = xrRenderState.baseLayer; Value A XRWebGLLayer object which is used as the source of the world's contents when rendering each frame of the scene. ...
...eRenderState. Syntax var xrWebGLLayer = xrRenderState.baseLayer; Value A XRWebGLLayer object which is used as the source of the world's contents when rendering each frame of the scene. See the examples below to see how to use updateRenderState
() to set the current XRWebGLLayer used for rendering the scene. ...
...d's contents when rendering each frame of the scene. See the examples below to see how to use updateRenderState
() to set the current XRWebGLLayer used for rendering the scene. Examples You can set the XRWebGLLayer used for rendering by calling updateRenderState
(), like this: let canvas = document.querySelector("canvas"); gl = canvas.getContext("webgl", { xrCompatible: true }); setNewWebGLLayer
(); function setNewWebGLLayer(gl) { if (!gl) { /* WebGL not available */ return; } xrSession.updateRenderState({ baseLayer: new XRWebGLLayer(xrSession, gl); }); }; Here, the canvas obtained in the first line is the canvas into which WebGL is going to draw. ...
...; gl = canvas.getContext("webgl", { xrCompatible: true }); setNewWebGLLayer
(); function setNewWebGLLayer(gl) { if (!gl) { /* WebGL not available */ return; } xrSession.updateRenderState({ baseLayer: new XRWebGLLayer(xrSession, gl); }); }; Here, the canvas obtained in the first line is the canvas into which WebGL is going to draw. That context is passed into new XRWebGLLayer
() to create an XRWebGLLayer which uses the contents of the WebGL context gl as the source of the world's image during presentation. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRRenderState.baseLayer' in that specification. Working Draft Initial definition. ...
XRView - Web APIs
at will transform the scene to appear correctly given the point-of-view indicated by eye. This matrix should be used directly in order to avoid presentation distortions that may lead to potentially serious user discomfort. transform Read only An XRRigidTransform which describes the current position and orientation of the viewpoint in relation to the XRReferenceSpace specified when getViewerPose
() was called on the XRFrame being rendered. Usage notes Positions and number of XRViews per frame While rendering a scene, the set of views that are used to render the scene for the viewer as of the current frame are obtained by calling the XRFrame object's getViewerPose
() method to get the XRViewerPose representing (in essence) the position of the viewer's head. That object's views property i...
...ewspoints not direclty associated with a player's eye. In addition, the number of views can change at any time, depending on the needs of the time. So you should process the view list every time without making assumptions based on previous frames. All positions and orientations within the views for a given XRViewerPose are specified in the reference space that was passed to XRFrame.getViewerPose
(); this is called the viewer reference space. The transform property describes the position and orientation of the eye or camera represented by the XRView, given in that reference space. The destination rendering layer To render a frame, you just iterate over the XRViewerPose's views, rendering each of them into the appropriate viewport within the frame's XRWebGLLayer. Currently, the specificatio...
...y inverting then transposing the model view matrix: mat4.invert(normalMatrix, modelViewMatrix); mat4.transpose(normalMatrix, normalMatrix); Teleporting an object To programmatically move and/or rotate (often referred to as teleporting) an object, you need to create a new reference space for that object which applies a transform that encapsulates the desired changes. The createTeleportTransform
() function returns the transform needed to move and rotate an object whose current situation is described by the reference space refSpace to a new position and orientation which is computed using previously recorded mouse and keyboard input data which has generated offsets for yaw, pitch, and position along all three axes. function applyMouseMovement(refSpace) { if (!mouseYaw && !mousePitch && !
...rameter. The returned object's matrix property is the actual matrix that transforms points from the scene's reference space to the object's new position. Finally, a new reference space is created to describe the relationship between the two reference spaces fully. That reference space is returnedto the caller. To use this function, we simply pass the returned reference space into XRFrame.getPose
() or getViewerPose
(), as appropriate for yoru needs. the XRPose returned will then be used to actuall render the scene for the current frame. You can find a more extensive and complete example in our article Movement, orientation, and motion. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRView' in that specification. Working Draft ...
XRViewerPose - Web APIs
mation becomes crucial. An XRViewerPose is always obtained and referenced relative to an existing XRReferenceSpace. This ensures that positions and orientations are reported using the expected relative coordinate system. To render a scene using the XRViewerPose representing the user's head, one would iterate over the views in the views array, rendering them one after another. By calling viewport
() on the WebGL context, specifying the XRView as input, you can get the viewport to use when rendering in order to draw the frame for that eye into the correct part of the drawing surface. Also, when rendering the scene for spectators or other players in a multiplayer game, the transform of the XRViewerPose can be used to determine both placement and facing direction of the other players in the ga...
... when rendering the scene for spectators or other players in a multiplayer game, the transform of the XRViewerPose can be used to determine both placement and facing direction of the other players in the game, so that they can be drawn in the correct place with the correct facing. ...
...If a valid pose is returned, the frame is rendered by clearing the backbuffer and then rendering each of the views in the pose; these are most likely the views for the left and right eyes. ...
... This code is derived from Drawing a frame in Movement, orientation, and motion: A WebXR example. You can see more context and see much more on that page. Specifications Specification Status Comment ...
XSLTProcessor - Web APIs
An XSLTProcessor applies an XSLT stylesheet transformation to an XML document to produce a new XML document as output. It has methods to load the XSLT stylesheet, to manipulate <xsl:param> parameter values, and to apply the transformation to documents. Syntax The constructor has no parameters. new XSLTProcessor
() Methods [Throws] void XSLTProcessor.importStylesheet(Node styleSheet) Imports the XSLT stylesheet. If the given node is a document node, you can pass in a full XSL Transform or a literal result element transform; otherwise, it must be an <xsl:stylesheet> or <xsl:transform> element. [Throws] DocumentFragment XSLTProcessor.transformToFragment(Node source, Document owner) Transforms the node source by applying the stylesheet imported using the XSLTProcessor.import...
... the XSLT stylesheet. If the given node is a document node, you can pass in a full XSL Transform or a literal result element transform; otherwise, it must be an <xsl:stylesheet> or <xsl:transform> element. [Throws] DocumentFragment XSLTProcessor.transformToFragment(Node source, Document owner) Transforms the node source by applying the stylesheet imported using the XSLTProcessor.importStylesheet
() function. The owner document of the resulting document fragment is the owner node. [Throws] Document XSLTProcessor.transformToDocument(Node source) Transforms the node source applying the stylesheet given importing using the XSLTProcessor.importStylesheet
() function. The resultant object depends on the output method of the stylesheet: Output method Result type ...
...for namespaceURI is treated the same as an empty string. [Throws] void XSLTProcessor.removeParameter(String namespaceURI, String localName) Removes the parameter if it was previously set. This will make the XSLTProcessor use the default value for the parameter as specified in the stylesheet. A null value for namespaceURI is treated the same as an empty string. void XSLTProcessor.clearParameters
() Removes all set parameters from the XSLTProcessor. The XSLTProcessor will then use the defaults specified in the XSLT stylesheet. void XSLTProcessor.reset
() Removes all parameters and stylesheets from the XSLTProcessor. Properties Non-Web-exposed properties The following properties are [ChromeOnly] and not exposed to Web content: [ChromeOnly] attribute unsigned long XSLTProcessor.flags ...
...faults specified in the XSLT stylesheet. void XSLTProcessor.reset
() Removes all parameters and stylesheets from the XSLTProcessor. Properties Non-Web-exposed properties The following properties are [ChromeOnly] and not exposed to Web content: [ChromeOnly] attribute unsigned long XSLTProcessor.flags Flags that tweak the behavior of the processor. Not reset by calling XSLTProcessor.reset
(). Default value: 0 Possible values are: Name Value Effect (None) 0 None DISABLE_ALL_LOADS 1 Disable loading external documents (via e.g. <xsl:import> and document
()) Examples Basic example Advanced example Additional example Specifications Not part of any specification. This is a proprietary interface that o...
ARIA: grid role - Accessibility
w = row + 1; }); function moveto(newrow, newcol) { var tgt = document.querySelector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); if (tgt && (tgt.getAttribute('role')==='gridcell') ) { Array.prototype.forEach.call(document.querySelectorAll('[role=gridcell]'), function(el, i){ el.setAttribute('tabindex', '-1'); }); tgt.setAttribute('tabindex', '0'); tgt.focus
(); return true; } else { return false; } } document.querySelector('table').addEventListener("keydown", function(event) { switch (event.key) { case "ArrowRight": moveto(parseInt(event.target.dataset.row, 10), parseInt(event.target.dataset.col, 10) + 1); break; case "ArrowLeft": moveto(parseInt(event.target.dataset.row, 10), parseInt(event.target.dataset.col, ...
... do { result = moveto(i, event.target.dataset.col); i++; } while (result == false); break; case "PageDown": var i = maxrow; var result; do { result = moveto(i, event.target.dataset.col); i--; } while (result == false); break; case "Enter": alert(event.target.textContent); break; } event.preventDefault
(); }); HTML <table role="grid" aria-labelledby="calendarheader"> <caption id="calendarheader">September 2018</caption> <thead role="rowgroup"> <tr role="row"> <td></td> <th role="columnheader" aria-label="Sunday">S</th> <th role="columnheader" aria-label="Monday">M</th> <th role="columnheader" aria-label="Tuesday">T</th> <th role="columnheader" aria-label...
...w = row + 1; }); function moveto(newrow, newcol) { var tgt = document.querySelector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); if (tgt && (tgt.getAttribute('role')==='gridcell') ) { Array.prototype.forEach.call(document.querySelectorAll('[role=gridcell]'), function(el, i){ el.setAttribute('tabindex', '-1'); }); tgt.setAttribute('tabindex', '0'); tgt.focus
(); return true; } else { return false; } } document.querySelector('table').addEventListener("keydown", function(event) { switch (event.key) { case "ArrowRight": moveto(parseInt(event.target.dataset.row, 10), parseInt(event.target.dataset.col, 10) + 1); break; case "ArrowLeft": moveto(parseInt(event.target.dataset.row, 10), parseInt(event.target.dataset.col, ...
...Make sure that the functionality and interaction needed can be best achieved using the grid role. Specifications Specification Status Accessi...
ARIA: checkbox role - Accessibility
e of the checkbox by changing the value of the aria-checked attribute and the appearance of the checkbox so it appears checked or unchecked to the sighted user Examples The following example creates a simple checkbox element using CSS and JavaScript to handle the checked or unchecked status of the element. ...
...the value of the aria-checked attribute and the appearance of the checkbox so it appears checked or unchecked to the sighted user Examples The following example creates a simple checkbox element using CSS and JavaScript to handle the checked or unchecked status of the element. ...
...hecked to the sighted user Examples The following example creates a simple checkbox element using CSS and JavaScript to handle the checked or unchecked status of the element. ...
... Examples The following example creates a simple checkbox element using CSS and JavaScript to handle the checked or unchecked status of the element. ...
Web applications and ARIA FAQ - Accessibility
gress> <button id="update-button">Update</button> </body> </html> ... and here is the JavaScript code that will ensure the progress bar still works in older browsers: var progressBar = document.getElementById("progress-bar"); // Check to see if the browser supports the HTML5 <progress> tag. var supportsHTML5Progress = (typeof (HTMLProgressElement) !== "undefined"); function setupProgress
() { if (!supportsHTML5Progress) { // HTML5 <progress> isn't supported in this browser, so we need to add // ARIA roles and states to the element. progressBar.setAttribute("role", "progressbar"); progressBar.setAttribute("aria-valuemin", 0); progressBar.setAttribute("aria-valuemax", 100); } } function updateProgress(percentComplete) { if (!supportsHTML5Progress) { // H...
... HTML5 <progress> isn't supported by this browser, // so we need to update the aria-valuenow attribute progressBar.setAttribute("aria-valuenow", percentComplete); } else { // HTML5 <progress> is supported, so update the value attribute instead. ...
...n't supported by this browser, // so we need to update the aria-valuenow attribute progressBar.setAttribute("aria-valuenow", percentComplete); } else { // HTML5 <progress> is supported, so update the value attribute instead. ...
...rogressBar.setAttribute("value", percentComplete); } progressBar.textContent = percentComplete + "% complete"; } function initDemo
() { setupProgress
(); // Setup the progress bar. // Bind a click handler to the button, which will update the progress bar to 75%. document.getElementById("update-button").addEventListener("click", function (e) { updateProgress(75); e.preventDefault
(); }, false); } initDemo
(); How do assistive technologies work? Assistive technologies use an API built into each operating system specifically designed to describe the roles, states, and structure of an application's user interface. For example, a screen reader uses this API to read the user interface with a text-to-speech engine, a magnifier uses it to highlight important or active areas of ...
Keyboard-navigable JavaScript widgets - Accessibility
ive tabindex are put before the default interactive elements on the page, which means page authors will have to set (and maintain) tabindex values for all focusable elements on the page whenever they use one or more positive values for tabindex. The following table describes tabindex behavior in modern browsers: tabindex attribute Focusable with mouse or JavaScript via element.focus
() Tab navigable not present Follows the platform convention of the element (yes for form controls, links, etc.). Follows the platform convention of the element. Negative (i.e. tabindex="-1") Yes No; author must focus the element with focus
() in response to arrow or other key presses. Zero (i.e. tabindex="0") Yes In tab order relative to element's posi...
...ocused item. To do this: Bind a key down handler to each element in the group, and when an arrow key is used to move to another element: programmatically apply focus to the new element, update the tabindex of the focused element to "0", and update the tabindex of the previously focused element to "-1". Here's an example of a WAI-ARIA tree view using this technique. Tips Use element.focus
() to set focus Do not use createEvent
(), initEvent
() and dispatchEvent
() to send focus to an element. DOM focus events are considered informational only: generated by the system after something is focused, but not actually used to set focus. Use element.focus
() instead. Use onfocus to track the current focus Don't assume that all focus changes will come via key and mouse events: assistive techno...
...igate using the arrow keys should also be used by mouse click handlers to produce the same changes. Ensure that the keyboard can be used to activate element To ensure that the keyboard can be used to activate elements, any handlers bound to mouse events should also be bound to keyboard events. For example, to ensure that the Enter key will activate an element, if you have an onclick="doSomething
()", you should bind doSomething
() to the key down event as well: onkeydown="return event.keyCode != 13 || doSomething
();". Always draw the focus for tabindex="-1" items and elements that receive focus programatically IE will not automatically draw the focus outline for items that programatically receive focus. Choose between changing the background color via something like this.style.backgroundCo...
...ines). Prevent used key events from performing browser functions If your widget handles a key event, prevent the browser from also handling it (for example, scrolling in response to the arrow keys) by using your event handler's return code. If your event handler returns false, the event will not be propagated beyond your handler. For example: <span tabindex="-1" onkeydown="return handleKeyDown
();"> If handleKeyDown
() returns false, the event will be consumed, preventing the browser from performing any action based on the keystroke. Don't rely on consistent behavior for key repeat, at this point Unfortunately onkeydown may or may not repeat depending on what browser and OS you're running on. ...
-moz-image-rect - CSS: Cascading Style Sheets
on This property allows you to, for example, use different parts of one larger image as backgrounds in different parts of your content. This works very similarly to the -moz-image-region property, which is used with the list-style-image property to use parts of an image as the bullets in lists. However, this can be used for any CSS background. The syntax for the rectangle is similar to the rect
() function generating a <<shape>
()> CSS type. All four values are relative to the upper left corner of the image. Examples This example loads an image and uses it in four segments to draw the Firefox logo in four <div> blocks. Clicking on their container causes the four segments to rotate around by swapping the background-image property values among the four <div> blocks. CSS The CSS defines on...
...These four segments are all contained within a larger <div> block whose...
... style="left:133px;top:136px;">Bottom right</div> </div> This places the four segments of our image in a two-by-two box grid. These four segments are all contained within a larger <div> block whose primary purpose is to receive click events and dispatch them to our JavaScript code. The JavaScript code This code handles the click event when the container receives a mouse click. ...
...Notice that before it begins doing so it saves a copy of the last box's style since it will be overwritten by the third element's style. By simply copying the values of the background-image property from one element to the next with each mouse click, we achieve the desired effect. What it looks like Specifications Not ...
@font-feature-values - CSS: Cascading Style Sheets
ule lets you use a common name in the font-variant-alternates property for features activated differently in OpenType. This can help simplify your CSS when using multiple fonts. The @font-feature-values at-rule may be used either at the top level of your CSS or inside any CSS conditional-group at-rule. Syntax Feature value blocks @swash Specifies a feature name that will work with the swash
() functional notation of font-variant-alternates. A swash feature value definition allows only one value: ident1: 2 is valid, but ident2: 2 4 isn't. @annotation Specifies a feature name that will work with the annotation
() functional notation of font-variant-alternates. An annotation feature value definition allows only one value: ident1: 2 is valid, but ident2: 2 4 isn't. @ornaments Specifies ...
... A swash feature value definition allows only one value: ident1: 2 is valid, but ident2: 2 4 isn't. @annotation Specifies a feature name that will work with the annotation
() functional notation of font-variant-alternates. An annotation feature value definition allows only one value: ident1: 2 is valid, but ident2: 2 4 isn't. @ornaments Specifies a feature name that will work with the ornaments
() functional notation of font-variant-alternates. An ornaments feature value definition allows only one value: ident1: 2 is valid, but ident2: 2 4 isn't. @stylistic Specifies a feature name that will work with the stylistic
() functional notation of font-variant-alternates. A stylistic feature value definition allows only one value: ident1: 2 is valid, but ident2: 2 4 isn't. @styleset Specifies ...
.... An ornaments feature value definition allows only one value: ident1: 2 is valid, but ident2: 2 4 isn't. @stylistic Specifies a feature name that will work with the stylistic
() functional notation of font-variant-alternates. A stylistic feature value definition allows only one value: ident1: 2 is valid, but ident2: 2 4 isn't. @styleset Specifies a feature name that will work with the styleset
() functional notation of font-variant-alternates. A stylset feature value definition allows an unlimited number of values: ident1: 2 4 12 1 maps to the OpenType values ss02, ss04, ss12, and ss01. ...
...A character-variant feature value definition allows either one or two values: ident1: 3 maps to cv03=1, and ident2: 2 4 maps to cv02=4, but ident2: 2 4 5 is invalid. ...
@supports - CSS: Cascading Style Sheets
a colon). The declaration must be surrounded by parentheses. The following example returns true if the browser's transform-origin property considers 5% 5% valid: @supports (transform-origin: 5% 5%) {} Function syntax The second basic supports condition is a supports function, the syntax for these is supported by all browsers, but the functions themselves are still being standardized. selector
() Tests if the browser supports the tested selector syntax. The following example returns true if the browser supports the child combinator: @supports selector(A > B) {} The not operator The not operator can precede any expression to create a new expression, resulting in the negation of the original one. The following example returns true if the browser's transform-origin property doesn't con...
... are supported */ } Testing for the non-support of a specific CSS property @supports not ((text-align-last: justify) or (-moz-text-align-last: justify)) { ... /* CSS to provide fallback alternative for text-align-last: justify */ } Testing for the support of custom properties @supports (--foo: green) { body { color: var(--varName); } } Testing for the support of a selector (eg. :is
()) /* This rule won't be applied in browsers which don't support :is
() */ :is(ul, ol) > li { ... /* CSS applied when the :is(...) selector is supported */ } @supports not selector(:is(a, b)) { /* Fallback for when :is
() is unsupported */ ul > li, ol > li { ... /* The above expanded for browsers which don't support :is(...) */ } } @supports selector(:nth-child(1n of a, b)) { /*...
...supported */ :is(:nth-child(1n of ul, ol) a, details > summary) { ... /* CSS applied when the :is(...) selector and the `of` argument of :nth-child(...) are both supported */ } } Specifications Specification Status Comment CSS Conditional Rules Module Level 4The definition of '@supports' in that specification. Editor's Draft Adds the selector
() function. CSS Conditional Rules Module Level 3The definition of '@supports' in that specification. Candidate Recommendation Initial definition. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopM...
...lusive): this feature is behind the layout.css.supports-rule.enabled preference (needs to be set to true). ...
Using CSS counters - CSS: Cascading Style Sheets
he counter-reset property (0 by default). The same property can also be used to change its value to any specific number. Once initialized, a counter's value can be increased or decreased with counter-increment. The counter's name must not be "none", "inherit", or "initial"; otherwise the declaration is ignored. ...
...et property (0 by default). The same property can also be used to change its value to any specific number. Once initialized, a counter's value can be increased or decreased with counter-increment. The counter's name must not be "none", "inherit", or "initial"; otherwise the declaration is ignored. ...
...an also be used to change its value to any specific number. Once initialized, a counter's value can be increased or decreased with counter-increment. 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 counte...
... section counter, and a colon before the content of each h3 */ } HTML <h3>Introduction</h3> <h3>Body</h3> <h3>Conclusion</h3> Result Nesting counters A CSS counter can be especially useful for making outlined lists, because a new instance of the counter is automatically created in child elements. Using the counters
() function, separating text can be inserted between different levels of nested counters. Example of a nested counter CSS ol { counter-reset: section; /* Creates a new instance of the section counter with each ol element */ list-style-type: none; } li::before { counter-increment: section;...
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
Complex websites have very large amounts of CSS, often with a lot of repeated values. ...
...oot { --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 -- --my-color will be treated as a separate custom property to --My-color. ...
...ctual variables like you might find in other programming languages. The value is computed where it is needed, not stored for use in other rules. For instance, you cannot set a property for an element and expect to retrieve it in a sibling's descendant's rule. The property is only set for the matching selector and its descendants, like any normal CSS. Custom property fallback values Using the var
() function, you can define multiple fallback values when the given variable is not yet defined; this can be useful when working with Custom Elements and Shadow DOM. Fallback values aren't used to fix the browser compatibility. If the browser doesn't support CSS custom Properties, the fallback value won't help. It's just a backup for the browser which supports CSS Custom Properties to choose a dif...
...the function is considered a fallback value. Validity and values The classical CSS concept of validity, tied to each property, is not very useful in regard to custom properties. When the values of the custom properties are parsed, the browser doesn't know where they will be used, so must, therefore, consider nearly all values as valid. Unfortunately, these valid values can be used, via the var
() functional notation, in a context where they might not make sense. Properties and custom variables can lead to invalid CSS statements, leading to the new concept of valid at computed time. What happens with invalid variables? When the browser encounters an invalid var
() substitution, the initial or inherited value of the property is used. Consider the code snippet below. HTML <p>This paragra...
clip-path - CSS: Cascading Style Sheets
, [ <length-percentage> <length-percentag...
..., [ <length-percentage> <length-percentage> ]# )<path(...
... the defs element and all graphics elementsInheritednoPercentagesrefer to reference box when specified, otherwise border-boxComputed valueas specified, but with <url> values made absoluteAnimation typeyes, as specified for <basic-shape>, otherwise no Formal syntax <clip-source> | [ <basic-shape> | <geometry-box> ] | nonewhere <clip-source> = <url><basic-shape> = <inset
()> | <circle
()> | <ellipse
()> | <polygon
()> | <path
()><geometry-box> = <shape-box> | fill-box | stroke-box | view-boxwhere <inset
()> = inset( <length-percentage>{1,4} [ round <'border-radius'> ]? )<circle
()> = circle( [ <shape-radius> ]? [ at <position> ]? )<ellipse
()> = ellipse( [ <shape-radius>{2} ]? [ at <position> ]? )<polygon
()> = polygon( <fill-rule>? , [ <length-percentage> <length-percentage> ]# )<path
()> = path( [ <...
... ...
<image> - CSS: Cascading Style Sheets
The <image> CSS data type represents a two-dimensional image. Syntax The <image> data type can be represented with any of the following: An image denoted by the <url> data type A <gradient> data type A part of the webpage, defined by the element
() function An image, image fragment or solid patch of color, defined by the image
() function A blending of two or more images defined by the cross-fade
() function. A selection of images chosed based on resolution defined by the image-set
() function. Description CSS can handle the following kinds of images: Images with intrinsic dimensions (a natural size), like a JPEG, PNG, or other raster format. Images with multiple intrinsic dimensions, existing in multiple versions inside a single file, like some .ico formats. (In this case, the...
...describe it semantically in the document. MDN Understanding WCAG, Guideline 1.1 explanations Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0 Examples Valid images url(test.jpg) /* A <url>, as long as test.jpg is an actual image */ linear-gradient(blue, red) /* A <gradient> */ element(#realid) /* A part of the webpage, referenced with the element
() function, if "realid" is an existing ID on the page */ image(ltr 'arrow.png#xywh=0,0,16,16', red) /* A section 16x16 section of <url>, starting from the top, left of the original image as long as arrow.png is a supported image, otherwise a solid red swatch. If language is rtl, ...
...cross-fade(20% url(twenty.png), url(eighty.png)) /* cross faded images, with twenty being 20% opaque and eighty being 80% opaque. */ image-set('test.jpg' 1x, 'test-2x.jpg' 2x) /* a selection of images with varying resolutions */ Invalid images nourl.jpg /* An image file must be defined using the url
() function. */ url(report.pdf) /* A file pointed to by the url
() function must be an image. */ element(#fakeid) /* An element ID must be an existing ID on the page. */ image(z.jpg#xy=0,0) /* The spatial fragment must be written in the format of xywh=#,#,#,# */ image-set('cat.jpg' 1x, 'dog.jpg' 1x) /* every image in an image set must have a different resolutions */ Specifications ...
... on the page. */ image(z.jpg#xy=0,0) /* The spatial fragment must be written in the format of xywh=#,#,#,# */ image-set('cat.jpg' 1x, 'dog.jpg' 1x) /* every image in an image set must have a different resolutions */ Specifications Specification Status Comment CSS Images Module Level 4The definition of '<image>' in that specification. Working Draft Adds element
(), image
(), image-set
(), conic-gradient
(), repeating-conic-gradient
(), and image-resolution. CSS Images Module Level 3The definition of '<image>' in that specification. Candidate Recommendation Initial definition. Before this, there was no explicitly defined <image> data type. Images could only be defined using the url
() functional notation. ...
list-style-type - CSS: Cascading Style Sheets
<string> Th...
... <string> The specified string will be used as the item's marker. none No item marker is shown. ...
...VoiceOver and list-style-type: none - Unfettered Thoughts MDN Understanding WCAG, Guideline 1.3 explanations Understanding Success Criterion 1.3.1 | W3C Understanding WCAG 2.0 Formal definition Initial valuediscApplies tolist itemsInheritedyesComputed valueas specifiedAnimation typediscrete Formal syntax <counter-style> | <string> | nonewhere <counter-style> = <counter-style-name> | symbols
()where <counter-style-name> = <custom-ident> Examples Setting list item markers HTML List 1 <ol class="normal"> <li>Hello</li> <li>World</li> <li>What's up?</li> </ol> List 2 <ol class="shortcut"> <li>Looks</li> <li>Like</li> <li>The</li> <li>Same</li> </ol> CSS ol.normal { list-style-type: upper-alpha; } /* or use the shortcut "list-style": */ ol.shortcut { list-style: up...
... the usual style types: hebrew, cjk-ideographic, hiragana, hiragana-iroha, katakana, katakana-iroha, japanese-formal, japanese-informal, simp-chinese-formal, trad-chinese-formal, simp-chinese-formal, trad-chinese-formal,korean-hangul-formal, korean-hanja-informal, korean-hanja-formal, cjk-decimal, ethiopic-numeric, disclosure-open and disclosure-closed. Extends <counter-style> with the symbols
() functional notation. CSS Lists Module Level 3The definition of 'list-style-type' in that specification. Working Draft Modify syntax to support for identifiers used in @counter-style rules to keywords. Support for a simple <string>. CSS Level 2 (Revision 1)The definition of 'list-style-type' in that specification. Recommendation Initial definition ...
transition-delay - CSS: Cascading Style Sheets
ransition-property: width height background-color font-size left top color; -webkit-transition-duration:2s; -webkit-transition-delay:0.5s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:0.5s; transition-timing-function: linear; } function updateTransition
() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-delay: 1s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .box { wid...
...it-transition-property: width height background-color font-size left top color; -webkit-transition-duration:2s; -webkit-transition-delay:1s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:1s; transition-timing-function: linear; } function updateTransition
() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-delay: 2s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .box { wid...
...it-transition-property: width height background-color font-size left top color; -webkit-transition-duration:2s; -webkit-transition-delay:2s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:2s; transition-timing-function: linear; } function updateTransition
() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-delay: 4s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .box { wid...
...ion-property: width height background-color font-size left top color; -webkit-transition-duration:2s; -webkit-transition-delay:4s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:4s; transition-timing-function: ease-in-out; } function updateTransition
() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); Specifications Specification Status Comment CSS TransitionsThe definition of 'transition-delay' in that specifi...
transition-duration - CSS: Cascading Style Sheets
-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration:0.5s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transformv color; transition-duration:0.5s; transition-timing-function: ease-in-out; } function updateTransition
() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-duration: 1s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .box { ...
...ition-property: width height background-color font-size left top -webkit-transform transform color; -webkit-transition-duration:1s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration:1s; transition-timing-function: ease-in-out; } function updateTransition
() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-duration: 2s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .box { ...
...ition-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration:2s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration:2s; transition-timing-function: ease-in-out; } function updateTransition
() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); transition-duration: 4s <div class="parent"> <div class="box">Lorem</div> </div> .parent { width: 250px; height:125px;} .box { ...
...ition-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration:4s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration:4s; transition-timing-function: ease-in-out; } function updateTransition
() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000); Specifications Specification Status Comment CSS TransitionsThe definition of 'transition-duration' in that spec...
Media buffering, seeking, and time ranges - Developer guides
s 5 myAudio.buffered.start(1); // returns 15 myAudio.buffered.end(1); // returns 19 To try out and visualize buffered time ranges we can write a little bit of HTML: <p> <audio id="my-audio" controls> <source src="music.mp3" type="audio/mpeg"> </audio> </p> <p> <canvas id="my-canvas" width="300" height="20"> </canvas> </p> and a little bit of JavaScript: window.onload = function
(){ var myAudio = document.getElementById('my-audio'); var myCanvas = document.getElementById('my-canvas'); var context = myCanvas.getContext('2d'); context.fillStyle = 'lightgray'; context.fillRect(0, 0, myCanvas.width, myCanvas.height); context.fillStyle = 'red'; context.strokeStyle = 'white'; var inc = myCanvas.width / myAudio.duration; // display TimeRange...
...udio'); var myCanvas = document.getElementById('my-canvas'); var context = myCanvas.getContext('2d'); context.fillStyle = 'lightgray'; context.fillRect(0, 0, myCanvas.width, myCanvas.height); context.fillStyle = 'red'; context.strokeStyle = 'white'; var inc = myCanvas.width / myAudio.duration; // display TimeRanges myAudio.addEventListener('seeked', function
() { for (i = 0; i < myAudio.buffered.length; i++) { var startX = myAudio.buffered.start(i) * inc; var endX = myAudio.buffered.end(i) * inc; var width = endX - startX; context.fillRect(startX, 0, width, myCanvas.height); context.rect(startX, 0, width, myCanvas.height); context.stroke
(); } }); } This works better with longer pieces ...
... background: #555; width: 300px; } #buffered-amount { display: block; height: 100%; background-color: #777; width: 0; } .progress { margin-top: -20px; height: 20px; position: relative; width: 300px; } #progress-amount { display: block; height: 100%; background-color: #595; width: 0; } And the following JavaScript provides our functionality: window.onload = function
(){ var myAudio = document.getElementById('my-audio'); myAudio.addEventListener('progress', function
() { var duration = myAudio.duration; if (duration > 0) { for (var i = 0; i < myAudio.buffered.length; i++) { if (myAudio.buffered.start(myAudio.buffered.length - 1 - i) < myAudio.currentTime) { document.getElementById("buffered-amount").style.width = (...
... The timeupdate event is fired 4 times a second as the media plays and th...
<input type="checkbox"> - HTML: Hypertext Markup Language
s on and off. Where multiple controls exist, radio buttons allow one to be selected out of them all, whereas checkboxes allow multiple values to be selected. Value A DOMString representing the value of the checkbox. Events change and input Supported common attributes checked IDL attributes checked, indeterminate and value Methods select
() Value A DOMString representing the value of the checkbox. This is never seen on the client-side, but on the server this is the value given to the data submitted with the checkbox's name. Take the following example: <form> <div> <input type="checkbox" id="subscribeNews" name="subscribe" value="newsletter"> <label for="subscribeNews">Subscribe to newsletter?</label> </div> <d...
... three are checked, the recipe name's checkbox is set to checked. So in this case the indeterminate state is used to state that collecting the ingredients has started, but the recipe is not yet complete. ...
...edients has started, but the recipe is not yet complete. ...
... Living Standard HTML5The definition of '<input type="...
<input type="month"> - HTML: Hypertext Markup Language
own arrow on the right hand side brings up a date picker that lets you select the month and year. The Microsoft Edge month control looks like this: Value A DOMString representing a month and year, or empty. Events change and input Supported common attributes autocomplete, list, readonly, and step. IDL attributes value Methods select
(), stepDown
(), stepUp
(). Value A DOMString representing the value of the month and year entered into the input, in the form YYYY-MM (four or more digit year, then a hyphen ("-"), followed by the two-digit month). The format of the month string used by this input type is described in Format of a valid local month string in Date and time formats used in HTML. You can set a default value for ...
...or('#year'); var monthSelect = document.querySelector('#month'); // hide fallback initially fallbackPicker.style.display = 'none'; fallbackLabel.style.display = 'none'; // test whether a new date input falls back to a text input or not var test = document.createElement('input'); try { test.type = 'month'; } catch (e) { console.log(e.description); } // if it does, run the code inside the if
() {} block if(test.type === 'text') { // hide the native picker and show the fallback nativePicker.style.display = 'none'; fallbackPicker.style.display = 'block'; fallbackLabel.style.display = 'block'; // populate the years dynamically // (the months are always the same, therefore hardcoded) populateYears
(); } function populateYears
() { // get the current year as a number var da...
...You'll need to take this into consideration whe...
... S...
<menu> - HTML: Hypertext Markup Language
hr/> <menuitem>Separated action</menuitem> </menu> Result Toolbar Toolbar menus haven't been implemented in any known browsers yet. HTML <!-- A context menu for a simple editor, - containing two menu buttons. ...
... Result Toolbar Toolbar menus haven't been implemented in any known browsers yet. HTML <!-- A context menu for a simple editor, - containing two menu buttons. ...
... Living Standard No change from latest snapshot, Unknown HTML 5.1The definition of '<menu>...
...nu="file-menu">File</button> <menu type="context" id="file-menu"> <menuitem label="New..." onclick="newFile
()"> <menuitem label="Save..." onclick="saveFile
()"> </menu> </li> <li> <button type="menu" menu="edit-menu">Edit</button> <menu type="context" id="edit-menu"> <menuitem label="Cut..." onclick="cutEdit
()"> <menuitem label="Copy..." onclick="copyEdit
()"> <menuitem label="Paste..." onclick="pasteEdit
()"> </menu> </li> </menu> Result Specifications Specification Status Comment HTML Living StandardThe definition of '<menu>' in that specification. Living Standard No change from latest snapshot, Unknown HTML 5.1The definition of '<menu>' in that specification. Recommendation ...
Using the application cache - HTML: Hypertext Markup Language
noupdate event to the applicationCache object, and the update process is complete. Note that if you change any cached resources on the server, you must also change the manifest file itself, so that the browser knows it needs to fetch all the resources again. If the manifest file has changed, all the files listed in the manifest--as well as those added to the cache by calling applicationCache.add
()--are fetched into a temporary cache, following the appropriate HTTP caching rules. For each file fetched into this temporary cache, the browser sends a progress event to the applicationCache object. If any errors occur, the browser sends an error event, and the update halts. Once all the files have been successfully retrieved, they are moved into the real offline cache automatically, and a cache...
...he manifest is being fetched and checked for updates. DOWNLOADING Resources are being downloaded to be added to the cache, due to a changed resource manifest. UPDATEREADY There is a new version of the application cache available. There is a corresponding updateready event, which is fired instead of the cached event when a new update has been downloaded but not yet activated using the swapCache
() method. OBSOLETE The application cache group is now obsolete. Testing for updates to the cache manifest You can programmatically test to see if an application has an updated cache manifest file, using JavaScript. Since a cache manifest file may have been updated before a script attaches event listeners to test for updates, scripts should always test window.applicationCache.status. function ...
...OLETE The application cache group is now obsolete. Testing for updates to the cache manifest You can programmatically test to see if an application has an updated cache manifest file, using JavaScript. Since a cache manifest file may have been updated before a script attaches event listeners to test for updates, scripts should always test window.applicationCache.status. function onUpdateReady
() { console.log('found new version!'); } window.applicationCache.addEventListener('updateready', onUpdateReady); if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { onUpdateReady
(); } To manually start testing for a new manifest file, you can use window.applicationCache.update
(). Gotchas Never access cached files by using traditional GET parameters (like other-cach...
...he link, such as other-cached-page.html#whatever?parameterName=value. When applications are cached, simply updating the resources (files) that are used in a web page is not enough to update the files that have been cached. You must update the cache manifest file itself before the browser retrieves and uses the updated files. You can do this programmatically using window.applicationCache.swapCache
(), though resources that have already been loaded will not be affected. To make sure that resources are loaded from a new version of the application cache, refreshing the page is ideal. It's a good idea to set expires headers on your web server for *.appcache files to expire immediately. This avoids the risk of caching manifest files. For example, in Apache you can specify such a configuration as ...
Browser detection using the user agent - HTTP
What you want to do for screen size is not slash off information on smaller screens. That will only annoy people because it will force them to use the desktop version. Rather, try to have fewer columns of information in a longer page on smaller screens while having more columns with a shorter page on larger screen sizes. This effect can be easily achi...
...ample, Webkit 6 has a bug whereby when the device orientation changes, the browser might not fire MediaQueryList listeners when it should. To overcome this bug, observe the code below. ...
...nt, isWebkit=/\b(iPad|iPhone|iPod)\b/.test(UA) && /WebKit/.test(UA) && !/Edge/.test(UA) && !window.MSStream; var mediaQueryUpdated = true, mqL = []; function whenMediaChanges
(){mediaQueryUpdated = true} var listenToMediaQuery = isWebkit ? function(mQ, f) { if(/height|width/.test(mQ.media)) mqL.push([mQ, f]); mQ.addListener(f), mQ.addListener(whenMediaChanges); } : function
(){}; var destroyMediaQuery = isWebkit ? ...
...t(mQ.media)) mqL.push([mQ, f]); mQ.addListener(f), mQ.addListener(whenMediaChanges); } : function
(){}; var destroyMediaQuery = isWebkit ? function(mQ) { for (var i=0,len=mqL.length|0; i<len; i=i+1|0) if (mqL[i][0] === mQ) mqL.splice(i, 1); mQ.removeListener(whenMediaChanges); } : listenToMediaQuery; var orientationChanged = false; addEventListener("orientationchange", function
(){ orientationChanged = true; }, PASSIVE_LISTENER_OPTION); addEventListener("resize", setTimeout.bind(0,function
(){ if (orientationChanged && !mediaQueryUpdated) for (var i=0,len=mqL.length|0; i<len; i=i+1|0) mqL[i][1]( mqL[i][0] ); mediaQueryUpdated = orientationChanged = false; },0)); Which part of the user agent contains the information you are looking for? As ...
CSP: script-src - HTTP
be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval
() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> e...
...sample of the violating code to be included in the violation report. Examples Violation case Given this CSP header: Content-Security-Policy: script-src https://example.com/ the following script is blocked and won't be loaded or executed: <script src="https://not-example.com/js/library.js"></script> Note that inline event handlers are blocked as well: <button id="btn" onclick="doSomething
()"> You should replace them with addEventListener calls: document.getElementById("btn").addEventListener('click', doSomething); Unsafe inline script Note: Disallowing inline styles and inline scripts is one of the biggest security wins CSP provides. However, if you absolutely have to use it, there are a few mechanisms that will allow them. To allow inline scripts and inline event handlers, '...
...tags and note that capitalization and whitespace matter, including leading or trailing whitespace. <script>var inline = 1;</script> Unsafe eval expressions The 'unsafe-eval' source expression controls several script execution methods that create code from strings. ...
...e that capitalization and whitespace matter, including leading or trailing whitespace. <script>var inline = 1;</script> Unsafe eval expressions The 'unsafe-eval' source expression controls several script execution methods that create code from strings. ...
Keyed collections - JavaScript
ECMAScript 2015 introduces a new data structure to map values to values. A Map object is a simple key/value map and can iterate its elements in insertion order. The following code shows some basic operations with a Map. See also the Map reference page for more examples and the complete API. You can use a for...of loop to return an array of [key, value] for each iteration. ...
...Objects allow you to set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Map objects, however, have a few more advantages that make them better maps. ...
... example is from Nick Fitzgerald's blog post "Hiding Implementation Details with ECMAScript 6 WeakMaps". The private data and methods belong inside the object and are stored in the privates WeakMap object. Everything exposed on the instance and prototype is public; everything else is inaccessible from the outside world because privates is not exported from the module. const privates = new WeakMap
(); function Public
() { const me = { // Private data goes here }; privates.set(this, me); } Public.prototype.method = function
() { const me = privates.get(this); // Do stuff with private data in `me`... }; module.exports = Public; Sets Set object Set objects are collections of values. You can iterate its elements in insertion order. A value in a Set may only occur once; it is un...
... stuff with private data in `me`... }; module.exports = Public; Sets Set object Set objects are collections of values. You can iterate its elements in insertion order. A value in a Set may only occur once; it is unique in the Set's collection. The following code shows some basic operations with a Set. See also the Set reference page for more examples and the complete API. let mySet = new Set
(); mySet.add(1); mySet.add('some text'); mySet.add('foo'); mySet.has(1); // true mySet.delete('foo'); mySet.size; // 2 for (let item of mySet) console.log(item); // 1 // "some text" Converting between Array and Set You can create an Array from a Set using Array.from or the spread operator. Also, the Set constructor accepts an Array to convert in the other direction. Note: Remember that Set o...
ReferenceError: can't access lexical declaration`X' before initialization - JavaScript
ization (Firefox) ReferenceError: 'x' is not defined (Chrome) Error type ReferenceError What went wrong? A lexical variable was accessed before it was initialized. This happens within any block statement, when let or const declarations are accessed before they are defined. ...
...lized. This happens within any block statement, when let or const declarations are accessed before they are defined. Examples Invalid cases In this case, the variable "foo" is redeclared in the block statement using let. ...
...lid cases In this case, the variable "foo" is redeclared in the block statement using let. ...
...statement using let. function test
() { let foo = 33; if (true) { let foo = (foo + 55); // ReferenceError: can't access lexical // declaration `foo' before initialization } } test
(); Valid cases To change "foo" inside the if statement, you need to remove the let that causes the redeclaration. ...
TypeError: can't define property "x": "obj" is not extensible - JavaScript
Usually, an object is extensible and new properties can be added to it. ...
...-extensible. Message TypeError: Cannot create property for a non-extensible object (Edge) TypeError: can't define property "x": "obj" is not extensible (Firefox) TypeError: Cannot define property: "x", object is not extensible. (Chrome) Error type TypeError What went wrong? Usually, an object is extensible and new properties can be added to it. However, in this case Object.preventExtensions
() marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. Examples Adding new properties to a non-extensible objects In strict mode, attempting to add new properties to a non-extensible object throws a TypeError. In sloppy mode, the addition of the "x" property is silently ignored. 'use strict'; var obj...
...-extensible objects In strict mode, attempting to add new properties to a non-extensible object throws a TypeError. In sloppy mode, the addition of the "x" property is silently ignored. ...
...Of course you can also remove the property that was attempted to be added, if you don't need it. ...
ReferenceError: "x" is not defined - JavaScript
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. ...
... 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 all variables and functions defined inside the scope in which it is defined. ...
...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. ...
... 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 ...
ReferenceError: assignment to undeclared variable "x" - JavaScript
erty of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted). For more details and examples, see the var reference page. Errors about undeclared variable assignments occur in strict mode code only. ...
...n or global). Undeclared variables are configurable (e.g. can be deleted). For more details and examples, see the var reference page. Errors about undeclared variable assignments occur in strict mode code only. ...
...e assignments occur in strict mode code only. In non-strict code, they are silently ignored. Examples Invalid cases In this case, the variable "bar" is an undeclared variable. ...
.... In non-strict code, they are silently ignored. Examples Invalid cases In this case, the variable "bar" is an undeclared variable. ...
Rest parameters - JavaScript
ers have been introduced to reduce the boilerplate code that was induced by the arguments // Before rest parameters, "arguments" could be converted to a normal array using: function f(a, b) { let normalArray = Array.prototype.slice.call(arguments) // -- or -- let normalArray = [].slice.call(arguments) // -- or -- let normalArray = Array.from(arguments) let first = normalArray.shift
() // OK, gives the first argument let first = arguments.shift
() // ERROR (arguments is not a normal array) } // Now, you can easily gain access to a normal array using a rest parameter function f(...args) { let normalArray = args let first = normalArray.shift
() // OK, gives the first argument } Examples Using rest parameters In this example, the first argument is mapped to a and the...
...s, [three] Below, the third argument isn't provided, but manyMoreArgs is still an array (albeit an empty one). // using the same function definition from example above myFun("one", "two") // a, one // b, two // manyMoreArgs, [] Argument length Since theArgs is an array, a count of its elements is given by the length property: function fun1(...theArgs) { console.log(theArgs.length) } fun1
() // 0 fun1(5) // 1 fun1(5, 6, 7) // 3 Ordinary parameter and rest parameters In the next example, a rest parameter is used to collect all parameters after the first into an array. Each one of them is then multiplied by the first parameter, and the array is returned: function multiply(multiplier, ...theArgs) { return theArgs.map(element => { return multiplier * element }...
... function sortArgumen...
...map(element => { return multiplier * element }) } let arr = multiply(2, 1, 2, 3) console.log(arr) // [2, 4, 6] Use with the arguments object Array methods can be used on rest parameters, but not on the arguments object: function sortRestArgs(...theArgs) { let sortedArgs = theArgs.sort
() return sortedArgs } console.log(sortRestArgs(5, 3, 7, 1)) // 1, 3, 5, 7 function sortArguments
() { let sortedArgs = arguments.sort
() return sortedArgs // this will never happen } console.log(sortArguments(5, 3, 7, 1)) // throws a TypeError (arguments.sort is not a function) To use Array methods on the arguments object, it must be converted to a real array first. function sortArguments
() { let args = Array.from(arguments) let sortedArgs = args.sort
() return sortedArgs } consol...
AsyncFunction - JavaScript
argN Names to be used by the function as formal argument names. ...
...heir 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. ...
...structor 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. ...
...oking the AsyncFunction constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. Examples Creating an async function from an AsyncFunction
() constructor function resolveAfter2Seconds(x) { return new Promise(resolve => { setTimeout(
() => { resolve(x); }, 2000); }); } let AsyncFunction = Object.getPrototypeOf(async function
(){}).constructor let a = new AsyncFunction('a', 'b', 'return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);'); a(10, 20).then(v => { console.log(v); // prints 30 after 4 seconds }); Specifications Specification ECMAScript (ECMA-262)The definition of 'AsyncFunction object' in that specification. ...
Function - JavaScript
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. ...
...[, ...argN]]]) Creates a new function which, when called, has its this set to the provided thisArg. Optionally, a given sequence of arguments will be prepended to arguments provided the newly-bound function is called. Function.prototype.call(thisArg[, arg1, arg2, ...argN]) Calls a function and sets its this to the provided value. 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 lo...
...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. ...
...ope. 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
() { var x = 20; function f
() { return x; // this |x| refers local |x| above } return f; } var f1 = createFunction1
(); console.log(f1
()); // 10 var f2 = createFunction2
(); console.log(f2
()); // 20 While this code works in web browsers, f1
() will produce a ReferenceError in Node.js, as x will not be found. This is because the top-level scope in Node is not...
Intl.RelativeTimeFormat - JavaScript
The Intl.RelativeTimeFormat object enables language-sensitive relative time formatting. 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. Constructor Intl.RelativeTimeFormat.RelativeTimeFormat
() Creates a new Intl.RelativeTimeFormat object. ...
...g. 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. Constructor Intl.RelativeTimeFormat.RelativeTimeFormat
() Creates a new Intl.RelativeTimeFormat object. ...
...d send us a pull request. Constructor Intl.RelativeTimeFormat.RelativeTimeFormat
() Creates a new Intl.RelativeTimeFormat object. Static methods Intl.RelativeTimeFormat.supportedLocalesOf
() Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. Instance methods Intl.RelativeTimeFormat.prototype.format
() Formats a value and a unit according to the locale and formatting options of the given Intl.RelativeTimeFormat object. Intl.RelativeTimeFormat.prototype.formatToParts
() Returns an Array of objects representing the relative time format in parts that can be used for custom locale-aware formatting. ...
... Examples Basic format usage The following example shows how to use a relative time formatter for the English language. // Create a relative time formatter in your locale // with default values explicitly passed in. ...
Proxy - JavaScript
Handler functions are sometimes called traps, presumably because they trap calls to the target object. The very simple trap in handler2 above redefines all property accessors: console.log(proxy2.message1); // world console.log(proxy2.message2); // world With the help of the Reflect class we can give some accessors the origi...
... Examples Basic example In this simple example, the number 37 gets returned as the default value when the property name is not in the object. It is using the get handler. const handler = { get: function(obj, prop) { return prop in obj ? obj[prop] : 37; } }; const p = new ...
...age2: "everyone" }; const handler3 = { get: function (target, prop, receiver) { if (prop === "message2") { return "world"; } return Reflect.get(...arguments); }, }; const proxy3 = new Proxy(target, handler3); console.log(proxy3.message1); // hello console.log(proxy3.message2); // world Constructor Proxy
() Creates a new Proxy object. Static methods Proxy.revocable
() Creates a revocable Proxy object. Examples Basic example In this simple example, the number 37 gets returned as the default value when the property name is not in the object. It is using the get handler. const handler = { get: function(obj, prop) { return prop in obj ? obj[prop] : 37; } }; const p = new Proxy({}, handler); p.a = 1; p.b = undefined; console.log(p.a, p.b...
...ey) { return oTarget[sKey] || oTarget.getItem(sKey) || undefined; }, set: function (oTarget, sKey, vValue) { if (sKey in oTarget) { return false; } return oTarget.setItem(sKey, vValue); }, deleteProperty: function (oTarget, sKey) { if (sKey in oTarget) { return false; } return oTarget.removeItem(sKey); }, enumerate: function (oTarget, sKey) { return oTarget.keys
(); }, ownKeys: function (oTarget, sKey) { return oTarget.keys
(); }, has: function (oTarget, sKey) { return sKey in oTarget || oTarget.hasItem(sKey); }, defineProperty: function (oTarget, sKey, oDesc) { if (oDesc && 'value' in oDesc) { oTarget.setItem(sKey, oDesc.value); } return oTarget; }, getOwnPropertyDescriptor: function (oTarget, sKey) { var vValue = oTarget...
Reflect - JavaScript
g static functions which have the same names as the proxy handler methods. Some of these methods are also the same as corresponding methods on Object, although they do have some subtle differences between them. Static methods Reflect.apply(target, thisArgument, argumentsList) Calls a target function with arguments as specified by the argumentsList parameter. See also Function.prototype.apply
(). Reflect.construct(target, argumentsList[, newTarget]) The new operator as a function. Equivalent to calling new target(...argumentsList). Also provides the option to specify a different prototype. Reflect.defineProperty(target, propertyKey, attributes) Similar to Object.defineProperty
(). Returns a Boolean that is true if the property was successfully defined. Reflect.deleteProperty(target, ...
...fined. Reflect.deleteProperty(target, propertyKey) The delete operator as a function. Equivalent to calling delete target[propertyKey]. Reflect.get(target, propertyKey[, receiver]) Returns the value of the property. Works like getting a property from an object (target[propertyKey]) as a function. Reflect.getOwnPropertyDescriptor(target, propertyKey) Similar to Object.getOwnPropertyDescriptor
(). Returns a property descriptor of the given property if it exists on the object, undefined otherwise. Reflect.getPrototypeOf(target) Same as Object.getPrototypeOf
(). Reflect.has(target, propertyKey) Returns a Boolean indicating whether the target has the property. Either as own or inherited. Works like the in operator as a function. Reflect.isExtensible(target) Same as Object.isExtensible(...
...Returns a Boolean that is true if the update was successful. Reflect.set(target, propertyKey, value[, receiver]) A function that assigns values to properties. Returns a Boolean that is true if the update was successful. ...
...function that assigns values to properties. Returns a Boolean that is true if the update was successful. Reflect.setPrototypeOf(target, prototype) A function that sets the prototype of an object. Returns a Boolean that is true if the update was successful. ...
Symbol.search - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
... 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. ...
... 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. ...
... examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Property attributes of Symbol.search Writable no Enumerable no Configurable no Examples Custom string search class caseInsensitiveSearch { constructor(value) { this.value = value.toLowerCase
(); } [Symbol.search](string) { return string.toLowerCase
().indexOf(this.value); } } console.log('foobar'.search(new caseInsensitiveSearch('BaR'))); // expected output: 3 Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.search' in that specification. ...
Symbol.split - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
... 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. ...
... 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. ...
...ease clone https://github.com/mdn/interactive-examples and send us a pull request. Property attributes of Symbol.split Writable no Enumerable no Configurable no Examples Custom reverse split class ReverseSplit { [Symbol.split](string) { const array = string.split(' '); return array.reverse
(); } } console.log('Another one bites the dust'.split(new ReverseSplit
())); // expected output: [ "dust", "the", "bites", "one", "Another" ] Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.split' in that specification. ...
globalThis - JavaScript
t syntax in different JavaScript environments. On the web you can use window, self, or frames - but in Web Workers only self will work. In Node.js none of these work, and you must instead use global. The this keyword could be used inside functions running in non-strict mode, but this will be undefined in Modules and inside functions running in strict mode. You can also use Function('return this')
(), but environments that disable eval
(), like CSP in browsers, prevent use of Function in this way. The globalThis property provides a standard way 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 ...
...other popular name choices such as self and global were removed from consideration because of their potential to break compatibility with existing code. See the language proposal's "naming" document for more details. Examples Search for the global across environments Prior to globalThis, the only reliable cross-platform way to get the global object for an environment was Function('return this')
(). ...
...with existing code. See the language proposal's "naming" document for more details. Examples Search for the global across environments Prior to globalThis, the only reliable cross-platform way to get the global object for an environment was Function('return this')
(). ...
...ion('return this')
(). ...
Optional chaining (?.) - JavaScript
n be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device. Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found: let result = someInterface.customMethod?.
(); Note: If there is a property with such a name and which is not a function, using ?. will still raise a TypeError exception (someInterface.customMethod is not a function). Note: If someInterface itself is null or undefined, a TypeError exception will still be raised (someInterface is null). If you expect that someInterface itself may be null or undefined, you have to use ?. at this position ...
...such a name and which is not a function, using ?. will still raise a TypeError exception (someInterface.customMethod is not a function). Note: If someInterface itself is null or undefined, a TypeError exception will still be raised (someInterface is null). If you expect that someInterface itself may be null or undefined, you have to use ?. at this position as well: someInterface?.customMethod?.
() Dealing with optional callbacks or event handlers If you use callbacks or fetch methods from an object with a destructuring assignment, you may have non-existent values that you cannot call as functions unless you have tested their existence. Using ?., you can avoid this extra test: // Written as of ES2019 function doSomething(onContent, onError) { try { // ... do something with the dat...
...he left-hand side of an assignment let object = {}; object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment Array item access with optional chaining let arrayItem = arr?.[42]; Examples Basic example This example looks for the value of the name property for the member bar in a map when there is no such member. The result is therefore undefined. let myMap = new Map
(); myMap.set("foo", {name: "baz", desc: "inga"}); let nameBar = myMap.get("bar")?.name; Short-circuiting evaluation When using optional chaining with expressions, if the left operand is null or undefined, the expression will not be evaluated. For instance: let potentiallyNullObj = null; let x = 0; let prop = potentiallyNullObj?.[x++]; console.log(x); // 0 as x was not incremented Stacking th...
...cking the optional chaining operator With nested structures, it is possible to use optional chaining multiple times: let customer = { name: "Carl", details: { age: 82, location: "Paradise Falls" // detailed address is unknown } }; let customerCity = customer.details?.address?.city; // ... ...
new operator - JavaScript
specifies its name and properties. An object can have a property that is itself another object. See the examples below. When the code new Foo(...) is executed, the following things happen: A new object is created, inheriting from Foo.prototype. The constructor function Foo is called with the specified arguments, and with this bound to the newly created object. new Foo is equivalent to new Foo
(), i.e. if no argument list is specified, Foo is called without arguments. The object (not null, false, 3.1415 or other primitive types) returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to...
...Function.prototype property. This defines a property that is shared by all objects created with that function, rather than by just one instance of the object type. The following code adds a color property with value "original color" to all objects of type Car, and then overwrites that value with the string "black" only in the instance object car1. For more information, see prototype. ...
...roperty. This defines a property that is shared by all objects created with that function, rather than by just one instance of the object type. The following code adds a color property with value "original color" to all objects of type Car, and then overwrites that value with the string "black" only in the instance object car1. For more information, see prototype. ...
...nes a property that is shared by all objects created with that function, rather than by just one instance of the object type. The following code adds a color property with value "original color" to all objects of type Car, and then overwrites that value with the string "black" only in the instance object car1. For more information, see prototype. ...
Transitioning to strict mode - JavaScript
Declaring two function parameters with the same name function f(a, b, b) {} These errors are good, because they reveal plain errors or bad practices. They occur before the code is running. New runtime errors J...
...tradiction with the user expectation. Poisoned arguments and function properties Accessing arguments.callee, arguments.caller, anyFunction.caller, or anyFunction.arguments throws an error in strict mode. ...
...callee, arguments.caller, anyFunction.caller, or anyFunction.arguments throws an error in strict mode. The only legitimate use case would be to reuse a function as in: // example taken from vanillajs: http://vanilla-js.com/ var s = document.getElementById('thing').style; s.opacity = 1; (function
() { if ((s.opacity-=.1) < 0) s.display = 'none'; else setTimeout(arguments.callee, 40); })
(); which can be rewritten as: 'use strict'; var s = document.getElementById('thing').style; s.opacity = 1; (function fadeOut
() { // name the function if((s.opacity-=.1) < 0) s.display = 'none'; else setTimeout(fadeOut, 40); // use the name of the function })
(); Semantic differences These differences are very subtle differences. It's possible that a test suite doesn't catch this kind...
...ferences These differences are very subtle differences. It's possible that a test suite doesn't catch this kind of subtle difference. Careful review of your code base will probably be necessary to be sure these differences don't affect the semantics of your code. Fortunately, this careful review can be done gradually down the function granularity. this in function calls In function calls like f
(), the this value was the global object. In strict mode, it is now undefined. When a function was called with call or apply, if the value was a primitive value, this one was boxed into an object (or the global object for undefined and null). In strict mode, the value is passed directly without conversion or replacement. arguments doesn't alias named function arguments In non-strict mode, modifyin...
Performance fundamentals - Web Performance
ly discarded, in the case of Firefox OS (see the note below). This in turn means they "start up" faster (since they are already running) and have better UPP. Specific coding tips for application performance The following practical tips will help improve one or more of the Application performance factors discussed above. Use CSS animations and transitions Instead of using some library's animate
() function, which probably currently uses many badly performing technologies (window.setTimeout
() or top/left positioning, for example) use CSS animations. In many cases, you can actually use CSS Transitions to get the job done. This works well because the browser is designed to optimize these effects and use the GPU to handle them smoothly with minimal impact on processor performance. Another bene...
...ent. The reason is, once again, hardware acceleration. The browser can do these tasks on your GPU, letting the CPU handle other things. In addition, transforms give you capabilities you might not otherwise have. Not only can you translate elements in 2D space, but you can transform in three dimensions, skew and rotate, and so forth. Paul Irish has an in-depth analysis of the benefits of translate
() from a performance point of view. In general, however, you have the same benefits you get from using CSS animations: you use the right tool for the job and leave the optimization to the browser. You also use an easily extensible way of positioning elements -- something that needs a lot of extra code if you simulate translation with top and left positioning. Another bonus is that this is just like...
...king in a canvas element. Note: You may need to attach a translateZ(0.1) transform if you wish to get hardware acceleration on your CSS animations, depending on platform. As noted above, this can improve performance, but can also have memory consumption issues. What you do in this regard is up to you -- do some testing and find out what's best for your particular app. Use requestAnimationFrame
() instead of setInterval
() Calls to window.setInterval
() run code at a presumed frame rate that may or may not be possible under current circumstances. It tells the browser to render results even while the browser isn't actually drawing; that is, while the video hardware hasn't reached the next display cycle. This wastes processor time and can even lead to reduced battery life on the user's device...
...ode at a presumed frame rate that may or may not be possible under current circumstances. It tells the browser to render results even while the browser isn't actually drawing; that is, while the video hardware hasn't reached the next display cycle. This wastes processor time and can even lead to reduced battery life on the user's device. Instead, you should try to use window.requestAnimationFrame
(). This waits until the browser is actually ready to start building the next frame of your animation, and won't bother if the hardware isn't going to actually draw anything. Another benefit to this API is that animations won't run while your app isn't visible on the screen (such as if it's in the background and some other task is operating). This will save battery life and prevent users from cursin...
Add to Home screen - Progressive web apps (PWAs)
tton initially because the PWA will not be available for install until it follows the A2HS criteria. When this happens, supporting browsers will fire a beforeinstallprompt event. ...
...lly showing the prompt e.preventDefault
(); // Stash the event so it can be triggered later. ...
... Store the event object in the deferredPrompt variable so it can be used later on to perform the actual installation. Set the button to display: block so it appears in the UI for the user to click. Set a click handler for the button. ...
.... Store the event object in the deferredPrompt variable so it can be used later on to perform the actual installation. Set the button to display: block so it appears in the UI for the user to click. Set a click handler for the button. The click handler contains the following steps: Hide the button again with display: none -- it is no longer needed once the app is installed. Use the prompt
() method available on the beforeinstallprompt event object (stored in deferredPrompt) to trigger showing the install prompt. Respond to the user's interaction with the prompt using the userChoice property, again available on the beforeinstallprompt event object. Set deferredPrompt to null since it is no longer needed. So when the button is clicked, the install prompt appears. If the user sel...
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
Its contents reside in the sw.js file, and can be executed after the registration is successful. It's the only piece of Service Worker code that sits inside the app.js file; everything else that is Service Worker-specific is written in the sw.js file itself. Lifecycle of a Service Worker When registration is complete, the sw.js file is automatically downloaded, then installed, and final...
...s/icon-128.png', '/pwa-examples/js13kpwa/icons/icon-168.png', '/pwa-examples/js13kpwa/icons/icon-192.png', '/pwa-examples/js13kpwa/icons/icon-256.png', '/pwa-examples/js13kpwa/icons/icon-512.png' ]; Next, the links to images to be loaded along with the content from the data/games.js file are generated in the second array. After that, both arrays are merged using the Array.prototype.concat
() function. var gamesImages = []; for(var i=0; i<games.length; i++) { gamesImages.push('data/img/'+games[i].slug+'.jpg'); } var contentToCache = appShellFiles.concat(gamesImages); Then we can manage the install event itself: self.addEventListener('install', (e) => { console.log('[Service Worker] Install'); e.waitUntil( caches.open(cacheName).then((cache) => { console.log('[Se...
...If not, we use another fetch request to fetch it from the network, then store the response in the cache so it will be available there next time it is requested. The FetchEvent.respondWith method...
...d in the background, and the previous one (v1) works correctly up until there are no pages using it -- the new Service Worker is then activated and takes over management of the page from the old one. Clearing the cache Remember the activate event we skipped? It can be used to clear out the old cache we don't need anymore: self.addEventListener('activate', (e) => { e.waitUntil( caches.keys
().then((keyList) => { return Promise.all(keyList.map((key) => { if(key !== cacheName) { return caches.delete(key); } })); }) ); }); This ensures we have only the files we need in the cache, so we don't leave any garbage behind; the available cache space in the browser is limited, so it is a good idea to clean up after ourselves. Other use cases Ser...
begin - SVG: Scalable Vector Graphics
roll, beginEvent, endEvent, and repeatEvent. An optional offset value as defined in <offset-value> can be appended. <repeat-value> This value defines a qualified repeat event. The element animation start time is defined relative to the time that the repeat event is raised with the specified iteration value. ...
...by a dot and the function repeat
() with an integer value specifying the number of repetitions as parameter. An optional offset value as defined in <offset-value> can be appended. <accessKey-value> This value defines an access key that should trigger the animation. The element animation will begin when the user presses the specified key. A valid accessKey-value consists of the function accessKey
() with the character to be input as parameter. An optional offset value as defined in <offset-value> can be appended. <wallclock-sync-value> This value defines the animation start time as a real-world clock time. A valid wallclock-sync-value consists of the function wallclock
() with a time value as parameter. The time syntax is based upon the syntax defined in ISO 8601. indefinite The begin of...
...tional offset value as defined in <offset-value> can be appended. <wallclock-sync-value> This value defines the animation start time as a real-world clock time. A valid wallclock-sync-value consists of the function wallclock
() with a time value as parameter. The time syntax is based upon the syntax defined in ISO 8601. indefinite The begin of the animation will be determined by a beginElement
() method call or a hyperlink targeted to the element. discard For <discard>, begin defines when the target element will be discarded. ...
... After removal of the target element, the <discard> element is no longer useful, therefore it is also discarded after the target element's removal. If the href attribute has an invalid URL reference (e.g. ...
Using templates and slots - Web Components
ent); Although trivial, you can already start to see how this could be useful. Using templates with web components Templates are useful on their own, but they work even better with web components. Let's define a web component that uses our template as the content of its shadow DOM. We'll call it <my-paragraph>: customElements.define('my-paragraph', class extends HTMLElement { constructor
() { super
(); let template = document.getElementById('my-paragraph'); let templateContent = template.content; const shadowRoot = this.attachShadow({mode: 'open'}) .appendChild(templateContent.cloneNode(true)); } } ); The key point to note here is that we append a clone of the template content to the shadow root, created using the Node.cloneNode
() method. And ...
...etails> element from the <template> Next, let's create a new custom element named <element-details> and use Element.attachShadow to attach to it, as its shadow root, that document fragment we created with our <template> element above. This uses exactly the same pattern as we saw in our earlier trivial example. ...
...from the <template> Next, let's create a new custom element named <element-details> and use Element.attachShadow to attach to it, as its shadow root, that document fragment we created with our <template> element above. This uses exactly the same pattern as we saw in our earlier trivial example. ...
...an slot="element-name">template</span> <span slot="description">A mechanism for holding client- side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaScript.</span> </element-details> <script> customElements.define('element-details', class extends HTMLElement { constructor
() { super
(); const template = document .getElementById('element-details-template') .content; const shadowRoot = this.attachShadow({mode: 'open'}) .appendChild(template.cloneNode(true)); } }) </script> </body> </html> ...
Cross-domain Content Scripts - Archive of obsolete content
" and adds a content script "panel-script.js" to it sends the panel a "show" message when it is shown adds a button which shows the panel when it is clicked // main.js var data = require("sdk/self").data; var forecast_panel = require("sdk/panel").Panel({ height: 50, contentURL: data.url("panel.html"), contentScriptFile: data.url("panel-script.js") }); forecast_panel.on("show", function
(){ forecast_panel.port.emit("show"); }); require("sdk/ui/button/action").ActionButton({ id: "get-forecast", label: "Get the forecast", icon: "./icon-16.png", onClick: function
() { forecast_panel.show
(); } }); The "panel.html" just includes a <div> block for the forecast: <!DOCTYPE html> <!-- panel.html --> <html> <head></head> <body> <div id="forecast_summary"></div> ...
...des a <div> block for the forecast: <!DOCTYPE html> <!-- panel.html --> <html> <head></head> <body> <div id="forecast_summary"></div> </body> </html> The "panel-script.js" uses XMLHttpRequest to fetch the latest forecast: // panel-script.js var url = "http://datapoint.metoffice.gov.uk/public/data/txt/wxfcs/regionalforecast/json/500?key=YOUR-API-KEY"; self.port.on("show", function
() { var request = new XMLHttpRequest
(); request.open("GET", url, true); request.onload = function
() { var jsonResponse = JSON.parse(request.responseText); var summary = getSummary(jsonResponse); var element = document.getElementById("forecast_summary"); element.textContent = summary; }; request.send
(); }); function getSummary(forecast) { return forecast.RegionalFcst.Fc...
... ...
Reddit Example - Archive of obsolete content
t of the Reddit page which intercepts mouse clicks on each title link and fetches the link's target URL. The content script then needs to send the URL to the add-on script. ...
... intercepts mouse clicks on each title link and fetches the link's target URL. The content script then needs to send the URL to the add-on script. ...
...sn't on a link. if (t.nodeName != "A") return; // Don't intercept the click if it was on one of the links in the header // or next/previous footer, since those links should load in the panel itself. if ($(t).parents('#header').length || $(t).parents('.nextprev').length) return; // Intercept the click, passing it to the addon, which will load it in a tab. event.stopPropagation
(); event.preventDefault
(); self.port.emit('click', t.toString
()); }); This script uses jQuery to interact with the DOM of the page and the self.port.emit function to pass URLs back to the add-on script. To run this example you'll also have to have an icon file named "icon-16.png" saved in your add-on's "data" directory. You could download this icon: . ...
self - Archive of obsolete content
es: access to the options object access to the port object access to a mostly deprecated messaging API For an overview of content scripts, see the main article. Note that the self object in content scripts is completely different from the self module, which provides an API for an add-on to access its data files and ID. self Properties options Content-scripting APIs such as tab.attach
(), page-mod, and page-worker let you pass read-only data to the content script as a JSON object via the contentScriptOptions option. If you do this, the data is available to the content script in the options property of self: // main.js const tabs = require("sdk/tabs"); tabs.open({ url: "./page.html", onReady: function(tab) { tab.attach({ contentScriptFile: "./content-script.js", ...
...s to, the main add-on code. See the documentation for port. Methods The self object has four methods, which enable the content script to send messages to, and receive messages from, the main add-on code. This is an older API than the API provided by port, and for most purposes the port API is a better choice. The exception is the context-menu module, which still uses postMessage. ...
...older API than the API provided by port, and for most purposes the port API is a better choice. The exception is the context-menu module, which still uses postMessage. postMessage
() Send a message from a content script to a listener in the main add-on code: self.postMessage(contentScriptMessage); This takes a single parameter, the message payload, which may be any JSON-serializable value. on
() Start listening to messages from the main add-on code: self.on("message", function(addonMessage) { // Handle the message }); This takes two parameters: the name of the event, and the handler function. The handler function is passed the message payload. once
() Exactly like on
(), but stop listening after the first message is received. removeListener
() Remove a listener to an event. This ta...
self - Archive of obsolete content
n's package.json file. data The data object is used to access data that was bundled with the add-on. This data lives in the add-on's data/ directory, immediately below the package.json file. All files in this directory will be copied into the XPI and made available through the data object. The Package Specification article explains the package.json file. Methods data.load(name) The data.load
() method returns the contents of an embedded data file, as a string. It is most useful for data that will be modified or parsed in some way, such as JSON, XML, plain text, or perhaps an HTML template. For data that can be displayed directly in a content frame, use data.url
(). Parameters name : string The filename to be read, relative to the package's data directory. Each package that uses the se...
...dified or parsed in some way, such as JSON, XML, plain text, or perhaps an HTML template. For data that can be displayed directly in a content frame, use data.url
(). Parameters name : string The filename to be read, relative to the package's data directory. Each package that uses the self module will see its own data directory. Returns string : the file contents. data.url(name) The data.url
() method returns a resource:// url that points at an embedded data file. It is most useful for data that can be displayed directly in a content frame. ...
...ontents. data.url(name) The data.url
() method returns a resource:// url that points at an embedded data file. It is most useful for data that can be displayed directly in a content frame. The url can be passed to a content frame constructor, such as the Panel: var self = require("sdk/self"); var myPanel = require("sdk/panel").Panel({ contentURL: self.data.url("myFile.html") }); myPanel.show
(); From Firefox 34, you can use "./myFile.html" as an alias for self.data.url("myFile.html"). So you can rewrite the above code like this: var myPanel = require("sdk/panel").Panel({ contentURL: "./myFile.html" }); myPanel.show
(); Parameters name : string The filename to be read, relative to the package's data directory. Each package that uses the self module will see its own data directo...
simple-prefs - Archive of obsolete content
ment", "value": "N", "options": [ { "value": "L", "label": "Lawful" }, { "value": "N", "label": "Neutral" }, { "value": "C", "label": "Chaotic" } ] } control Displays a button. ...
...See the localization tutorial for more details. Getting and setting preferences Unless you've marked them as hidden, the user will be able to see and change the preferences in the Add-on Manager. ...
...ou can provide translated forms of the title and description attributes. See the localization tutorial for more details. Getting and setting preferences Unless you've marked them as hidden, the user will be able to see and change the preferences in the Add-on Manager. You can also see them and change them programmatically using the prefs property, and listen for changes to a preference using on
(). Simple-prefs in the preferences system Preferences defined using simple-prefs are stored in the Firefox preferences system alongside all the other preferences. This means that they're visible in about:config, and they can be accessed using the global simple-preferences module. By default, simple preferences are stored in a preference like: extensions.<addon-id>.<preference-name> For example,...
url - Archive of obsolete content
I("http://mozilla.org") would return true, whereas isValidURI("mozilla.org") would return false. Parameters uri : string The URI, as a string, to be tested. Returns boolean : A boolean indicating whether or not the URI is valid. getTLD(url) Returns the top-level domain for the given URL: that is, the highest-level domain under which individual domains may be registered. Uses getPublicSuffix
() internally. var urls = require("sdk/url"); console.log(urls.getTLD("http://www.bbc.co.uk/")); // "co.uk" console.log(urls.getTLD("https://developer.mozilla.org/")); // "org" Parameters url : string The URL, as a string. Returns string : The top-level domain for the URL. URL Methods toString
() Returns a string representation of the URL. Returns string : The URL as a string. t...
... Returns string : The URL as a string. ...
...example=true&visible=yes#top"); console.log(url.protocol); // https: search If any parameters are present, a '?' followed by the parameters of the URL, as a string. Mirrors window.location.search. For example: var url = require("sdk/url").URL("https://developer.mozilla.org/Add-ons?example=true&visible=yes#top"); console.log(url.search); // ?example=true&visible=yes DataURL Methods toString
() Returns a string representation of the Data URL. If base64 is true, the data property is encoded using base-64 encoding. Returns string : The URL as a string. Properties mimeType The MIME type of the data. By default is an empty string. parameters An hashmap that contains the parameters of the Data URL. By default is an empty object. base64 Defines the encoding for the value in data pro...
windows - Archive of obsolete content
any window events, and you won't be able to open private windows. To learn more about private windows, how to opt into private browsing, and how to support private browsing, refer to the documentation for the private-browsing module. Converting to chrome windows To convert from the BrowserWindow objects used in this API to the chrome window objects used in the window/utils API, use the viewFor
() function exported by the viewFor module. To convert back the other way, from a chrome window to a BrowserWindow object, use the modelFor
() function, exported by the modelFor module. Here's an example converting from a high-level BrowserWindow to a chrome window, and then back the other way: var { modelFor } = require("sdk/model/core"); var { viewFor } = require("sdk/view/core"); var browserWi...
...s.open({ url: "http://www.example.com", onOpen: function(window) { // do stuff like listen for content // loading. } }); Returns the window that was opened: var windows = require("sdk/windows").browserWindows; var example = windows.open("http://www.example.com"); require("sdk/ui/button/action").ActionButton({ id: "read", label: "Read", icon: "./read.png", onClick: function
() { example.close
(); } }); This example uses the action button API, which is only available from Firefox 29 onwards. Parameters options : object Required options: Name Type url string String URL to be opened in the new window. This is a required property. isPrivate boolean Boolean which will determine whether the new win...
...xported by this module. var windows = require("sdk/windows").browserWindows; //Print how many tabs the current window has console.log("The active window has " + windows.activeWindow.tabs.length + " tabs."); // Print the title of all browser windows for (let window of windows) { console.log(window.title); } // close the active window windows.activeWindow.close(function
() { console.log("The active window was closed"); }); Methods activate
() Makes window active, which will focus that window and bring it to the foreground. close(callback) Close the window. Parameters callback : function A function to be called when the window finishes its closing process. This is an optional argument. Properties title The current title of the window. Usually the title o...
core/namespace - Archive of obsolete content
Provides an API for creating namespaces for objects, which effectively may be used for creating fields that are not part of objects public API. let { ns } = require('sdk/core/namespace'); let aNamespace = ns
(); aNamespace(publicAPI).secret = secret; One namespace may be used with multiple objects: let { ns } = require('sdk/core/namespace'); let dom = ns
(); function View(element) { let view = Object.create(View.prototype); dom(view).element = element; // .... } View.prototype.destroy = function destroy
() { let { element } = dom(this); element.parentNode.removeChild(element); // ... }; // ... exports.View = View; // ... Also, multiple namespaces can be used with one object: // ./widget.js let { Cu } = require('chrome'); let { ns ...
...his); element.parentNode.removeChild(element); // ... }; // ... exports.View = View; // ... Also, multiple namespaces can be used with one object: // ./widget.js let { Cu } = require('chrome'); let { ns } = require('sdk/core/namespace'); let { View } = require('./view'); // Note this is completely independent from View's internal Namespace object. let sandboxes = ns
(); function Widget(options) { let { element, contentScript } = options; let widget = Object.create(Widget.prototype); View.call(widget, options.element); sandboxes(widget).sandbox = Cu.Sandbox(element.ownerDocument.defaultView); // ... } Widget.prototype = Object.create(View.prototype); Widget.prototype.postMessage = function postMessage(message) { let { sandbox } =...
...all(widget, options.element); sandboxes(widget).sandbox = Cu.Sandbox(element.ownerDocument.defaultView); // ... } Widget.prototype = Object.create(View.prototype); Widget.prototype.postMessage = function postMessage(message) { let { sandbox } = sandboxes(this); sandbox.postMessage(JSON.stringify(JSON.parse(message))); ... }; Widget.prototype.destroy = function destroy
() { View.prototype.destroy.call(this); // ... delete sandboxes(this).sandbox; }; exports.Widget = Widget; In addition access to the namespace can be shared with other code by just handing them a namespace accessor function. let { dom } = require('./view'); Widget.prototype.setInnerHTML = function setInnerHTML(html) { dom(this).element.innerHTML = String(html); }; ...
Release notes - Archive of obsolete content
ox 33 and Firefox 34. This will not include any uplifts made after this release entered Aurora. Bugs fixed between Firefox 33 and Firefox 34. This will not include any uplifts made after this release entered Aurora. Firefox 33 Highlights Added support for context menus in panels via a new option in the Panel constructor. Added tab.readyState. Added a BrowserWindow parameter to sidebar.show
() and sidebar.hide
(), to control the window for which the sidebar will be shown or hidden. Details GitHub commits made between Firefox 32 and Firefox 33. This will not include any uplifts made after this release entered Aurora. Bugs fixed between Firefox 32 and Firefox 33. This will not include any uplifts made after this release entered Aurora. Firefox 32 Highlights Added exclude option t...
...clude any uplifts made after this release entered Aurora. Firefox 30 Highlights Added the ability to anchor panels to buttons. Changes in the way content scripts share objects with page scripts. Documentation and blog post. Added child_process, an implementation of the node.js child_process API. Content scripts in page-mod get detach events when the add-on is disabled or removed. throttle
() and debounce
() functions added to lang/functional. getTabForId
() function added to tabs/utils. Details GitHub commits made between Firefox 29 and Firefox 30. This will not include any uplifts made after this release entered Aurora. Bugs fixed between Firefox 29 and Firefox 30. This will not include any uplifts made after this release entered Aurora. Firefox 29 Highlights Added new UI mo...
...and api-utils.publicConstructor Details GitHub commits made between Firefox 28 and Firefox 29. This will not include any uplifts made after this release entered Aurora. Bugs fixed between Firefox 28 and Firefox 29. This will not include any uplifts made after this release entered Aurora. Firefox 28 Highlights Added wildcard event type "*". Added a ready event to sidebars. Added a delete
() method to sdk/request. Details GitHub commits made between Firefox 27 and Firefox 28. This will not include any uplifts made after this release entered Aurora. Bugs fixed between Firefox 27 and Firefox 28. This will not include any uplifts made after this release entered Aurora. ...
Chrome Authority - Archive of obsolete content
ees module code which references Components directly. Your modules should refrain from using chrome privileges unless they are absolutely necessary. Chrome-authority-using modules must receive extra security review, and most bugs in these modules are security-critical. Manifest Generation The manifest is a list, included in the generated XPI, which specifies which modules have requested require
() access to which other modules. It also records which modules have requested chrome access. This list is generated by scanning all included modules for require(XYZ) statements and recording the particular "XYZ" strings that they reference. When the manifest implementation is complete the runtime loader will actually prevent modules from require
()ing modules that are not listed in the manifest. Li...
...pers should stick to simple require statements, with a single static string, one per line of code. If the scanner fails to see a require entry, the manifest will not include that entry, and (once the implementation is complete) the runtime code will get an exception. ...
...Their statements must therefore be clear and easy to parse. ...
List Open Tabs - Archive of obsolete content
To follow this tutorial you'll need to have learned the basics of jpm. To list the open tabs, you can iterate over the tabs object itself. The following add-on adds an action button that logs the URLs of open tabs when the user clicks it: require("sdk/ui/button/action").ActionButton({ id: "list-tabs", label: "List Tabs", icon: "./icon-16.png", onClick: listTabs }); function listTabs
() { var tabs = require("sdk/tabs"); for (let tab of tabs) console.log(tab.url); } Note: to get this working, you will need to save an icon for the button to your add-on's "data" directory as "icon-16.png". You can download the icon here: . Run the add-on, load a couple of tabs and click the button. You'll see output in the command line console that looks something like this: info: htt...
... as "icon-16.png". You can download the icon here: . Run the add-on, load a couple of tabs and click the button. You'll see output in the command line console that looks something like this: info: http://www.mozilla.org/about/ info: http://www.bbc.co.uk/ You don't get direct access to any content hosted in the tab. To access tab content, you need to attach a script to the tab using tab.attach
(). ...
...You don't get direct access to any content hosted in the tab. To access tab content, you need to attach a script to the tab using tab.attach
(). This add-on attaches a script to all open tabs. The script adds a red border to the tab's document: require("sdk/ui/button/action").ActionButton({ id: "list-tabs", label: "List Tabs", icon: "./icon-16.png", onClick: listTabs }); function listTabs
() { var tabs = require("sdk/tabs"); for (let tab of tabs) runScript(tab); } function runScript(tab) { tab.attach({ contentScript: "document.body.style.border = '5px solid red';" }); } Learning More To learn more about working with tabs in the SDK, see the tabs API reference. To learn more about running scripts in tabs, see the tutorial on using tab.attach
(). ...
Listening for Load and Unload - Archive of obsolete content
To follow this tutorial you'll need to have learned the basics of jpm. If your add-on exports a function called main
(), then that function will be called whenever the add-on is loaded, and it will be passed an object containing a string describing the reason it was loaded as well as any arguments passed to it. If your add-on exports a function called onUnload
(), then that function will be called when the add-on is unloaded, and it will be passed a string describing the reason it was unloaded. You don't have to use exports.main
() or exports.onUnload
(). You can just place your add-on's code at the top level instead of wrapping it in a function assigned to exports.main
(). It will be loaded in the same circumstances, but you won't get access to the load/unload reason or arguments. exports...
...n the add-on is unloaded, and it will be passed a string describing the reason it was unloaded. You don't have to use exports.main
() or exports.onUnload
(). You can just place your add-on's code at the top level instead of wrapping it in a function assigned to exports.main
(). It will be loaded in the same circumstances, but you won't get access to the load/unload reason or arguments. exports.main
() Your add-on's main.js code is executed as soon as it is loaded. It is loaded when it is installed, when it is enabled, or when Firefox starts. If your add-on exports a function called main
(), that function will be called immediately after the overall main.js is evaluated, and after all top-level require
() statements have run (so generally after all dependent modules have been loaded). export...
...e
() statements have run (so generally after all dependent modules have been loaded). exports.main = function (options, callbacks) {}; options is an object describing the parameters with which your add-on was loaded. options.loadReason options.loadReason is one of the following strings describing the reason your add-on was loaded: install enable startup upgrade downgrade exports.onUnload
() If your add-on exports a function called onUnload
(), that function will be called when the add-on is unloaded. exports.onUnload = function (reason) {}; reason reason is one of the following strings describing the reason your add-on was unloaded: uninstall disable shutdown upgrade downgrade If your add-on is disabled, then uninstalled, your onUnload listener will only be called once, w...
Localization - Archive of obsolete content
g where you want the localized string to appear, and assign the identifier to it: <html> <body> <h1 data-l10n-id="hello_id"></h1> </body> </html> Then you can use this HTML file to build your interface, for example inside a panel: var button = require("sdk/ui/button/action").ActionButton({ id: "localized-hello", label: "Localized hello", icon: "./icon-16.png", onClick: function
() { hello.show
(); } }); var hello = require("sdk/panel").Panel({ height: 75, width: 150, contentURL: require("sdk/self").data.url("my-panel.html") }); Given locale files for "en-US" and "fr" which provide translations of hello_id, the panel will now display "Hello!" or "Bonjour !", according to the current locale: The translation is inserted into the node which has the data-l10n-id...
...you do this: var _ = require("sdk/l10n").get; console.log(_("hello_id")); Assigning to "_" in particular is not required, but is a convention from the gettext tools and will make it possible to work with existing tools that expect "_" to indicate localizable strings. Import the l10n module, and assign its get function to "_" (underscore). Wrap all references to localizable strings with the _
() function. If you run it you'll see the expected output for the current locale: info: Hello! info: Bonjour ! Note that because you can't require
() modules in content scripts, you can't yet reference localized strings from content scripts. Plurals The l10n module supports plural forms. Different languages have different rules for the formation of plurals. For example, English has two forms...
...a new .properties file for that add-on. If you provide a new file, the add-on's locale data will be updated with the new file. Limitations The current localization support is a first step towards full support, and contains a number of limitations. There's no support for content scripts or CSS files: at the moment, you can only localize strings appearing in JavaScript files that can require
() SDK modules and in HTML. See bug 787351. The set of locale files is global across an add-on. This means that a module isn't able to override a more general translation: so a module informal.js can't specify that "hello_id" occurring in its code should be localized to "Hi!". The SDK tools compile the locale files into a JSON format when producing an XPI. This means that translators can...
Cookies - Archive of obsolete content
Setting a cookie The following code demonstrates how to set a cookie in Firefox. ...
... Setting a cookie The following code demonstrates how to set a cookie in Firefox. ...
... Setting a cookie The following code demonstrates how to set a cookie in Firefox. ...
On page load - Archive of obsolete content
key chrome://navigator/content/navigator.xul Attaching a script Attach a script to your overlay (see "Attaching a Script to an Overlay") that adds a load event listener to appcontent element (browsers) or messagepane (mail): window.addEventListener("load", function load(event){ window.removeEventListener("load", load, false); //remove listener, no longer needed myExtension.init
(); },false); var myExtension = { init: function
() { var appcontent = document.getElementById("appcontent"); // browser if(appcontent){ appcontent.addEventListener("DOMContentLoaded", myExtension.onPageLoad, true); } var messagepane = document.getElementById("messagepane"); // mail if(messagepane){ messagepane.addEventListener("load", function(event) { myExtensio...
...he unload event in above example you can use the "pagehide" event like this: appcontent.addEventListener("pagehide", myExtension.onPageUnload, false); for appcontent and similarly for messagepane messagepane.addEventListener("pagehide", myExtension.onPageUnload, false); and add your code to onPageUnload method. Basic onPageLoad for a browser window var myExtension = { init: function
() { // The event can be DOMContentLoaded, pageshow, pagehide, load or unload. if(gBrowser) gBrowser.addEventListener("DOMContentLoaded", this.onPageLoad, false); }, onPageLoad: function(aEvent) { var doc = aEvent.originalTarget; // doc is document that triggered the event var win = doc.defaultView; // win is the window for the doc // test desired cond...
....nodeName != "#document") return; // only documents // if (win != win.top) return; //only top window. // if (win.frameElement) return; // skip iframes/frames alert("page is loaded \n" +doc.location.href); } } window.addEventListener("load", function load(event){ window.removeEventListener("load", load, false); //remove listener, no longer needed myExtension.init
(); },false); References If you need to have a more complicated listener (not just onload), use Progress Listeners. See also DOMContentLoaded event in Listening to events: Simple DOM events ...
Tree - Archive of obsolete content
.toggleOpenState(i); } To collapse all tree nodes just change the condition: var treeView = tree.treeBoxObject.view; for (var i = 0; i < treeView.rowCount; i++) { if (treeView.isContainer(i) && treeView.isContainerOpen(i)) treeView.toggleOpenState(i); } Getting the text from the selected row Assuming the given <tree>: <tree id="my-tree" seltype="single" onselect="onTreeSelected
()"> Use the following JavaScript: function onTreeSelected
(){ var tree = document.getElementById("my-tree"); var cellIndex = 0; var cellText = tree.view.getCellText(tree.currentIndex, tree.columns.getColumnAt(cellIndex)); alert(cellText); } Getting the tree item from the focused row Assuming <tree id="my-tree">, you can use the following to get the tree item: var view = document...
...an use the following to get the tree item: var view = document.getElementById("my-tree").view; var sel = view.selection.currentIndex; //returns -1 if the tree is not focused var treeItem = view.getItemAtIndex(sel); Note that the current index may be unselected (for example, a multi-select tree). Getting the cell from a mouse click Your first choice is likely to try <treecell onclick="yourfunc
();"/> or something similar. But this will not work. You can't add event handlers to <treecell>. Instead, you can add the event handler to the <tree> element. You can then use the event and some utility methods to find the <treecell>. For example, assuming the given <tree>: <tree id="my-tree" onclick="onTreeClicked(event)"> Use the following JavaScript: function onTreeClicked(event){ var tree...
...var tbo = tree.treeBoxObject; // get the row, col and child element at the point var row = { }, col = { }, child = { }; tbo.getCellAt(event.clientX, event.clientY, row, col, child); var cellText = tree.view.getCellText(row.value, col.value); alert(cellText); } Getting the selected indices of a multiselect tree var start = {}, end = {}, numRanges = tree.view.selection.getRangeCount
(), selectedIndices = []; for (var t = 0; t < numRanges; t++){ tree.view.selection.getRangeAt(t, start, end); for (var v = start.value; v <= end.value; v++) selectedIndices.push(v); } Other resources XUL: Tree documentation XUL tutorial: Tree selection ...
Custom about: URLs - Archive of obsolete content
const ABOUTPAGE_ID = 'aa132730-2278-11e5-867f-0800200c9a66'; // make sure you generate a unique id from https://www.famkruithof.net/uuid/uuidgen const ABOUTPAGE_WORD = 'myaboutpage' const ABOUTPAGE_URI = 'data:text/html,hi this is the page that is shown when navigate to about:myaboutpage'; // const ABOUTPAGE_URI = 'chrome://myaboutaddon/content/index.html'; class AboutPage { static get classID
() { return Components.ID(`{${ABOUTPAGE_ID}}`); } static get classDescription
() { return ABOUTPAGE_DESCRIPTION; } static get contractID
() { return `@mozilla.org/network/protocol/about;1?what=${ABOUTPAGE_WORD}`; } static get QueryInterface
() { return XPCOMUtils.generateQI([Ci.nsIAboutModule]); } constructor
() { Object.freeze(this); } getURIFlags(aURI) { return Ci.nsIAboutModule.
...ater than or equal to firefox48 so aSecurity_or_aLoadInfo is aLoadInfo channel = Services.io.newChannelFromURIWithLoadInfo(uri, aSecurity_or_aLoadInfo); } else { channel = Services.io.newChannel(ABOUTPAGE_URI, null, null); } channel.originalURI = aURI; return channel; } } class Factory { constructor(component) { this.component = component; this.register
(); Object.freeze(this); } createInstance(outer, iid) { if (outer) { throw Cr.NS_ERROR_NO_AGGREGATION; } return new this.component
(); } register
() { Cm.registerFactory(this.component.classID, this.component.classDescription, this.component.contractID, this); } unregister
() { Cm.unregiste...
...} And there you have it, your own custom about page. ...
Listening to events in Firefox extensions - Archive of obsolete content
om all tabs is available. How events are used by Firefox The Firefox frontend already listens for a number of these progress events from web pages. Most of this goes on in browser.js. DOMLinkHandler The DOMLinkHandler object is called by the DOMLinkAdded event in order to detect any RSS feeds, site icons, or OpenSearch plugins for the web site. pageShowEventHandlers The pageShowEventHandlers
() function is called by the pageshow event and is used to populate the character set menu and update the UI elements associated with any detected feeds or OpenSearch plugins for the website. XULBrowserWindow XULBrowserWindow is an nsIWebProgressListener used to get progress events for the currently visible browser. It is used to update the UI for many different reasons: Update the progress bar...
... allow the user to block the attempt. How events are used by the tabbrowser tabbrowser maintains a set of objects relating to progress listening for each browser. First it creates a browser-status-filter and adds it as a web progress listener for the browser. Next it creates an internal object to receive all web progress events from the browser. This is created by the method mTabProgressListener
(). ...
...is is created by the method mTabProgressListener
(). This receives events from the browser-status-filter. The filter acts to reduce the number of status and progress events to improve performance. The filters are held in the array mFilters, the internal listeners in the array mTabListeners. The internal listeners are used to send out progress events to listeners registered with addProgressListener
() (which receives events from the browser that is currently visible) and addTabsProgressListener
() (which receives events from all browsers). ...
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
lder, like the initial DB the add-on will use for storage. A few others require cleanup code to be run after the add-on is uninstalled. This appendix covers these cases with simple code that should work for most add-ons. Install Scripts Just like with a regular initialization function, we want a load event handler: // rest of overlay code goes here. ...
...l use for storage. A few others require cleanup code to be run after the add-on is uninstalled. This appendix covers these cases with simple code that should work for most add-ons. Install Scripts Just like with a regular initialization function, we want a load event handler: // rest of overlay code goes here. ...
...s here. window.addEventListener( "load", function
() { XulSchoolChrome.BrowserOverlay.init
(); }, false); Then all we need is some persistent flag that ensures that the first run code is only run once. The best approach in this case is to use a preference, as explained in the Handling Preferences section. So, if we were to use FUEL, we can do the following in the init function: init : function
() { let firstRunPref = "extensions.xulschoolhello.firstRunDone"; if (!Application.prefs.getValue(firstRunPref, false)) { Application.prefs.setValue(firstRunPref, true); // all the rest of the first run code goes here. } } In this case you would need to declare the first run preference in your default preferences file, with a default value of false. You should also change the prefere...
User Notifications and Alerts - Archive of obsolete content
ear. The notification shows up again when you come back to the tab that displayed it. This means that these notifications make the most sense when they are related to the page currently being displayed, such as a page trying to install an add-on, or a site you just entered a password on. ...
...ain when you come back to the tab that displayed it. This means that these notifications make the most sense when they are related to the page currently being displayed, such as a page trying to install an add-on, or a site you just entered a password on. ...
...that displayed it. This means that these notifications make the most sense when they are related to the page currently being displayed, such as a page trying to install an add-on, or a site you just entered a password on. Notification boxes are very easy to create, and are very customizable: let nb = gBrowser.getNotificationBox
(); let acceptButton = new Object
(); let declineButton = new Object
(); let message = this._bundle.getString("xulschoolhello.friendMessage.label"); let that = this; acceptButton.label = this._bundle.getString("xulschoolhello.acceptButton.label"); acceptButton.accessKey = this._bundle.getString("xulschoolhello.acceptButton.accesskey"); acceptButton.popup = null; acceptButton.callback = function
() { that.acceptRequest
(); }; // similarly for decline button. nb.a...
Session store API - Archive of obsolete content
ensions to easily save and restore data across Firefox sessions. There is a simple API that lets extensions access the session store feature. One key scenario in which supporting this feature can be crucial for an extension: Firefox 2 lets users undo the closing of tabs. In order to properly restore your extension's state when a tab is restored, it needs to use the session store API's setTabValue
() method to save any data it will need in order to restore its state, and then call getTabValue
() to retrieve the previous setting when the tab is restored. The Session Store API is implemented using the nsISessionStore interface. Knowing when to restore Each time Firefox is about to restore a tab, an event of type SSTabRestoring is sent. If your extension wants to be able to restore data when t...
...In this example, nsIConsoleService is used to display a message to the console. This event is sent just before a tab is restored. An event of type SSTabRestored fires each time a tab has finished restoring. It's worth noting that this event is sent even if tab loading at startup is deferred until the user selects the tab. Firefox 3 note I...
...d as required (one for each window that was saved in the session store), and cookies and the list of recently closed tabs are restored. After that, the following steps are taken for each tab being restored: Either an existing tab is reused or a new tab is created. In the latter case, a TabOpen event is sent. The tab's persistent XUL attributes (those saved due to calls to persistTabAttribute
()) and permissions are restored. The SSTabRestoring event is sent. The tab is told to load the URL it should be displaying. When the page is finished loading, text fields and scroll state are restored. Finally, the SSTabRestored event is sent. If you want to set permissions or otherwise manipulate a restored tab before the page is loaded into it, you should watch SSTabRestoring. If you want t...
Using Dependent Libraries In Extension Components - Archive of obsolete content
sGetModuleProc getmoduleproc = (nsGetModuleProc) PR_FindFunctionSymbol(lib, NS_GET_MODULE_SYMBOL); if (!getmoduleproc) return NS_ERROR_FAILURE; return getmoduleproc(aCompMgr, aLocation, aResult); } extensions/stub/bdsStubLoader.cpp (for Mac OS X) The code as written above won't work for Mac OS X. Dependant libraries on the mac must be loaded with a special system function NSAddImage
() with the flag NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME. The following are the necessary modifications you will need in order to write a stub loader for an OS X extension. You will also need to make sure you are properly linking the XPCOM glue libraries. See XPCOM Glue for the proper flags on how to link to the glue libraries. /* * OS X Stubloader * Original stubloader code by Benjam...
...raries for (char const *const *dependent = kDependentLibraries; *dependent; ++dependent) { library->SetNativeLeafName(nsDependentCString(*dependent)); rv = library->GetNativePath(path); if (NS_FAILED(rv)) return rv; //At this point, we would have used PRLibrary *lib; library->Load(&lib); //But we can't use that in OS X. Instead, we use NSAddImage. ...
.../ // 2) We are going to leak this library. We don't care about that either. // NSAddImage adds the image to the process. When the process terminates, the library // will be properly unloaded. } library->SetNativeLeafName(NS_LITERAL_CSTRING(kRealComponent)); rv = library->GetNativePath(path); if (NS_FAILED(rv)) return rv; const mach_header * componentlib = NSAddImage(path.get
(), NSADDIMAGE_OPTION_RETURN_ON_ERROR | NSADDIMAGE_OPTION_WITH_SEARCHING | NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME); if (componentlib == NULL) return NS_ERROR_UNEXPECTED; //Find the NSGetModule procedure of the real component and "pass the buck". nsGetModuleProc getmoduleproc = (nsGetModuleProc)LookupSymbol(componentlib, "_NSGetModule"); if (!getmoduleproc) return ...
Index of archived content - Archive of obsolete content
ing an XPI Signing an extension Supporting search suggestions in search plugins Tabbed browser Techniques Promises Updating addons broken by private browsing changes Using Dependent Libraries In Extension Components Using the Stylesheet Service bookmarks.export
() bookmarks.import
() Adding preferences to an extension An Interview With Douglas Bowman of Wired News Archived Mozilla and build documentation ActiveX Control for Hosting Netscape Plug-ins in IE Archived SpiderMonkey docs File object ...
... Helper Apps (and a bit of Save As) Hidden prefs How to Write and Land Nanojit Patches IO Guide/Directory Keys Introducing the Audio API extension Isp Data Java in Firefox Extensions JavaScript OS.Shared JavaScript crypto CRMF Request object generateCRMFRequest
() importUserCertificates popChallengeResponse Jetpack Basics Content Page modifications Extenders Jetpack Snippets Libraries Twitter ...
... Reference Server-Side JavaScript Back to the Server: Server-Side JavaScript On The Rise Sharp variables in JavaScript Standards-Compliant Authoring Tools StopIteration Styling the Amazing Netscape Fish Cam Page Using JavaScript Generators in Firefox Window.importDialog
() Writing JavaScript for XHTML XForms Building Mozilla XForms Community Developing Mozilla XForms Implementation Status Mozilla XForms Specials Mozilla XForms User Interface XForms Alert Element XForms Group Element ...
Enabling the behavior - retrieving tinderbox status - Archive of obsolete content
Our Mozilla extension now exists, but it doesn't do anything. To make it work we have to add JavaScript code that changes its status when the tinderbox status changes. The first step is to write a function that queries the tinderbox server and retrieves the current status. var gXMLHttpRequest; function loadTinderboxStatus
() { gXMLHttpRequest = new XMLHttpRequest
(); gXMLHttpRequest.onload = updateTinderboxStatus; gXMLHttpRequest.open("GET", "http://tinderbox.mozilla.org/SeaMonkey/panel.html"); gXMLHttpRequest.send(null); } XMLHttpRequest is an interface in Mozilla for retrieving documents via HTTP. Although it is designed to retrieve XML content and parse it into a DOM, it can retrieve (but not parse) other kinds of content as well. In this case we use it to retrieve an HT...
...taining a brief summary of the current tinderbox state. That document gets updated by the tinderbox server every time a build finishes. It displays a list of active tinderbox clients along with the result of their last build attempt. XMLHttpRequest is easy to use in the simple case we have here. We use new to create a new instance of it, set the instance's onload property to updateTinderboxStatus
(), the function we want to execute when the document finishes loading, call its open method with the type of HTTP request we want to make and the URL of the document to retrieve, and then call its send method to send the request. XMLHttpRequest will retrieve the document located at the given URL and call the updateTinderboxStatus
() function when it is done. Notice that we defined the instance of ...
...of HTTP request we want to make and the URL of the document to retrieve, and then call its send method to send the request. XMLHttpRequest will retrieve the document located at the given URL and call the updateTinderboxStatus
() function when it is done. Notice that we defined the instance of XMLHttpRequest as a global variable. This is because we need to reference it in the updateTinderboxStatus
() function as well as the current function, and we can't pass the object from one function to the other because the one doesn't call the other directly. << PreviousNext >> ...
Dehydra Object Reference - Archive of obsolete content
memberOf aggregate type object Indicates the aggregate type(class/struct) in the type system that this variable is a member of. .fieldOf variable object Provides the object being dereferenced, in the AST system. Applicable when accessing member variables or nonstatic member functions of aggregate types, e.g. the "foo" variable would be a .fieldOf memberVar/Fn in foo->memberVar or foo->memberFn
(). Note that when constructing the return value of a function (e.g. return T
();), no container variable is available; in this case, .isReturn will be true (see Function Variable). Variables can identified by their DehydraDecl
() prototype. Function Variable Function objects are an extension of Variable Objects. The following additional properties are available on functions: Property Type Descr...
...e; in this case, .isReturn will be true (see Function Variable). Variables can identified by their DehydraDecl
() prototype. Function Variable Function objects are an extension of Variable Objects. The following additional properties are available on functions: Property Type Description .isVirtual true or "pure" true for virtual methods, or "pure" for pure virtuals (e.g. virtual void foo
() = 0;). .isConstructor boolean flag Constructors generally have a .fieldOf attribute (see Variable Objects). .isFunction boolean flag true for function variables. Type Objects Dehydra provides detailed type objects. Dehydra Type objects use the DehydraType
() prototype. Common Type Properties Property Type Description .name string If applicable, the name of of the type. For typedefs...
.... .isExplicit boolean flag true for constructors declared using the C++ explicit keyword Template Objects Property Type Description .name string the name of the template, for example "nsCOMPtr". .arguments array an array where arguments are either strings representing C++ constants or type objects. Location Objects Location objects are passed to builtin functions such as warning
() and error
() to specify the location of the message. They convert to a string of the form "file:line:column". They have the following properties: Property Type .file string .line integer .column integer (optional) ...
GRE - Archive of obsolete content
per libraries. If you link directly against xpcom.dll/libxpcom.so (xpcom.lib import lib), your application will not launch unless xpcom.dll is in your PATH. This prevents dynamically finding a compatible GRE at runtime. Find a compatible GRE Note: Support for locating a standalone glue was removed in Gecko 6.0. To find a compatible GRE, you should use the function GRE_GetGREPathWithProperties
() (declared in xpcom/glue/standalone/nsXPCOMGlue.h). This allows the embedder to specify what version(s) of GRE are appropriate, and to specify any special features the GRE must have (currently there are no special features defined). Statically link to xpcomglue.lib (the "standalone glue") The solution is to statically link against xpcomglue.lib, also known as the "standalone glue" (see XPCOM Glu...
...nown as the "standalone glue" (see XPCOM Glue). This library provides a layer of indirection between embedding code and XPCOM. To use the XPCOM glue, you must follow these steps: Compile your code with XPCOM_GLUE defined. Link with xpcomglue.lib (not xpcomglue_s.lib!). Don't link against the NSPR libs. Find a compatible GRE (see above). ...
...you must follow these steps: Compile your code with XPCOM_GLUE defined. Link with xpcomglue.lib (not xpcomglue_s.lib!). Don't link against the NSPR libs. Find a compatible GRE (see above). Dynamically link to that GRE using the XPCOMGlueStartup
() function. See environment variables below. Initialize XPCOM and do your work; when finished, shut down XPCOM. Unlink XPCOM with XPCOMGlueShutdown
(). Dependent libraries and environment variables The XULRunner GRE is designed so that the embedder does not need to set any environment variables such as PATH or LD_LIBRARY_PATH before calling XPCOMGlueStartup
(), because it dynamically loads the correct dependent libraries. Unfortunately, the Mozilla suite-based GRE is not as forgiving, especially on Linux. Embedders will need to set the LD_LIB...
Me - Archive of obsolete content
t. Read the experiment report for what we learned from it and the blog post announcing the first SDK release for what we're up to next! The jetpack.me namespace provides mechanisms for introspecting the dynamic state of your jetpack. ...
...ing the first SDK release for what we're up to next! The jetpack.me namespace provides mechanisms for introspecting the dynamic state of your jetpack. The namespace currently lives in the future and must be imported before it is used: jetpack.future.import("me"); Methods onFirstRun(funcfunction)jetpack.me.onFirstRun
() allows jetpacks to be notified after they are successfully installed. onFirstRun
() accepts a callback which is called after installation. Note that this mechanism is independent of the first-run page; in particular, the callback is not a load event listener or jQuery ready callback. onFirstRun
() may be called anywhere in your jetpack, but if it is called as the result of some asynchronous operation such as a timeout or XMLHttpRequest, it is ignored. If you call it multiple time...
...uery ready callback. onFirstRun
() may be called anywhere in your jetpack, but if it is called as the result of some asynchronous operation such as a timeout or XMLHttpRequest, it is ignored. If you call it multiple times, all but the final call are ignored. funcA function. it takes no paramenters. ...
Tabs - Archive of obsolete content
ss is jetpack.tabs. blah(lengthstringfocusedstringtoStringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengthThe number of open tabsstring focusedthe current tab in your browserstring toStringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onReady
()when the inherited document is fully loaded. onFocus
()changing the focus of a tab. Methods open(urlstring)Opens a new tab in your browser with a defined url. urlURL to be openedstring jetpack.tabs.open("http://www.example.com/"); blah(lengthstringfocusedstringtoStringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengthThe number ...
... ...
... ...
Reading textual data - Archive of obsolete content
Not doing so can cause problems if you try to rename or delete the file at a later time on some platforms. Note that you may get less characters than you asked for, especially (but not only) at the end of the file (stream). Unsupported byte sequences You can specify what should happen with byte sequences that do not correspond to a valid character. The last (4th) argument to init specifies w...
...24, 0xFFFD); is.QueryInterface(Components.interfaces.nsIUnicharLineInputStream); if (is instanceof Components.interfaces.nsIUnicharLineInputStream) { var line = {}; var cont; do { cont = is.readLine(line); // Now you can do something with line.value } while (cont); } The above example reads an entire stream until EOF. See nsIConverterInputStream for nsIConverterInputStream.init
() arguments. Earlier versions Reading strings Earlier versions of gecko do not provide easy ways to read unicode data from a stream. You will have to manually read a block of data and convert it using nsIScriptableUnicodeConverter. For example: // First, get and initialize the converter var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"] ...
...network/file-input-stream;1"] .createInstance(Components.interfaces.nsIFileInputStream); fis.init(file, -1, -1, 0); var lis = fis.QueryInterface(Components.interfaces.nsILineInputStream); var lineData = {}; var cont; do { cont = lis.readLine(lineData); var line = converter.ConvertToUnicode(lineData.value); // Now you can do something with line } while (cont); fis.close
(); See also Writing textual data Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets ...
Same origin policy for XBL - Archive of obsolete content
?>, user sheets, and UA sheets), it depends on where the sheet is loaded from, just like it would for an HTML document loaded from a similar source. For inline stylesheets (<style> and style attributes), the principal of the element node involved (meaning the <style> element or the element whose style attribute is being looked at). For the nsIDOMDocumentXBL interface's nsIDOMDocumentXBL.addBinding
() and nsIDOMDocumentXBL.loadBindingDocument
() methods, the originating principal is the one of the script making the call, or the principal of the document the call is made on if there isn't a script. Checks performed Once the originating principal is determined, checks are done to make sure the load should be allowed. The checks performed are: If the principal originating the load is the system ...
...ing principal is the one of the script making the call, or the principal of the document the call is made on if there isn't a script. Checks performed Once the originating principal is determined, checks are done to make sure the load should be allowed. The checks performed are: If the principal originating the load is the system principal, the load is allowed. A call to ChecLoadURIWithPrincipal
() is done to make sure the principal is able to link to the given URI in the first place. A content policy check is performed. If the URI is a chrome: URI, the load is allowed. Note that step 2 already denied the load attempt for cases in which the chrome: URI isn't accessible to untrusted content. A CheckMayLoad
() check is performed on the originating principal for the given URI. If the CheckMayL...
... done to make sure the principal is able to link to the given URI in the first place. A content policy check is performed. If the URI is a chrome: URI, the load is allowed. Note that step 2 already denied the load attempt for cases in which the chrome: URI isn't accessible to untrusted content. A CheckMayLoad
() check is performed on the originating principal for the given URI. If the CheckMayLoad
() check passes, the load is allowed. ...
Abc Assembler Tests - Archive of obsolete content
er code can be found in /utils/abcasm. Tests can be found in /test/acceptance/abcasm and end with the .abs extension. The tests are run using the same runtests.py script that is used for the actionscript tests. ...
...n of this file under the terms 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. ...
...le under * the terms of any one of the MPL, the GPL or the LGPL. ...
Cmdline tests - Archive of obsolete content
ts in python allowing any executable to run, sending commands to stdin, and asserting output using regular expressions. See test/cmdline/README document for more information. ...
...g any executable to run, sending commands to stdin, and asserting output using regular expressions. See test/cmdline/README document for more information. ...
... '%s -d testdata/debug.abc'%r.avmrd, input='break 53\ncontinue\nnext\ninfo locals\nnext\ninfo locals\nquit\n', expectedout=['local1 = undefined','local2 = 10','local2 = 15'] ) Use case 2: test -memstats returns memory logs to stdout Test contents: start avmshell -memstats test.abc, assert stdout contains 'gross stats', 'sweep m reclaimed n pages.' from cmdutils import * def run
(): r=RunTestLib
() r.run_test(name='memstats', command="%s -memstats testdata/memstats.abc" % r.avm, expectedout=[ 'gross stats', 'managed fragmentation', 'gross stats end', 'sweep\\([0-9]+\\) reclaimed [0-9]+ whole pages' ]...
File.macAlias - Archive of obsolete content
udio Player) that is installed locally. ...
...installed locally. ...
... = "Miscellaneous Program"; var vi = "1.1.1.1"; initInstall( "Macintosh Alias", "misc", vi, 0); f = getFolder("Program"); g = getFolder("Mac Desktop"); addFile( "filemacalias", "2.2.2.2", xpiSrc, f, xpiSrc, true); err = File.macAlias(f, xpiSrc, g, xpiSrc + " alias"); logComment("File.macAlias returns: " + err); if (0 == getLastError
()) performInstall
(); else cancelInstall
(); ...
diskSpaceAvailable - Archive of obsolete content
les (see example below). ...
... can use a string representing any file on the disk you want to check, and XPInstall will resolve the reference to the partition itself. ...
...d XPInstall will resolve the reference to the partition itself. ...
cancelInstall - Archive of obsolete content
Summary Aborts installation of the software; performs cleanup of temporary files. Method of Install object Syntax void cancelInstall
() void cancelInstall( int errorCode ) Parameters None. Returns An integer error code. The optional argument is an error code that can be returned to the triggering page. For most purposes, it's recommended that one of the standard return codes be used. But a script can, in fact, return any valid integer. For a list of possible values, and any custom errorCode created by install writer, see Return Codes. ...
...n codes be used. But a script can, in fact, return any valid integer. ...
...an, in fact, return any valid integer. ...
performInstall - Archive of obsolete content
Summary Performs the actual installation of the software. Moves all components to their final locations, launches any pending executions, and registers the package and all of its subcomponents in the Client Version Registry. Method of Install Syntax int performInstall
(); Parameters None. Returns An integer error code. For a list of possible values, see Return Codes. In some situations the method may return other errors. In a few cases you may get a registry error. ...
...er error code. For a list of possible values, see Return Codes. ...
...ssible values, see Return Codes. In some situations the method may return other errors. ...
reserved - Archive of obsolete content
s won't be passed to content, and event listeners registered for them in content will not be executed. Currently, the content still receives these key events, even though it can't override them. In future releases, it won't receive them. See bug 1173061 for details. ...
...In future releases, the event handler will never be called for the given keyboard shortcut. ...
...In future releases, the event handler will never be called for the given keyboard shortcut. ...
Index - Archive of obsolete content
rmation | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] 433 Writing to Files To write to a file, an output stream is used. An output stream is an object which can be used to write bytes, strings and other values to a file. To create an output stream, use nsIScriptableIO.newOutputStream
(). This method has a number of options to specify text or binary writing, the character set, and whether to append to an existing file or create a new one. 434 How to Quit a XUL Application XUL, XULRunner Script can attempt to quit a XUL application, or force the application to quit, using the nsIAppStartup interface. 435 How to implement a custom XUL query processor...
...530 loadURI XUL Methods, XUL Reference NOTE: This is the XUL method on <browser> / <tabbrowser>, not the global function in chrome://browser/content/browser.js. ...
...ver. 1.x) Add-ons, Extensions, SeaMonkey This page tells you step-by-step how to make a custom toolbar button in SeaMonkey 1.x. (For SeaMonkey 2, Firefox, Thunderbird and Sunbird, see the page: Custom Toolbar Button) 961 Toolbar customization events Toolbars, XUL When toolbars are customized, events are sent to their parent window. You can use window.addEventListener
() to listen for these events in order to keep abreast of changes to toolbars. 962 Tree Widget Changes XUL This describes changes in XUL Trees API for Gecko 1.8. 963 Urlbar-icons XUL Reference, XUL_Element The location of UI elements like the bookmarks, feed and go buttons. Create new image or button child elements to add your own items. 964 Using...
appendItem - Archive of obsolete content
<< XUL Reference home appendItem( label, value ) Return type: element Creates a new item and adds it to the end of the existing list of items. You may optionally set a value. The function returns the newly created element. ...
...n returns the newly created element. ...
...addItemsToList
(){ var list = document.getElementById('myMenuList'); // add item with just the label list.appendItem('One'); // add item with label and value list.appendItem('Two', 999); // Select the first item list.selectedIndex = 0; } </script> <button label="Add items" oncommand="addItemsToList
()"/> <menulist id="myMenuList"> <menupopup/> </menulist> See also insertItemAt
() removeItemAt
() ...
removeItemAt - Archive of obsolete content
<< XUL Reference home removeItemAt( index ) Return type: element Removes the child item in the element at the specified index. The method returns the removed item. ...
...he child item in the element at the specified index. The method returns the removed item. ...
...ex == -1){ return; // no item selected so return }else{ myListBox.removeItemAt(myListBox.selectedIndex); } } function removeAllItems
(){ var myListBox = document.getElementById('myListBox'); var count = myListBox.itemCount; while(count-- > 0){ myListBox.removeItemAt(0); } } </script> <button label="Remove selected item" oncommand="removeSelectedItem
()"/> <button label="Remove all items" oncommand="removeAllItems
()"/> <listbox id="myListBox"> <listitem label="Alpha"/> <listitem label="Beta"/> <listitem label="Oscar"/> <listitem label="Foxtrot"/> </listbox> See also removeAllItems
() insertItemAt
() ...
ContextMenus - Archive of obsolete content
he context menu. However, the event will also fire when the label is right-clicked for instance, so the event handler should check to make sure that the target of the contextmenu event is what is desired. To cancel a context menu event, you can use the preventDefault method of the event object. function checkContextMenu(event) { if (event.target.localName == "textbox") event.preventDefault
(); } function init
() { var container = document.getElementById("container"); container.addEventListener("contextmenu", checkContextMenu, true); } The 'checkContextMenu' function checks to see if the textbox was the target of the context menu and, if so, cancels the event using the preventDefault method. This has the effect of disabling the context menu. The event listener is attached using t...
...image might display items pertaining to images, whereas clicking on a link would display items pertaining to links. In many cases, it may be easier to use a single context menu containing every possible item, and show and hide the necessary items when needed. To hide an item, set its hidden property to true. To show an item, set its hidden property to false. ...
...cessary items when needed. To hide an item, set its hidden property to true. To show an item, set its hidden property to false. <script> function showHideDeleteItem
() { var deleteItem = document.getElementById("delete"); var rows = document.getElementById("rows"); deleteItem.hidden = (rows.childNodes.length == 0); } </script> <menupopup id="inssel-menu" onpopupshowing="showHideDeleteItem
()"> <menuitem label="Insert"/> <menuitem id="delete" label="Delete"/> </menupopup> In this example, the showHideDeleteItem function is called when the popupshowing event is fired. This function checks if the element with the id 'rows' has no children and, if so, hides the 'delete' menu item by adjusting the item's hidden property. When the user attempts to open the context menu, the delete me...
Extensions - Archive of obsolete content
ly to that type of element are hidden from the menu as needed. Thus, you can add items to the Firefox context menu by overlaying this single menu. This context menu has the id 'contentAreaContextMenu'. In this example, a single item is added to the end of the Firefox context menu. <popup id="contentAreaContextMenu"> <menuitem id="thumbnail-show" label="View Thumbnail" oncommand="Thumbnails.view
();"/> </popup> Note that the popup element is used rather than the menupopup element as this is the element that Firefox uses. The code above will append the new item at the end of the context menu. If you want to place the item at a specific location within the context menu rather than at the end, you can use either the insertbefore or insertafter attributes to insert it before or after another...
...em at a specific location within the context menu rather than at the end, you can use either the insertbefore or insertafter attributes to insert it before or after another item specified by an id. For example, the following may be used to insert a command just after the 'Select All' command: <popup id="contentAreaContextMenu"> <menuitem label="Select Links" oncommand="Thumbnails.selectAllLinks
();" insertafter="context-selectall"/> </popup> See Firefox Context Menu for a list of the ids of the items found on the Firefox context menu. Showing and hiding context menu items To have a menuitem you have added be shown or hidden based on the context, you can use an event handler that listens for the popupshowing event. For instance, if an image was context clicked, you may wish ...
...of the items found on the Firefox context menu. Showing and hiding context menu items To have a menuitem you have added be shown or hidden based on the context, you can use an event handler that listens for the popupshowing event. For instance, if an image was context clicked, you may wish to hide the menu item you have added if the operation it performed wouldn't apply to images. ...
MenuItems - Archive of obsolete content
hecked attribute as the menuitem will update this automatically before the command event is fired. Note that the checked state is updated before the command event fires, so if you use the menuitem's checked attribute within the command listener, it will already be in the new state. <script> function changeToolbarState(event) { if (event.target.getAttribute("checked") == "true") showToolbar
(); else hideToolbar
(); } </script> ... <menuitem label="Show Toolbar" accesskey="T" type="checkbox" oncommand="changeToolbarState
();"/> In this example, we show the toolbar when the menuitem is checked and hide the toolbar otherwise. There may be times when you do not want the checkbox state to be updated automatically when the menuitem is activated. This can be useful if there's...
...he checkbox state again. As this can be more complicated, it is also possible to use the autocheck attribute to disable this behavior. When the autocheck attribute is set to false, the checkbox state is not updated automatically, and you must write code to adjust the state yourself. <script> function changeToolbarState(event) { if (event.target.getAttribute("checked") == "true") hideToolbar
(); event.target.removeAttribute("checked"); } else { if (!showToolbar
()) return; event.target.setAttribute("checked", "true"); } } </script> ... <menuitem label="Show Toolbar" accesskey="T" type="checkbox" autocheck="false" oncommand="changeToolbarState
();"/> This version of the changeToolbarState function changes the checked attribute itself. The autocheck attri...
...checked attribute itself. The autocheck attribute has been set to false on the menuitem so the checked attribute will not be updated automatically. Note that the code has been reversed in the condition blocks to hide the toolbar when the menuitem is checked and show the toolbar when the menuitem is not checked because the checked state hasn't been modified. The example assumes that the showToolbar
() function might fail so if it returns false, the checked attribute is not modified. When clearing the checked state, the checked attribute should be removed rather than just set to false. In the example, this is done by using the removeAttribute method. Radio menu items A radio menu item os used when you wish to have a group of menuitems in which only one can be checked at a time. This works si...
MenuModification - Archive of obsolete content
Modifying a Menu Menus have a number of methods which may be used to add and remove items. Adding Items to a Menu The appendItem method may be used to append a new item to the end of the popup associated with a menu. This method will create a new menuitem element and insert it into the popup. This method may only be used with the menu element. <script> function addToMenu
() { var menu = document.getElementById("edit-menu"); menu.appendItem("Insert", "insert"); } </script> <menu id="edit-menu"/> <button label="Add" oncommand="addToMenu
()"/> In this example, the addToMenu function is called when the button is pressed. This function appends a new item to the menu's popup with the label Insert. The first argument to appendItem is the label of the menuitem, and the second argume...
...le: var item = menu.appendItem("Insert", "insert"); item.accessKey = "I"; Appending Submenus There is no built-in method to append submenus to a menu. To do this, we instead need to use the inherited node modification methods available for all elements. First, we need to retrieve the menupopup for the menu, and then use the appendChild method to append a new item. <script> function addSubMenu
() { var popup = document.getElementById("file-popup"); var newmenu = document.createElement("menu"); popup.appendChild(newmenu); newmenu.label = "New"; newmenu.appendItem("Document", "doc"); newmenu.appendItem("Image", "image"); } </script> <menu label="File" onpopupshowing="addSubMenu
()"> <menupopup id="file-popup"/> </menu>. Comment: appendItem not working in TB 52.7.0. Workaroun...
... example above, we would also want to make sure to remove the items again in a popuphiding event listener. Otherwise, a new submenu would be added every time the menu is opened, which is clearly not desirable. Another possibility is to ensure that the menu is only added once. The following shows how the addSubMenu function above might be rewritten to handle this case. <script> function addSubMenu
() { var popup = document.getElementById("file-popup"); if (popup.hasChildNodes
()) return; var newmenu = document.createElement("menu"); popup.appendChild(newmenu); newmenu.label = "New"; newmenu.appendItem("Document", "doc"); newmenu.appendItem("Image", "image"); } </script> The hasChildNodes method may be used to check if a node has any children. The first time the function is...
Panels - Archive of obsolete content
r more details about both methods, see Opening and Closing Popups. Closing a panel A panel is closed automatically when the user clicks outside of the panel. It is quite common however, to have an element such as a button within the panel to close it as well. For instance, using the search panel example above, we could add a button which closes the panel when pressed: <script> function doSearch
() { document.getElementById("search-panel").hidePopup
(); } </script> <toolbarbutton label="Search" type="panel"> <panel id="search-panel" position="after_start"> <textbox id="search"/> <button label="Search" oncommand="doSearch
();"/> </panel> </toolbarbutton> In this example, the doSearch
() function is called when the "Search" button is pressed. This function retrieves the popup an...
...panel, especially if the panel is larger with a lot of controls within it. Sometimes, however, you may wish to keep the panel open, even if the user clicks outside of it. This is useful when creating floating tool panels. To do this, set the noautohide attribute on the panel to true. <panel id="search-panel" noautohide="true"> <textbox id="search"/> <button label="Search" oncommand="doSearch
();"/> <button label="Cancel" oncommand="this.parentNode.hidePopup
();"/> </panel> Because the panel can no longer be closed by clicking elsewhere, the panel should always provide a means to close the panel itself. In this example a cancel button has been added. For more information about these types of panels, see Floating Panels. Focus in panels Elements within panels may be focused with the...
...he popup panel is focused by default, the user may focus the first element within the panel by pressing the Tab key. If you want to set the focus to an element by default when a panel is opened, adjust the focus within a popupshown event handler. For instance, to have the textbox initially focused in the example above: <panel id="search-panel" onpopupshown="document.getElementById('search').focus
()"> To disable the adjusting of focus when a panel is opened, set the noautofocus attribute to true: <panel noautofocus="true"> This will cause the focus to remain on the element within the main window that has focus when the panel is opened. Note that this will also keep the focus within the panel when it is closed. When a panel is closed, the focus is removed from the element within the pan...
Code Samples - Archive of obsolete content
tem knows how to open. Note: On operating systems that use backslash characters, double each backslash character. On operating systems that use forward-slash characters, specify the file in the normal way. const path = "C:\\WINDOWS\\CHARMAP.EXE" var file = Components .classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile) file.initWithPath(path) file.launch
() Open a web page If your button is in Firefox or SeaMonkey, use code like this to open a web page. Change the first line to specify the page that you want to open: const url = "http://www.mozilla.org/" document .getElementById("content") .webNavigation .loadURI(url, 0, null, null, null) If your button is in Thunderbird or Sunbird, use code like this to open a web page. Change the first li...
... application's windows, use code like this. If the window already exists, this code just focusses it. Otherwise it opens the window: const name = "...internal name of the window..." const uri = "...chrome URI of the window..." var w = Components .classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator) .getMostRecentWindow(name) if (w) w.focus
() else Components .classes["@mozilla.org/embedcomp/window-watcher;1"] .getService(Components.interfaces.nsIWindowWatcher) .openWindow(null, uri, name, "chrome,resizable", null) Change the first two lines to specify the window that you want to open. Here are the names and URIs of some windows: Thunderbird Configuration const name = "Preferences:ConfigManager" ...
... IRC Chat const name = "irc:chatzilla" const uri = "chrome://chatzilla/content/" Calendar const name = "calendarMainWindow" const uri = "chrome://calendar/content/" * At the time of writing, Sunbird's Passwords window is broken Close the current window To close the window containing the button, possibly leaving other windows open: close
() Exit the application To exit the application, first closing all its windows: Components .classes['@mozilla.org/toolkit/app-startup;1'] .getService(Components.interfaces.nsIAppStartup) .quit(Components.interfaces.nsIAppStartup.eAttemptQuit) ...
Custom toolbar button - Archive of obsolete content
Change the text between double-quote characters on these two lines. Optionally remove the sections for toolbars that you do not need. Save the file. Explanation: This XUL file adds the button to the application's too...
... {-moz-image-region: rect(24px 40px 40px 24px);} There is nothing to customize. Save the file. Explanation: This CSS stylesheet specifies how the button is displayed. It links to the button image, specifying the dimensions of the four parts of the image. 8. Create a plain text file named button.js. Copy the following content, and paste it into the new file: CustomButton = { 1: function
() { alert("Just testing") }, } There is nothing to customize for now. Save the file. The next section in this tutorial contains examples of code that you can use to make your button do something useful. Explanation: This file specifies what happens when you press the button. It uses the JavaScript programming language, together with features provided by the application. 9. Download the...
... the label and tooltiptext attributes to whatever you want. Do not change the class attribute. Now edit button.css. Duplicate the first three lines, changing the new lines to specify button-2. Edit button.js and add JavaScript code for the new button. Be sure to add the extra code before the curly brace on the last line of the file. For example, you could add this code for testing: 2: function
() { alert("Just testing again") }, Create an image for the new button, naming the file button-2.png. The images supplied here are 40 pixels wide and 48 pixels high, with a 256-colour palette and a transparent background, in PNG format. Some other formats will also work. Here are some more images that you can download and use: Restart the application and customize the toolbar to find...
Additional Install Features - Archive of obsolete content
special string which means the root of the filesystem. From there, we get the file 'grep' which is contained inside the 'bin' directory. If this file does not exist, an error will occur during the installation. Next, we get the 'main' folder, again from the file system root. Finally, we call the File.copy function which copies the source file to the destination. Functions also exist to move
(), rename
() and execute
() files. Thus, you can move files that might conflict with your package out of the way. Handling Errors You will likely want to handle errors gracefully. This will occur if a file or directory cannot be found, there is insufficient disk space or for a number of other reasons. You can use the getLastError
() function to determine whether an error occured. If it returns SUCCESS...
...h indicates the type of error that occured. You can call this function at any point during the installation script to determine whether an error occured during the last operation. If an error occurs, you will likely want to abort the installation. You may also want to display an error message to the user. For example, you might put the following as the last section of your script: if (getLastError
() == SUCCESS) { performInstall
(); } else { cancelInstall
(); } Error codes that could be returned by getLastError
() are listed in the Mozilla source file nsInstall.h. During installation, a log file is created that contains the operations that are performed. It will also show any errors that occured. The log file can be found in the file 'install.log' in the Mozilla installation directory. A bl...
...It takes one argument, the text to write. ...
Creating a Wizard - Archive of obsolete content
thing once the Finish button is pressed. You can set an attribute onwizardfinish on the wizard element to accomplish this. Set it to a script which performs whatever task you want and then returns true. This script might be used to save the information that the user entered during the wizard. ...
...ich performs whatever task you want and then returns true. This script might be used to save the information that the user entered during the wizard. For example: <wizard id="example-window" title="Select a Dog Wizard" onwizardfinish="return saveDogInfo
();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> When the user clicks the Finish button, the function saveDogInfo
() will be called, which would be defined in a script file to save the information that was entered. If the function returns true, the wizard closes. If it returns false, then the wizard does not close, which might occur if the function saveDogInfo
() encountered invalid input, for example. There are also related onwizardback, onwizardnext and onwizardcancel attributes, which are called when the Bac...
...ge that the user is leaving. pageadvanced wizardpage Called on the page the user is leaving. wizardnext wizard Called on the wizard. pageshow wizardpage Called on the page that the user is entering. A similar process occurs for the Back button. When trying to use a function in the event above, such as pageadvanced, you should use return funcName
() instead of just calling funcName
() or it will not work as expected e.g. <wizardpage pageadvanced='return funcName
()'></wizardpage> In the next section, we'll see some additional features of wizards. << PreviousNext >> ...
Keyboard Shortcuts - Archive of obsolete content
the Keyboard Shortcuts Now that we know how to define keyboard shortcuts, we'll find out how we can use them. There are two ways. The first way is the simplest and just requires that you use the command event handler on the key element. When the user presses the key, the script will be invoked. An example is shown below: <keyset> <key id="copy-key" modifiers="accel" key="C" oncommand="DoCopy
();"/> </keyset> The function DoCopy will be called when the user presses the keys specified by the key element, which in this example, are the keys for copying to the clipboard (such as Control + C). This will work as long as the window is open. The DoCopy function should check to see if text is selected and then copy the text to the clipboard. Note that textboxes have the clipboard shortcuts bui...
... and also one for the Close command when the user presses Esc. ...
...w.close
();"/> </keyset> <vbox flex="1"> <toolbox> <menubar id="findfiles-menubar"> <menu id="file-menu" label="File" accesskey="f"> <menupopup id="file-popup"> <menuitem label="Open Search..." accesskey="o"/> <menuitem label="Save Search..." accesskey="s"/> <menuseparator/> <menuitem label="Close" accesskey="c" key="close_cmd" oncommand="window.close
();"/> </menupopup> </menu> <menu id="edit-menu" label="Edit" accesskey="e"> <menupopup id="edit-popup"> <menuitem label="Cut" accesskey="t" key="cut_cmd"/> <menuitem label="Copy" accesskey="c" key="copy_cmd"/> <menuitem label="Paste" accesskey="p" key="paste_cmd" disabled="true"/> </menupopup> </menu> </menubar> </toolbox> </vbox> </window> Now we...
Using nsIXULAppInfo - Archive of obsolete content
tformVersion; var platformBuildID = appInfo.platformBuildID; Getting nsIXULAppInfo in xpcshell tests In Firefox 21, a testing module was added that provides access to app info during the execution of xpcshell tests. See Bug 809920, and in summary: // Work around the fact that xpcshell doesn't have a proper app-info XPCOM object. Cu.import("resource://testing-common/AppInfo.jsm"); updateAppInfo
(); Older versions As stated above, older Mozilla 1.7-based applications do not support nsIXULAppInfo. You'll have to write additional code if you choose to support those versions. For example, Firefox and Thunderbird 1.0 stored their ID in the app.id preference (and their version in app.version), so you could use code like this to find out what application you're running under: function getAppI...
... Older versions As stated above, older Mozilla 1.7-based applications do not support nsIXULAppInfo. You'll have to write additional code if you choose to support those versions. ...
...zilla.org/xre/app-info;1"] .getService(Components.interfaces.nsIXULAppInfo).ID; } else { try { id = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefBranch) .getCharPref("app.id"); } catch(e) { // very old version dump(e); } } return id; } alert(getAppID
()); See also MXR: nsIXULAppInfo.idl ...
script - Archive of obsolete content
to declare a script to be used by the XUL window. You should usually put scripts in a separate file pointed to by the src attribute, but you may also place the script inline inside the opening and closing script tags. More information is available in the XUL tutorial. Attributes src, type Examples <script src="test.js"/> <script src="http://example.com/js/test.js"/> <script> function foo
(){ // code } </script> Attributes src Type: URI The URI of the script. type Type: language content type The language of the script. Usually, you would set this to application/javascript. Note: If the JavaScript file is in chrome://, setting this attribute to application/javascript will always use the latest available JavaScript version. If you omit this attribute, the def...
...ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
scrollbox - Archive of obsolete content
t use a scrollbox tag; you only need that tag if you want to programmatically scroll in addition to the automatic scroll bars. Note: avoid nested scroll boxes; it's maddening for the experienced user and confusing for the less experienced user. Instead, figure out some other way to lay things out. Scrolling a child element into view See element.scrollIntoView. Prior to Gecko 19, scrollIntoView
() didn't exist in XUL. Do this instead: var xpcomInterface =scrollbox_element.boxObject.QueryInterface( Components.interfaces.nsIScrollBoxObject); xpcomInterface.ensureElementIsVisible(child_element_to_make_visible); See the nsIScrollBoxObject API for other scroll-related methods. Attributes Inherited from XUL element align, allowevents, allownegativeassertions, class, coa...
...ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
titlebar - Archive of obsolete content
s This XUL file will create a HUD-style window that can be moved with the mouse. It will close if the mouse button is released. ...
...ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
toolbarpalette - Archive of obsolete content
add your own custom buttons to the Firefox browser by using an overlay that overlays the toolbarpalette with the idBrowserToolbarPalette. ...
...ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
treecell - Archive of obsolete content
s not used for any specific purpose, but you can access it with a script for your own use. Be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an element, you could 1) Use another attribute like "value2" or "data-myAtt" (as in the HTML5 draft), as XUL does not require validation (less future-proof); 2) Use setAttributeNS
() to put custom attributes in a non-XUL namespace (serializable and future-proof); 3) Use setUserData
() (future-proof and clean, but not easily serializable). For user editable menulist elements, the contents, as visible to the user, are read and set using the Menulist.value syntax. For those elements, setAttribute("value", myValue) and getAttribute("value") do not access or affect the contents dis...
...ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
Debugging a XULRunner Application - Archive of obsolete content
. Browser Debugger As of Gecko 44, it is no longer possible to start the DevTools server from XUL apps. See bug 1244163. Starting with XULRunner 24, you should use the Firefox Browser Debugger to debug your XULRunner apps. Add the following code to your XUL app: Components.utils.import('resource://gre/modules/devtools/dbg-server.jsm'); if (!DebuggerServer.initialized) { DebuggerServer.init
(); // Don't specify a window type parameter below if "navigator:browser" // is suitable for your app. DebuggerServer.addBrowserActors("myXULRunnerAppWindowType"); } DebuggerServer.openListener(6000); For XULRunner version 37+ the code to enable the debugger has changed: Components.utils.import('resource://gre/modules/devtools/dbg-server.jsm'); if (!DebuggerServer.initialized) { Debugger...
...t specify a window type parameter below if "navigator:browser" // is suitable for your app. DebuggerServer.addBrowserActors("myXULRunnerAppWindowType"); } DebuggerServer.openListener(6000); For XULRunner version 37+ the code to enable the debugger has changed: Components.utils.import('resource://gre/modules/devtools/dbg-server.jsm'); if (!DebuggerServer.initialized) { DebuggerServer.init
(); DebuggerServer.addBrowserActors
(); DebuggerServer.allowChromeProcess = true; } let dbgListener=DebuggerServer.createListener
(); dbgListener.portOrPath=6000; dbgListener.open
(); Add the following to your prefs.js: (in recent ffox, edit about:config instead) pref("devtools.debugger.remote-enabled", true); In Firefox, go to Tools > Web Developer > Connect... and you should be able to poin...
...ting). To download the package, right-click the install link and save the package locally. Create a directory <application>/distribution/bundles/venkman. Unzip the package into that directory. Add <script src="chrome://venkman/content/venkman-overlay.js" /> to one of your XUL windows. Add UI to open Venkman to your window (it could be a menu item or a toolbar button). Make it call start_venkman
() when activated. Troubleshooting x-jsd is not a registered protocol If the message "x-jsd is not a registered protocol" appears when trying to open *.js files in Venkman, then add an empty file called .autoreg in the same directory as your XULRunner binary. If .autoreg already exists, then edit it to force the last modified time to be updated. XULRunner will then notice the new components file...
Getting started with XULRunner - Archive of obsolete content
javascript.options.showInConsole", true); pref("javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true); XULRunner specific preferences include: toolkit.defaultChromeURI Specifies the default window to open when the application is launched. toolkit.defaultChromeFeatures Specifies the features passed to window.open
() when the main application window is opened. toolkit.singletonWindowType Allows configuring the application to allow only one instance at a time. The toolkit preferences are described in further detail in XULRunner:Specifying Startup Chrome Window. The debugging preferences are discussed in Debugging a XULRunner Application Step 7: Create some XUL Finally, we need to create a simple XUL w...
...XUL is simple to use and quite powerful and can even be used on mobile devices.</description> </window> Note: Make sure there is no extra whitespace at the beginning of the XML/XUL file The application also has a JavaScript file. Most XUL applications will include some external JavaScript, s...
...mple to use and quite powerful and can even be used on mobile devices.</description> </window> Note: Make sure there is no extra whitespace at the beginning of the XML/XUL file The application also has a JavaScript file. Most XUL applications will include some external JavaScript, so the sample application does too, just to show how to include it into the XUL file. main.js: function showMore
() { document.getElementById("more-text").hidden = false; } For more information about XUL see: XUL. For information about mixing HTML elements into your XUL read Adding HTML Elements. Step 8: Run the application The moment of truth. We need to get XULRunner to launch the bare-bones application. Windows From a Windows command prompt opened to the myapp folder, we should be able to execute...
Windows and menus in XULRunner - Archive of obsolete content
s" type="text/css"?> <!DOCTYPE window SYSTEM "chrome://basicapp/locale/main.dtd"> <window id="main" title="&title;" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script src="main.js"/> <toolbox> <menubar id="menubar"> <menu id="file-menu" label="&file;"> <menupopup id="file-popup"> <menuitem label="&file.new;" oncommand="doFileNew
();"/> <menuitem label="&file.open;" oncommand="doFileOpen
();"/> <menuitem label="&file.save;" oncommand="doFileSave
();"/> <menuseparator/> <menuitem label="&file.exit;" oncommand="doFileExit
();"/> </menupopup> </menu> <menu id="edit-menu" label="&edit;"> <menupopup id="edit-popup"> <menuitem label="&edit.undo;" oncommand=...
... <menuitem label="&file.open;" oncommand="doFileOpen
();"/> <menuitem label="&file.save;" oncommand="doFileSave
();"/> <menuseparator/> <menuitem label="&file.exit;" oncommand="doFileExit
();"/> </menupopup> </menu> <menu id="edit-menu" label="&edit;"> <menupopup id="edit-popup"> <menuitem label="&edit.undo;" oncommand="doEditUndo
();"/> <menuitem label="&edit.redo;" oncommand="doEditRedo
();"/> </menupopup> </menu> </menubar> <toolbar id="main-toolbar"> <toolbarbutton id="open" label="&file.open;" oncommand="doFileOpen
();"/> <toolbarbutton id="save" label="&file.save;" oncommand="doFileSave
();"/> </toolbar> </toolbox> ... </window> Notice that I used entity-references for th...
...d event is hooked up to JavaScript, just like an onclick in HTML. The JavaScript is contained in the main.js file. XUL has a way to centralize commands and event handlers for menus and toolbars that do the same thing, like open and save in the above example. You can add a <commandset> and <command> elements like this: <commandset> <command id="cmd_open" label="&file.open;" oncommand="doFileOpen
();"/> <command id="cmd_save" label="&file.save;" oncommand="doFileSave
();"/> </commandset> ... <menuitem command="cmd_open"/> <menuitem command="cmd_save"/> ... <toolbarbutton id="open" command="cmd_open"/> <toolbarbutton id="save" command="cmd_save"/> ... We can add images to the toolbar buttons through the CSS file. We could hard-code the images in the XUL file itself, but CSS is a better pr...
calICalendarViewController - Archive of obsolete content
&& !aIID.equals(Components.interfaces.nsISupports)) { throw Components.results.NS_ERROR_NO_INTERFACE; } return this; }, createNewEvent: function (aCalendar, aStartTime, aEndTime) { // if we're given both times, skip the dialog if (aStartTime && aEndTime && !aStartTime.isDate && !aEndTime.isDate) { var event = createEvent
(); event.startDate = aStartTime; event.endDate = aEndTime; event.title = "New Event"; aCalendar.addItem(event, null); } else if (aStartTime && aStartTime.isDate) { var event = createEvent
(); event.startDate = aStartTime; aCalendar.addItem(event, null); } else { createEventWithDialog(aCale...
...hDialog(aCalendar, aStartTime, aEndTime); } }, modifyOccurrence: function (aOccurrence, aNewStartTime, aNewEndTime) { // if we can modify this thing directly (e.g. ...
...; instance.startDate = aNewStartTime; instance.endDate = aNewEndTime; instance.calendar.modifyItem(instance, aOccurrence, null); } else { modifyEventWithDialog(aOccurrence); } }, deleteOccurrence: function (aOccurrence) { if (aOccurrence.parentItem != aOccurrence) { var event = aOccurrence.parentItem.clone
(); event.recurrenceInfo.removeOccurrenceAt(aOccurrence.recurrenceId); event.calendar.modifyItem(event, aOccurrence, null); } else { aOccurrence.calendar.deleteItem(aOccurrence, null); } } }; History calICalendarViewController was introduced as part of the 'backend rewrite' that occurred prior to Lightning 0.1 and between Sunbird 0.2 and S...
Mozprocess - Archive of obsolete content
TODO Document improvements over subprocess.Popen.kill ...
...TODO Document improvements over subprocess.Popen.kill ...
...TODO Document improvements over subprocess.Popen.kill ...
NPByteRange - Archive of obsolete content
gth Number of bytes to fetch from the specified offset. next Points to the next NPByteRange request in the list of requests, or null if this is the last request. ...
...ange objects, which represents a set of discontiguous byte ranges. The only plug-in API call that uses the NPByteRange type is NPN_RequestRead
(), which lets the plug-in read specified parts of a file without downloading it. The plug-in is responsible for deleting NPByteRange objects when finished with them. ...
...s a set of discontiguous byte ranges. The only plug-in API call that uses the NPByteRange type is NPN_RequestRead
(), which lets the plug-in read specified parts of a file without downloading it. The plug-in is responsible for deleting NPByteRange objects when finished with them. ...
NPN_UserAgent - Archive of obsolete content
has the following parameter: instance Pointer to the current plug-in instance. Returns A pointer to a buffer that contains the user agent field of the browser. ...
...urns A pointer to a buffer that contains the user agent field of the browser. ...
...to a buffer that contains the user agent field of the browser. Description The user agent is the part of the HTTP header that identifies the browser during transfers. ...
Accessing XML children - Archive of obsolete content
f the type "bar". IMPORTANT It is your responsibility to determine whether you have an XML list or a single element when using the . operator. E4X behaves no differently when returning these properties. The XML list behaves much like an array. var element = <foo> <bar baz="1">red</bar> <bar baz="2">blue</bar> </foo>; var list = element.bar; list.length
(); // returns 2 list[0]; // the first bar element list[1]; // the second bar element Notice further that this list is "live" in the sense that changes made to the list are reflected back in the element that the list originally came from. list[1] = "green"; changes the XML document to read <foo> <bar baz="1">red</bar> <bar baz="2">green</bar> </foo> Special types of nodes XML objects have me...
...made to the list are reflected back in the element that the list originally came from. list[1] = "green"; changes the XML document to read <foo> <bar baz="1">red</bar> <bar baz="2">green</bar> </foo> Special types of nodes XML objects have methods for accessing XML lists of certain common types of nodes as well. var a = <foo> Some text <bar>not text</bar> More text </foo>; var list = a.text
(); list.length
(); // returns 2 list[0]; // returns " Some text " list[1]; // returns " More text " You can similarly access comment nodes: XML.ignoreComments = false; var a = <foo> Some <!-- abc --> text </foo>; var comments = a.comments
(); alert(comments[0]); // Returns <!-- abc --> The * selector will return all child nodes in an XML list. var a = <foo> <bar/> <baz/> ...
...; // returns " Some text " list[1]; // returns " More text " You can similarly access comment nodes: XML.ignoreComments = false; var a = <foo> Some <!-- abc --> text </foo>; var comments = a.comments
(); alert(comments[0]); // Returns <!-- abc --> The * selector will return all child nodes in an XML list. var a = <foo> <bar/> <baz/> </foo>; var list = a.*; list.length
(); // returns 2 Element attributes Many XML elements have attributes with particular values assigned to them. For instance <pets> <dog color="brown">Fido</dog> <cat color="grey">Fluffy</cat> </pets> E4X allows you to access the attributes of a particular element with the .@ operator. The most basic case would look something like. var element = <foo bar="1"/> element.@bar = 2; which gives <...
Namespaces - Archive of obsolete content
repeating the statement. ...
...e statement. ...
...info.uri; // returns "http://www.w3.org/1999/xhtml" Elements in no namespace return the empty string as their uri. The Namespace global constructor is very similar to QName. Namespace differs in its toString method, and in that it has a prefix property instead of a localName property. For further information on namespaces in E4X, see Processing XML with E4X. ...
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
status Optional The status of the asynchronous operation. If not specified, Debug.MS_ASYNC_OP_STATUS_SUCCESS is used. Remarks Call this function when the asynchronous operation completes. asyncOperationId must correspond to the operation ID previously returned from Debug.msTraceAsyncOperationStarting. ...
...erationStarting. The possible values for status include: Debug.MS_ASYNC_OP_STATUS_SUCCESS Debug.MS_ASYNC_OP_STATUS_CANCELED Debug.MS_ASYNC_OP_STATUS_ERROR Note: Some debugging tools do not display the information sent to the debugger. Example The following code provides an example of tracing an asynchronous call for a Windows 8.x Store app. function asyncWrapperFunction
() { var opID = Debug.msTraceAsyncOperationStarting('async trace'); doSomethingAsync
().then(function (result) { Debug.msTraceAsyncOperationCompleted(opID, Debug.MS_ASYNC_OP_STATUS_SUCCESS); Debug.msTraceAsyncCallbackStarting(opID); // Process result of async operation. }, function (error) { Debug.msTraceAsyncOperationCompleted(opID, Debug.MS_ASYNC_OP_STATU...
...result) { Debug.msTraceAsyncOperationCompleted(opID, Debug.MS_ASYNC_OP_STATUS_SUCCESS); Debug.msTraceAsyncCallbackStarting(opID); // Process result of async operation. }, function (error) { Debug.msTraceAsyncOperationCompleted(opID, Debug.MS_ASYNC_OP_STATUS_ERROR); Debug.msTraceAsyncCallbackStarting(opID); }); Debug.msTraceAsyncCallbackCompleted
(); } function doSomethingAsync
() { return WinJS.Promise.as(true); } asyncWrapperFunction
(); Requirements Supported in the Internet Explorer 11 standards document mode. Also supported in Store apps (Windows 8.1 and Windows Phone 8.1). Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet ...
VBArray - Archive of obsolete content
ts. The first part is VBScript code to create a Visual Basic safe array. The second part is JavaScript code that converts the Visual Basic safe array to a JavaScript array. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JavaScript code that goes in the <BODY> section to run the other two parts. ...
... Methods VBArray.dimensions Returns the number of dimensions in a VBArray. ...
... Methods VBArray.dimensions Returns the number of dimensions in a VBArray. ...
Packages - Archive of obsolete content
ess the public methods and fields of an arbitrary Java class from within JavaScript. The java, netscape, and sun properties represent the packages java.*, netscape.*, and sun.* respectively. Use standard Java dot notation to access the classes, methods, and fields in these packages. ...
...You must use the Packages object to access classes outside the netscape, sun, and java packages. ...
...ified name of a Java class in a package other than netscape, java, or sun that is available to JavaScript. java: Any class in the Java package java.*. netscape: Any class in the Java package netscape.*. sun: Any class in the Java package sun.*. Examples Example: JavaScript function to create a Java dialog box The following JavaScript function creates a Java dialog box: function createWindow
() { var theOwner = new Packages.java.awt.Frame
(); var theWindow = new Packages.java.awt.Dialog(theOwner); theWindow.setSize(350, 200); theWindow.setTitle("Hello, World"); theWindow.setVisible(true); } In the previous example, the function instantiates theWindow as a new Packages object. The setSize, setTitle, and setVisible methods are all available to JavaScript as public methods ...
Mozilla XForms Specials - Archive of obsolete content
ol use: @namespace xf url("http://www.w3.org/2002/xforms"); xf|input .xf-value { ... } The pseudo elements are defined in the CSS3 Basic User Interface specification . (limitation tracked in bug 271724) Optional parameters in XPath functions Optional parameters in XPath functions are not supported, you will have to specify all parameters when calling a function. This affects functions like hmac
() or digest
(). Instead of using digest('abc', 'SHA-1') explicitly use the third parameter (the results are equal): digest('abc', 'SHA-1', 'base64') (limitation tracked in bug 477857) Extensions Enumerating Instances The standardized nsIXFormsModelElement does not allow one to enumerate over all possible instances, but only to retrieve instances by their name. In the Mozilla XForms Extension we ...
...ng digest('abc', 'SHA-1') explicitly use the third parameter (the results are equal): digest('abc', 'SHA-1', 'base64') (limitation tracked in bug 477857) Extensions Enumerating Instances The standardized nsIXFormsModelElement does not allow one to enumerate over all possible instances, but only to retrieve instances by their name. In the Mozilla XForms Extension we added a getInstanceDocuments
() function to the model which returns all the model's instance documents. This is documented in nsIXFormsNSModelElement. Getting To Instance Element From A Data Node In the XForms 1.0 specification there is no way to get to the instance element from an instance data node. We have added a function via the getFeature
() call on each node, that allows the form author to do that. That is, if instanceNod...
....getFeature("org.mozilla.xforms.instanceOwner", "1.0") will return the <instance> element (in the main document) that the node belongs to. Getting To The Instance Document From The Instance Element In the XForms 1.0 specification you have to go through the model element to get to the instance document. It seems a bit awkward if you have the instance element, so we have added a getInstanceDocument
() function directly on the instance element as a shortcut. This is documented in nsIXFormsNSInstanceElement. Custom Control Interface We have added a lot of functionality to our user interface, which allows the form authors to create custom controls. It involves exposing some (script) functionality on all our controls, like output, input, etc. and allowing the UI to be represented in XBL. More info...
Archived open Web documentation - Archive of obsolete content
ML documents than via DOM interfaces. A valid alternative to E4X is a non-native JXON algorithm. E4X Tutorial This tutorial walks you through the basic syntax of E4X (ECMAScript for XML). With E4X, programmers can manipulate an XML document with a syntax more familiar to JavaScript programming. Talk:Array.forEach
() Ok, in the end I didn't remove the old code as it isn't hosted anywhere (I thought the github reference contained the code) but inserted a faster implementation above while retaining the rest of the document. Iterator The Iterator function returns an object which implements legacy iterator protocol and iterates over enumerable prope...
...TML 4 as an XML 1.0 application. Talk:JavaScript Reference 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 languag...
...of the iteration in the legacy iterator protocol. Do not use this ancient feature. Styling the Amazing Netscape Fish Cam Page Using JavaScript Generators in Firefox Generators can be used to simplify asynchronous code in Firefox by opting in to using JavaScript version 1.7 or later. You can opt in in HTML as follows: Window.importDialog
() Because opening windows on mobile isn't necessarily appropriate, the Firefox Mobile team designed the importDialog
() method to replace window.openDialog
(). Instead of opening a new window, it merges the specified XUL dialog into the main window. Writing JavaScript for XHTML Technical review completed. Editorial review completed. ...
2D collision detection - Game development
Circle Collision Another simple shap...
...ion: static !important; height: 200px !important; } Crafty.init(200, 200); var dim1 = {x: 5, y: 5} var dim2 = {x: 20, y: 20} Crafty.c("Circle", { circle: function(radius, color) { this.radius = radius; this.w = this.h = radius * 2; this.color = color || "#000000"; this.bind("Move", Crafty.DrawManager.drawAll) return this; }, draw: function
() { var ctx = Crafty.canvas.context; ctx.save
(); ctx.fillStyle = this.color; ctx.beginPath
(); ctx.arc( this.x + this.radius, this.y + this.radius, this.radius, 0, Math.PI * 2 ); ctx.closePath
(); ctx.fill
(); ctx.restore
(); } }); var circle1 = Crafty.e("2D, Canvas, Circle").attr(...
... this.color = "green"; } else { // no collision this.color = "blue"; } }); var...
WebVR — Virtual Reality for the Web - Game development
two concepts -- sending stereoscopic images to both lenses in your headset and receiving positional data for your head from the sensor, and those two are handled by HMDVRDevice (head-mounted display virtual reality device) and PositionSensorVRDevice. ...
...estFOV = new VRFieldOfView(up,right,down,left); gHMD.setFieldOfView(testFOV,testFOV,0.01,10000.0); } The gPositionSensor variable holds the PositionSensorVRDevice -- using this you can get the current position or orientation state (for example to update the scene view on every frame), or reset the sensor. ...
...; gHMD.setFieldOfView(testFOV,testFOV,0.01,10000.0); } The gPositionSensor variable holds the PositionSensorVRDevice -- using this you can get the current position or orientation state (for example to update the scene view on every frame), or reset the sensor. ...
Efficient animation for web games - Game development
s = 0; if (startTime < 0) { startTime = timestamp; } else { progress = timestamp - startTime; } // Do animation ... if (progress < animationLength) { requestAnimationFrame(doAnimation); } } // Start animation requestAnimationFrame(doAnimation); You will note that we set startTime to -1 at the beginning, when we could just as easily have set the time using the Date
() object and avoided the extra code in the animation callback. We do this so that any setup or processes that happen between the start of the animation and the callback being processed do not affect the start of the animation, and so that all the animations we start before the frame is processed are synchronised. To save battery life, it is best to only draw when there are things going on, so that...
...estAnimationFrame (though, in our experience, it is in the order in which they were requested), so this also helps cut out any ambiguity. An easy way to do this is to declare your own refresh function that sets a flag when it calls requestAnimationFrame. When the callback is executed, you can unset that flag so that calls to that function will request a new frame again, like this: function redraw
() { drawPending = false; // Do drawing ... } var drawPending = false; function requestRedraw
() { if (!drawPending) { drawPending = true; requestAnimationFrame(redraw); } } Following this pattern -- or something similar -- means that no matter how many times you call requestRedraw, your drawing function will only be called once per frame. Remember that when you do drawing with req...
...r animating object properties. Puzzowl uses it to drive all the drawing updates and transitions, by overriding its requestAnimationFrame function with a custom version that makes the request, and appending the game's drawing function onto the end of the callback like so: animator.requestAnimationFrame = function(callback) { requestAnimationFrame(function(t) { callback(t); redraw
(); }); }; The game's redraw function does all drawing, and the animation callbacks just update state. When you request a redraw outside of animations, the animator's activeAnimations property is queried first to avod mistakenly drawing multiple times in a single animation frame. This gives nice, synchronised animations at a very low cost. Puzzowl isn't out yet, but here's a little screencast o...
Game over - Game development
only allow three now -- left, top and right. Hitting the bottom wall will end the game. We'll edit the second if block so it's an if else block that will trigger our "game over" state upon the ball colliding with the bottom edge of the canvas. For now we'll keep it simple, showing an alert message and restarting the game by reloading the page. ...
...ng an alert message and restarting the game by reloading the page. First, replace where you initially called setInterval
() setInterval(draw, 10); with: var interval = setInterval(draw, 10); Then replace the second if statement with the following: if(y + dy < ballRadius) { dy = -dy; } else if(y + dy > canvas.height-ballRadius) { alert("GAME OVER"); document.location.reload
(); clearInterval(interval); // Needed for Chrome to end game } Letting the paddle hit the ball The last thing to do in this lesson is to create some kind of collision detection between the ball and the paddle, so it can bounce off it and get back into the play area. The easiest thing to do is to check whether the center of the ball is between the left and right edges of the paddle. Update th...
...to do is to check whether the center of the ball is between the left and right edges of the paddle. Update the last bit of code you modified again, to the following: if(y + dy < ballRadius) { dy = -dy; } else if(y + dy > canvas.height-ballRadius) { if(x > paddleX && x < paddleX + paddleWidth) { dy = -dy; } else { alert("GAME OVER"); document.location.reload
(); clearInterval(interval); } } If the ball hits the bottom edge of the Canvas we need to check whether it hits the paddle . if yes, then it bounces off just like you'd expect; if not then the game is over as before. Compare your code Here's the working code for you to compare yours against: Exercise: make the ball move faster when it hits the paddle. Next steps We're doing qu...
Collision detection - Game development
the collision detection between the ball and the bricks. Luckily enough we can use the physics engine to check collisions not only between single objects (like the ball and the paddle), but also between an object and the group. Brick/Ball collision detection The physics engine makes everything a lot easier -- we just need to add two simple pieces of code. First, add a new line inside your update
() function that checks for collision detection between ball and bricks, as shown below: function update
() { game.physics.arcade.collide(ball, paddle); game.physics.arcade.collide(ball, bricks, ballHitBrick); paddle.x = game.input.x || game.world.width*0.5; } The ball's position is calculated against the positions of all the bricks in the group. The third, optional parameter is the fu...
...all and bricks, as shown below: function update
() { game.physics.arcade.collide(ball, paddle); game.physics.arcade.collide(ball, bricks, ballHitBrick); paddle.x = game.input.x || game.world.width*0.5; } The ball's position is calculated against the positions of all the bricks in the group. The third, optional parameter is the function executed when a collision occurs -- ballHitBrick
(). Create this new function as the bottom of your code, just before the closing </script> tag, as follows: function ballHitBrick(ball, brick) { brick.kill
(); } And that's it! Reload your code and you should see the new collision detection working just as required. Thanks to Phaser there are two parameters passed to the function -- the first one is the ball, which we explicitly defined in th...
...should see the new collision detection working just as required. Thanks to Phaser there are two parameters passed to the function -- the first one is the ball, which we explicitly defined in the collide method, and the second one is the single brick from the bricks group that the ball is colliding with. Inside the function we remove the brick in question from the screen simply by running the kill
() method on it. You would expect to have to write a lot more calculations of your own to implement collision detection when using pure JavaScript. That's the beauty of using the framework -- you can leave a lot of boring code to Phaser, and focus on the most fun and interesting parts of making a game. Compare your code You can check the finished code for this lesson in the live demo below, and p...
Initialize the framework - Game development
This tutorial uses Phaser V2 -- it won't work with the current version on Phaser (V3). The V2 library is still available on the Phaser download page, below the links for the...
...This tutorial uses Phaser V2 -- it won't work with the current version on Phaser (V3). The V2 library is still available on the Phaser download page, below the links for the V3 download. Go to th...
...This tutorial uses Phaser V2 -- it won't work with the current version on Phaser (V3). The V2 library is still available on the Phaser download page, below the links for the V3 download. Go to the Phaser download page. ...
Load the assets and print them on screen - Game development
on03.html. Our game will feature a ball rolling around the screen, bouncing off a paddle, and destroying bricks to earn points -- familiar, huh? In this article we'll look at how to add sprites into our gameworld. Having a ball Let's start by creating a JavaScript variable to represent our ball. Add the following line between the game initialization code (our var game... block) and the preload
() function: var ball; Note: For the sake of this tutorial, we will use global variables. The purpose of the tutorial is to teach Phaser-specific approaches to game development rather than dwelling on subjective best approaches. Loading the ball sprite Loading images and printing them on our canvas is a lot easier using Phaser than using pure JavaScript. To load the asset, we will use the gam...
...tutorial, we will use global variables. The purpose of the tutorial is to teach Phaser-specific approaches to game development rather than dwelling on subjective best approaches. Loading the ball sprite Loading images and printing them on our canvas is a lot easier using Phaser than using pure JavaScript. To load the asset, we will use the game object created by Phaser, executing its load.image
() method. Add the following new line just inside the preload
() function, at the bottom: function preload
() { // ... game.load.image('ball', 'img/ball.png'); } The first parameter we want to give the asset is the name that will be used across our game code -- for example, in our ball variable name -- so we need to make sure it is the same. The second parameter is the relative path to the ...
...all. (Note that the file name does not also have to be the same, but we'd recommend it, as it makes everything easier to follow.) Of course, to load the image, it must be available in our code directory. Grab the ball image from Github, and save it inside an /img directory in the same place as your index.html file. Now, to show it on the screen we will use another Phaser method called add.sprite
(); add the following new code line inside the create
() function as shown: function create
() { ball = game.add.sprite(50, 50, 'ball'); } This will add the ball to the game and render it on the screen. The first two parameters are the x and y coordinates of the canvas where you want it added, and the third one is the name of the asset we defined earlier. That's it -- if you load your index.ht...
Plug-in Development Overview - Gecko Plugin API Reference
to the plug-in instance in a new stream. The NPN_PostURLNotify function operates like NPN_PostURL, except that it notifies the plug-in of the result when the operation completes. For information about using these methods, see URLs. Starting in Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7), you can get the origin of the document in a secure, convenient way by calling NPN_GetValue
() to retrieve the value of the variable NPNVdocumentOrigin. The returned value is the Unicode serialization of the document's origin converted to NFKC-encoded (that is, normalized) UTF-8. Your plug-in must free the returned string's memory by calling NPN_MemFree
() when you're done with it. Getting Version and UI Information The Netscape group of Plug-in API methods provides some basic services to...
...tus line. For information about using this method, see Version, UI, and Status Information. Making Plug-ins Scriptable Scriptable plug-ins are plug-ins that have been extended to provide methods that can be called from JavaScript and the DOM when accessed through the object or embed element. ...
...See the Wikipedia article for historical information. ...
Abstraction - MDN Web Docs Glossary: Definitions of Web-related terms
code. Avoids code duplication and increases reusability. Can change internal implementation of class independently without affecting the user. Helps to increase security of an application or program as only important details are provided to the user. ...
... without affecting the user. Helps to increase security of an application or program as only important details are provided to the user. ...
...lps to increase security of an application or program as only important details are provided to the user. ...
Constructor - MDN Web Docs Glossary: Definitions of Web-related terms
a particular class object that is instantiated. The constructor initializes this object and can provide access to its private information. The concept of a constructor can be applied to most object-oriented programming languages. Essentially, a constructor in JavaScript is usually declared at the instance of a class. ...
...s usually declared at the instance of a class. Syntax // This is a generic default constructor class Default function Default
() { } // This is an overloaded constructor class Overloaded // with parameter arguments function Overloaded(arg1, arg2, ...,argN){ } To call the constructor of the class in JavaScript, use a new operator to assign a new object reference to a variable. ...
...{ } // This is an overloaded constructor class Overloaded // with parameter arguments function Overloaded(arg1, arg2, ...,argN){ } To call the constructor of the class in JavaScript, use a new operator to assign a new object reference to a variable. ...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
26 Bandwidth Glossary, Infrastructure Bandwidth is the measure of how much information can pass through a data connection in a given amount of time. It is usually measured in multiples of bits-per-second (bps), for example megabits-per-second (Mbps) or gigabits-per-second (Gbps). 27 Base64 Advanced, Base64, JavaScript, Typed Arrays, URI, URL, Unicode Problem, atob
(), btoa
() Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding. 28 Baseline CSS, Glossary, SVG, alignment, typography The baseline is a term used in European and West Asian typography meani...
... 187 Grid container CSS, Glossary, grid Using the value grid or inline-grid on an element turns it into a grid container using CSS Grid Layout, and any direct children of this element become grid items. 188 Guard API, CodingScripting, Glossary, guard Guard is a feature of Headers objects (as defined in the Fetch spec, which affects whether methods such as set
() and append
() can change the header's contents. For example, immutable guard means that headers can't be changed. For more information, read Fetch basic concepts: guard. 189 Gutters CSS Grids Gutters or alleys are spacing between content tracks. These can be created in CSS Grid Layout using the grid-column-gap, grid-row-gap, or grid-gap properties. 190 Gzip compress...
...rticipating nodes (peers) have equal privileges and share the workload. P2P differs from a client-server network architecture, where multiple client nodes connect to centralized servers for services. P2P is commonly found in Blockchain Applications. 307 PAC CodingScripting, Glossary A Proxy Auto-Configuration file (PAC file) is a file which contains a function, FindProxyForURL
(), which is used by the browser to determine whether requests (including HTTP, HTTPS, and FTP) should go directly to the destination or if they need to be forwarded through a web proxy server. 308 PDF Composing, Glossary, PDF, Portable Document Format PDF (Portable Document Format) is a file format used to share documentation without depending on any particular software impleme...
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
value, and it will work. Symbols are special. They don't auto-convert. For example: let Sym = Symbol("Sym") alert(Sym) // TypeError: Cannot convert a Symbol value to a string That's a "language guard" against messing up, because strings and symbols are fundamentally different, and should not occasionally convert one into another. If you really want to show a symbol, we need to call .toString
() on it. let Sym = Symbol("Sym") alert(Sym.toString
()) // Symbol(Sym), now it works Or you can use the symbol.description property to get its description: let _Sym = Symbol("Sym"); alert(_Sym.description); // Sym Well-known symbols The Symbol class has constants for so-called well-known symbols. These symbols let you configure how JS treats an object, by using them as property keys. Example...
...ols are: Symbol.iterator for array-like objects, or Symbol.search for string objects. They are listed in the specification in the Well-known symbols table: Symbol.hasInstance Symbol.isConcatSpreadable Symbol.iterator Symbol.toPrimitive ...and so on. Global symbol registry There is a global symbol registry holding all available symbols. The methods that access the registry are Symbol.for
() and Symbol.keyFor
(); these mediate between the global symbol table (or "registry") and the run-time environment. The global symbol registry is mostly built by JavaScript's compiler infrastructure, and the global symbol registry's content is not available to JavaScript's run-time infrastructure, except through these reflective methods. The method Symbol.for(tokenString) returns a symbol value fro...
...stry, and Symbol.keyFor(symbolValue) returns a token string from the registry; each is the other's inverse, so the following is true: Symbol.keyFor(Symbol.for("tokenString")) === "tokenString" // true Learn more General knowledge Symbol (programming) on Wikipedia JavaScript data types and data structures Symbols in ECMAScript 6 Symbol in the MDN JS reference Object.getOwnPropertySymbols
() ...
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
var j; var xincludeParent = xinclude.parentNode; try { netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect UniversalBrowserRead'); // Necessary with file:///-located files trying to reach external sites if (href !== null) { var response, responseType; var request = new XMLHttpRequest
(); request.open('GET', href, false); request.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT'); request.setRequestHeader('Cache-Control', 'no-cache'); if (accept) { request.setRequestHeader('Accept', accept); } if (acceptLanguage) { ...
... return false; break; } request.send(null); if((request.status === 200 || request.status === 0) && request[responseType] !== null) { response = request[responseType]; if (responseType === 'responseXML') { // apply xpointer (only xpath1
() subset is supported) var responseNodes; if (xpointer) { var xpathResult = response.evaluate( xpointer, response, nul...
... } else { encodingType = 'utf-8'; } // Need to make a whole new request apparently since cannot convert the encoding after receiving it (to know what the encoding was) var request2 = new XMLHttpRequest
(); request2.overrideMimeType('text/plain; charset='+encodingType); request2.open('GET', href, false); request2.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT'); request2.setRequestHeader('Cache-Control', 'no-cache'); ...
Mobile accessibility - Learn web development
running live) to see what we mean. Alternatively, mouse-specific events such as mousedown and mouseup create problems -- their event handlers cannot be invoked using non-mouse controls. If you try to control our simple-box-drag.html (see example live) example with a keyboard or touch, you'll see the problem. ...
...s mousedown and mouseup create problems -- their event handlers cannot be invoked using non-mouse controls. If you try to control our simple-box-drag.html (see example live) example with a keyboard or touch, you'll see the problem. ...
... Note: You can also see fully functional examples showing how to implement different control mechanisms at Implementing game control mechanisms. ...
Advanced styling effects - Learn web development
ry commonly used, but worth mentioning. Filters While you can't change the composure of an image using CSS, there are some creative things you can do. One very nice property, which can help you bring interest to your designs, is the filter property. This property enables Photoshop-like filters right from CSS. In the example below we have used two different values for filter. The first is blur
() -- this function can be passed a value to indicate how much the image should be blurred. The second is grayscale
(); by using a percentage we are setting how much color we want to be removed. Play with the percentage and pixel parameters in the live example to see how the images change. You could also swap the values for some others. Try contrast(200%), invert(100%) or hue-rotate(20deg) on the...
...o see how the images change. You could also swap the values for some others. Try contrast(200%), invert(100%) or hue-rotate(20deg) on the live example below. Take a look at the MDN page for filter for many other options you could try. You can apply filters to any element and not just images. Some of the filter options available do very similar things to other CSS features, for example drop-shadow
() works in a very similar way and gives a similar effect to box-shadow or text-shadow. The really nice thing about filters however, is that they work on the exact shapes of the content inside the box, not just the box itself as one big chunk, so it is worth knowing the difference. In this next example we are applying our filter to a box, and comparing it to a box shadow. As you can see, the drop-...
...shape in this example is not reacting to the content of the image file. Instead, the circle function is taking its centre point from the centre of the image file, as if we had put a compass in the middle of the file and drawn a circle that fits inside the file. It is that circle that the text flows around. Note: In Firefox you can use the DevTools Shapes Inspector to inspect Shapes. The circle
() function is just one of a few basic shapes that are defined, however there are a number of different ways to create shapes. For more information and example code for CSS Shapes see the Guides to CSS Shapes on MDN. -webkit-background-clip: text Another feature we thought we'd mention briefly is the text value for background-clip. When used along with the proprietary -webkit-text-fill-color: tran...
Legacy layout methods - Learn web development
.col.span11 { width: 89.5833333%; } .col.span12 { width: 97.91666663%; } Now save your code, load it in a browser, and try changing the viewport width -- you should see the column widths adjust nicely to suit. Note: If you are having trouble getting the above example to work, try comparing it against our finished version on GitHub (see it running live also). Easier calculations using the calc
() function You could use the calc
() function to do the math right inside your CSS -- this allows you to insert simple mathematical equations into your CSS values, to calculate what a value should be. It is especially useful when there is complex math to be done, and you can even compute a calculation that uses different units, for example "I want this element's height to always be 100% of its pare...
...t this element's height to always be 100% of its parent's height, minus 50px". See this example from a MediaRecorder API tutorial. Anyway, back to our grids! Any column that spans more than one column of our grid has a total width of 6.25% multiplied by the number of columns spanned plus 2.08333333% multiplied by the number of gutters (which will always be the number of columns minus 1). ...
... calc((6.25%*9) + (2.08333333%*8)); } .col.span10 { width: calc((6.25%*10) + (2.08333333%*9)); } .col.span11 { width: calc((6.25%*11) + (2.08333333%*10)); } .col.span12 { width: calc((6.25%*12) + (2.08333333%*11)); } Note: You can see our finished version in fluid-grid-calc.html (also see it live). Note: If you can't get this to work, it might be because your browser does not support the calc
() function, although it is fairly well supported across browsers -- as far back as IE9. Semantic versus "unsemantic" grid systems Adding classes to your markup to define layout means that your content and markup becomes tied to your visual presentation. You will sometimes hear this use of CSS classes described as being "unsemantic" -- describing how the content looks -- rather than a semantic us...
Practical positioning examples - Learn web development
lowing block of code, exactly as written in between your opening and closing <script> tags (you'll find these below the HTML content): var tabs = document.querySelectorAll('.info-box li a'); var panels = document.querySelectorAll('.info-box article'); for(i = 0; i < tabs.length; i++) { var tab = tabs[i]; setTabHandler(tab, i); } function setTabHandler(tab, tabPos) { tab.onclick = function
() { for(i = 0; i < tabs.length; i++) { tabs[i].className = ''; } tab.className = 'active'; for(i = 0; i < panels.length; i++) { panels[i].className = ''; } panels[tabPos].className = 'active-panel'; } } This code does the following: First we save a reference to all the tabs and all the panels in two variables called tabs and panels, so we can easily do t...
...(i = 0; i < panels.length; i++) { panels[i].className = ''; } panels[tabPos].className = 'active-panel'; } } This code does the following: First we save a reference to all the tabs and all the panels in two variables called tabs and panels, so we can easily do things to them later on. ...
... things to them later on. Then we use a for loop to cycle through all the tabs and run a function called setTabHandler
() on each one, which sets up the functionality that should occur when each one is clicked on. When run, the function is passed a reference to the particular tab it is being run for, and an index number i that indentifies the tab's position in the tabs array. In the setTabHandler
() function, the tab has an onclick event handler set on it, so that when the tab is clicked, the following occurs: A for loop is used to cycle through all the tabs and remove any classes that are present on them. A class of active is set on the tab that was clicked on -- remember from earlier that this class has an associated rule in the CSS that sets the same color and background-color on...
Fundamental text and font styling - Learn web development
You've reached the end o...
... You've reached the end of this article, and already did some skill testing in our Active Learning section, but can you remember the most important infor...
...utput = document.querySelector(".output"); const styleElem = document.createElement('style'); const headElem = document.querySelector('head'); headElem.appendChild(styleElem); function drawOutput
() { output.innerHTML = htmlInput.value; styleElem.textContent = cssInput.value; } reset.addEventListener("click", function
() { htmlInput.value = htmlCode; cssInput.value = cssCode; drawOutput
(); }); htmlInput.addEventListener("input", drawOutput); cssInput.addEventListener("input", drawOutput); window.addEventListener("load", drawOutput); Test your skills! You've reached the end of this article, and already did some skill testing in our Active Learning section, but can you remember the most important information going forward? You can find an assessment to verify that you've reta...
Styling links - Learn web development
s. Visited: A link when it has already been visited (exists in the browser's history), styled using the :visited pseudo class. Hover: A link when it is being hovered over by a user's mouse pointer, styled using the :hover pseudo class. Focus: A link when it has been focused (for example moved to by a keyboard user using the Tab key or similar, or programmatically focused using HTMLElement.focus
()) -- this is styled using the :focus pseudo class. Active: A link when it is being activated (e.g. clicked on), styled using the :active pseudo class. Default styles The following example illustrates what a link will behave like by default (the CSS is simply enlarging and centering the text to make it stand out more.) <p><a href="#">A simple link</a></p> p { font-size: 2rem; text-align:...
...t = document.querySelector(".css-input"); var reset = document.getElementById("reset"); var htmlCode = htmlInput.value; var cssCode = cssInput.value; var output = document.querySelector(".output"); var solution = document.getElementById("solution"); var styleElem = document.createElement('style'); var headElem = document.querySelector('head'); headElem.appendChild(styleElem); function drawOutput
() { output.innerHTML = htmlInput.value; styleElem.textContent = cssInput.value; } reset.addEventListener("click", function
() { htmlInput.value = htmlCode; cssInput.value = cssCode; drawOutput
(); }); solution.addEventListener("click", function
() { htmlInput.value = htmlCode; cssInput.value = 'p {\n font-size: 1.2rem;\n font-family: sans-serif;\n line-height: 1.4;\n}\n\na {\n outl...
...Let's look at a really simple example that adds an icon to external links (links that lead to ...
Example 4 - Learn web development
= select.querySelectorAll('.option'); nativeWidget.selectedIndex = index; value.innerHTML = optionList[index].innerHTML; highlightOption(select, optionList[index]); }; function getIndex(select) { var nativeWidget = select.previousElementSibling; return nativeWidget.selectedIndex; }; // ------------- // // Event binding // // ------------- // window.addEventListener("load", function
() { var form = document.querySelector('form'); form.classList.remove("no-widget"); form.classList.add("widget"); }); window.addEventListener('load', function
() { var selectList = document.querySelectorAll('.select'); selectList.forEach(function (select) { var optionList = select.querySelectorAll('.option'); optionList.forEach(function (option) { option.addEventListener(...
...nt.querySelector('form'); form.classList.remove("no-widget"); form.classList.add("widget"); }); window.addEventListener('load', function
() { var selectList = document.querySelectorAll('.select'); selectList.forEach(function (select) { var optionList = select.querySelectorAll('.option'); optionList.forEach(function (option) { option.addEventListener('mouseover', function
() { highlightOption(select, option); }); }); select.addEventListener('click', function (event) { toggleOptList(select); }); select.addEventListener('focus', function (event) { activeSelect(select, selectList); }); select.addEventListener('blur', function (event) { deactivateSelect(select); }); }); }); window.addEventListener('load', ...
... highlightOption(select, option); }); }); select.addEventListener('click', function (event) { toggleOptList(select); }); select.addEventListener('focus', function (event) { activeSelect(select, selectList); }); select.addEventListener('blur', function (event) { deactivateSelect(select); }); }); }); window.addEventListener('load', function
() { var selectList = document.querySelectorAll('.select'); selectList.forEach(function (select) { var optionList = select.querySelectorAll('.option'), selectedIndex = getIndex(select); select.tabIndex = 0; select.previousElementSibling.tabIndex = -1; updateValue(select, selectedIndex); optionList.forEach(function (option, index) { option.addEventListener('c...
Solve common problems in your JavaScript code - Learn web development
problems you may encounter when writing JavaScript. Common beginner's mistakes Correct spelling and casing If your code doesn't work and/or the browser complains that something is undefined, check that you've spelt all your variable names, function names, etc. correctly. Some common built-in browser functions that cause problems are: Correct Wrong getElementsByTagName
() getElementbyTagName
() getElementsByName
() getElementByName
() getElementsByClassName
() getElementByClassName
() getElementById
() getElementsById
() Semi-colon position You need to make sure you don't place any semi-colons incorrectly. For example: Correct Wrong elem.style.color = 'red'; elem.style.color = 'red;' Functions...
...) Semi-colon position You need to make sure you don't place any semi-colons incorrectly. For example: Correct Wrong elem.style.color = 'red'; elem.style.color = 'red;' Functions There are a number of things that can go wrong with functions. One of the most common errors is to declare the function, but not call it anywhere. For example: function myFunction
() { alert('This is my function.'); }; This code won't do anything unless you call it with the following statement: myFunction
(); Function scope Remember that functions have their own scope -- you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e. not inside any functions), or return the value from the function. Runni...
...nd how do you create them? What different ways are there to create objects in JavaScript? JSON How do you structure JSON data, and read it from JavaScript? How can you load a JSON file into a page? How do you convert a JSON object to a text string, and back again? Events What are event handlers and how do you use them? What are inline event handlers? What does the addEventListener
() function do, and how do you use it? Which mechanism should I use to add event code to my web pages? What are event objects, and how do you use them? How do you prevent default event behaviour? How do events fire on nested elements? (event propagation, also related -- event bubbling and capturing) What is event delegation, and how does it work? Object-oriented JavaScript What are object ...
Test your skills: JSON - Learn web development
ut the answer (or into the browser's JavaScript console, in the case of the downloadable version). JSON 1 The one and only task in this article concerns accessing JSON data and using it in your page. JSON data about some mother cats and their kittens is available in sample.json. The JSON is loaded into the page as a text string and made available in the catString parameter of the displayCatInfo
() function, called when the provided promise chain (which starts by fetching the JSON data) is fulfilled. Your task is to fill in the missing parts of the displayCatInfo
() function to store: The names of the three mother cats, separated by commas, in the motherInfo variable. The total number of kittens, and how many are male and female, in the kittenInfo variable. The values of these variable...
...You'll need to parse it into JSON before you can get any data out of it. You'll probably want to use an outer loop to loop through the cats and add their names to the motherInfo variable string, and an inner loop to loop through all the kittens, add up the total of all/male/female kittens, and add those details to the kittenInfo variable string. ...
...through all the kittens, add up the total of all/male/female kittens, and add those details to the kittenInfo variable string. The last mother cat name should have an "and" before it, and a full stop after it. How do you make sure this can work, no matter how many cats are in the JSON? Why are the para1.textContent = motherInfo; and para2.textContent = kittenInfo; lines inside the displayCatInfo
() function, and not at the end of the script? This has something to do with async code. Try updating the live code below to recreate the finished example: Warning: To answer this question, you'll need to write your code into the live code window above. The example won't work locally, or in an environment like CodePen or JSFiddle, because of something called cross-origin security. This basical...
Client-Server Overview - Learn web development
It also has benefits in terms of maintenance, because you can change the URL used to deliver a particular feature in one place, without having to change the handler function. For example, consider the following Django (Python) code that maps two URL patterns to two view functions. ...
...feature in one place, without having to change the handler function. For example, consider the following Django (Python) code that maps two URL patterns to two view functions. The first pattern ensures that an HTTP request with a resource URL of /best will be passed to a function named index
() in the views module. A request that has the pattern "/best/junior", will instead be passed to the junior
() view function. # file: best/urls.py # from django.conf.urls import url from . import views urlpatterns = [ # example: /best/ url(r'^$', views.index), # example: /best/junior/ url(r'^junior/$', views.junior), ] Note: The first parameters in the url
() functions may look a bit odd (e.g. r'^junior/$') because they use a pattern matching technique called "regular expressions" (Re...
...e many other types of matches and we can daisy chain them. We can also control the order and the number of results returned. #best/views.py from django.shortcuts import render from .models import Team def junior(request): list_teams = Team.objects.filter(team_type__exact="junior") context = {'list': list_teams} return render(request, 'best/index.html', context) After the junior
() function gets the list of junior teams, it calls the render
() function, passing the original HttpRequest, an HTML template, and a "context" object defining the information to be included in the template. The render
() function is a convenience function that generates HTML using a context and an HTML template, and returns it in an HttpResponse object. Obviously web frameworks can help you with a ...
Getting started with Svelte - Learn web development
the app running at localhost:5000 will be automatically updated. A first look at Svelte reactivity In the context of a UI framework, reactivity means that the framework can automatically update the DOM when the state of any component is changed. In Svelte, reactivity is triggered simply by assigning a new value to any top level variable in a component. ...
...work can automatically update the DOM when the state of any component is changed. In Svelte, reactivity is triggered simply by assigning a new value to any top level variable in a component. For example, we could include a toggleName
() function in our App component, and a button to run it. ...
... As you can see, the <h1> label is automatically updated. Behind the scenes, Svelte created the JavaScript code to update the DOM whenever the value of the name variable changes, without using any virtual DOM or other complex reconciliation mechanism. Note the use of : in on:click. ...
Implementing feature detection - Learn web development
techniques Feature detection type Explanation Example If member in object Check whether a certain method or property (typically an entry point into using the API or other feature you are detecting for) exists in its parent Object. if("geolocation" in navigator) { ... } Property on element Create an element in memory using Document.createElement
() and then check if a property exists on it. The example shown is a way of detecting HTML5 Canvas support. function supports_canvas
() { return !!document.createElement('canvas').getContext; } if(supports_canvas
()) { ... } Method on element return value Create an element in memory using Document.createElement
() and then check if a method exists on it. If it does, chec...
... See Dive into HTML5 <input> types detection test. Note: The double NOT in the above example (!!) is a way to force a return value to become a "proper" boolean value, rather than a Truthy/Falsy value that may skew the results. ...
...hot demo makes use of it to selectively apply the Brick JavaScript library and use it to handle the UI layout, but only for the small screen layout (480px wide or less). We first use the media attribute to only apply the Brick CSS to the page if the page width is 480px or less: <link href="dist/brick.css" type="text/css" rel="stylesheet" media="all and (max-width: 480px)"> We then use matchMedia
() in the JavaScript several times, to only run Brick navigation functions if we are on the small screen layout (in wider screen layouts, everything can be seen at once, so we don't need to navigate between different views). if (window.matchMedia("(max-width: 480px)").matches) { deck.shuffleTo(1); } Using Modernizr to implement feature detection It is possible to implement your own feature dete...
Introducing a complete toolchain - Learn web development
However, in the project's source files we are using React JSX syntax (for your real projects you might use React or Vue or any other framework, or no framework at all!). Putting JSX syntax in the middle of our JavaScript is going to cause eslint to complain pretty quickly with the current config...
... However, in the project's source files we are using React JSX syntax (for your real projects you might use React or Vue or any other framework, or no framework at all!). Putting JSX syntax in the middle of our JavaScript is going to cause eslint to complain pretty quickly with the current configuration, ...
...er": true }, "extends": "eslint:recommended", "parserOptions": { "ecmaVersion": 6, "sourceType": "module" }, "rules": { "no-console": 0 } } The above eslint configuration says that we want to use the "recommended" eslint settings, that we're going to allow usage of ES6 features (such as map
() or Set
()), that we can use module import statements, and that using console.log
() is allowed. However, in the project's source files we are using React JSX syntax (for your real projects you might use React or Vue or any other framework, or no framework at all!). Putting JSX syntax in the middle of our JavaScript is going to cause eslint to complain pretty quickly with the current configuration, so we'll need to add a little more configuration to the eslint settings t...
Debugging JavaScript
mon JavaScript idioms that are not errors). Console.log in Browser Console You can dump variables in the Browser Console from addon code, by adding this line to import the console utility: const { console } = Components.utils.import("resource://gre/modules/devtools/Console.jsm", {}); This has an advantage over dump in that you can list out properties of an object logged with console.log. dump
() The dump
() function allows you to print text on the native console. Use \n to output a newline at the end. To see anything, you need to set the pref browser.dom.window.dump.enabled to true, e.g. in about:config (add new pref, it doesn't exist per default). Under Microsoft Windows you additionally need to start Firefox via the following command to have a native console : firefox.exe -console ...
...ng, you need to set the pref browser.dom.window.dump.enabled to true, e.g. in about:config (add new pref, it doesn't exist per default). Under Microsoft Windows you additionally need to start Firefox via the following command to have a native console : firefox.exe -console Using normal JavaScript object inspection, you can write a function that dumps a whole object, similar to this ddumpObject
(). Log.jsm (formerly log4moz) This is a partial implementation of the Log4* interfaces (for example, see log4j or log4net). Components.utils.import("resource://gre/modules/Log.jsm"); "debugger" keyword You can halt Venkman or Chromebug at a line using the keyword debugger. In debug builds this also dumps a stack trace to the console, even when the debugger is not running. In extensions you can...
...interfaces (for example, see log4j or log4net). Components.utils.import("resource://gre/modules/Log.jsm"); "debugger" keyword You can halt Venkman or Chromebug at a line using the keyword debugger. In debug builds this also dumps a stack trace to the console, even when the debugger is not running. ...
Debugging on Windows
} >Debug.EvaluateStatement ((nsGenericElement*)0x03f0e710)->List((FILE*)0x10311dc0, 1) <void> >Debug.EvaluateStatement {,,msvcr80d}fclose((FILE*)0x10311dc0) 0x000000...
...} >Debug.EvaluateStatement ((nsGenericElement*)0x03f0e710)->List((FILE*)0x10311dc0, 1) <void> >Debug.EvaluateStatement {,,msvcr80d}fclose((FILE*)0x10311dc0) 0x00000000 Note that you may not see the debugging output until you flu...
...You can also specify the profile to use with the -P profile_name command-line argument. Debugging JavaScript Use Venkman, the JavaScript Debugger for Mozilla. You can use helper functions from nsXPConnect.cpp to inspect and modify the state of JavaScript code from the MSVS debugger. For example, to print curent JavaScript stack to stdout, evaluate this in QuickWatch window: {,,xul}DumpJSStack
() Note: Visual C++ will show you something in the quick watch window, but not the stack, you have to look in the OS console for the output. Also this magical command only works when the VC++ stack is in certain states. It works when you have js_Interpret
() in the newest stackframe Debugging minidumps See debugging a minidump. Debugging tinderbox builds See Running Windows Debug Builds Prob...
Gecko Logging
Debug 4 A debug message, useful for debugging but too verbose to be turned on normally. Verbose 5 A message that will be printed a lot, useful for debugging program flow and will probably impact performance. ...
... Verbose 5 A message that will be printed a lot, useful for debugging program flow and will probably impact performance. ...
...It can also be adjusted by setting prefs. ...
Cross Process Object Wrappers
ilable to chrome through a wrapper called a Cross Process Object Wrapper, also known as a CPOW. However, although CPOWs are convenient, they have serious limitations and can cause responsiveness problems, so should only be used when necessary and only as a migration aid. Passing CPOWs from frame scripts Frame scripts can send messages to chrome using one of two global functions: sendAsyncMessage
() or sendSyncMessage
(). The optional third parameter to each of these functions is an object whose properties are objects to wrap. For example, this frame script sends a DOM node to chrome when the user clicks it, as the clicked property of the third argument: // frame script addEventListener("click", function (event) { sendAsyncMessage("my-e10s-extension-message", {}, { clicked : event.target }...
...d the frame script, then listen for the message. When we get the message, extract the CPOW and add a function as a listener to the button's "click" event. */ browserMM.loadFrameScript("chrome://my-addon/content/frame-script.js", false); browserMM.addMessageListener("my-addon-message", function(message) { let wrapper = message.objects.element; wrapper.addEventListener("click", function
() { console.log("they clicked"); }); }); Mapping content documents to XUL browsers A common pattern is to get the XUL <browser> that corresponds to a content document. To enable this, gBrowser.getBrowserForDocument and gBrowser.getBrowserForContentWindow can be passed a CPOW for the content document and content window, respectively, and return the XUL <browser> that these documents ...
...eturn the XUL <browser> that these documents / windows belong to. Both return null if no such browser can be found. Limitations of CPOWs Although CPOWs can be convenient they have several major limitations, which are listed below. CPOWs and platform APIs You can't pass CPOWs into platform APIs that expect to receive DOM objects. For example, you can't pass a CPOW into nsIFocusManager.setFocus
(). Also, from Firefox 47 onwards, browser code can no longer perform unsafe CPOW operations. This means that as an add-on developer, you should not pass CPOWs into browser APIs. Chrome responsiveness The lack of a synchronous API on the chrome side is intentional: because the chrome process runs the Firefox UI, any responsiveness problems affect the whole browser. By making the chrome process bl...
Tracking Protection
s enabled. For example, if your site includes a callback that runs when content from a tracking site is loaded, then the callback will not execute. ...
...then the callback will not execute. ...
... 'hitCallback': function
() { document.location = url; } }); } </script> Instead, you should account for the case when Google Analytics is missing by checking to see if the ga object has initialized: <a href="http://www.example.com" onclick="trackLink('http://www.example.com', event);"> Visit example.com </a> <script> function trackLink(url,event) { event.preventDefault
(); if (window.ga && ga.loaded) { ga('send', 'event', 'outbound', 'click', url, { 'transport': 'beacon', 'hitCallback': function
() { document.location = url; } }); } else { document.location = url; } } </script> More information about this technique is available at Google Analytics, Privacy, and Event Tracking. Note: Depending on a third part...
mozbrowsershowmodalprompt
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The mozbrowsershowmodalprompt event is fired when the content of a browser <iframe> calls the window.alert
(), window.confirm
(), or window.prompt
() methods. General info Specification Non standard Interface CustomEvent Bubbles Yes Cancelable Yes Target <iframe> Default Action None Properties Property Type Description target Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only ...
...lable or not. details Read only Object A custom object. details The details property is an anonymous JavaScript object with the following properties: promptType A DOMString defining the type of the prompt. It can be alert, confirm, or prompt. title A DOMString representing the title of the prompt. message A DOMString representing the value passed to the window.alert
(), window.confirm
(), or window.prompt
() methods within the browser <iframe>'s content. returnValue A DOMString representing the return value for the window.prompt
() methods. This should be set by the embedder. unblock
() A function to be called when the iframe is unblocked. Note that if the embedder calls preventDefault
() on this event, the iframe is blocked until unblock
() is called. Obsolete...
... embedder. unblock
() A function to be called when the iframe is unblocked. Note that if the embedder calls preventDefault
() on this event, the iframe is blocked until unblock
() is called. Obsolete properties of details msg_name A string representing the type of message. For that event, it's always showmodalprompt. initialValue A string representing the initial value for the window.prompt
() methods. Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowsershowmodalprompt", function( event ) { console.log("Asking for prompt:" + JSON.stringify(event.detail)); }); Related Events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchang...
MozBeforePaint
nimationStartTime. This new property indicates the time, in milliseconds since epoch, at which all animations started in the specified window during the current refresh interval should be considered to have started running. With that value in hand, you can then schedule all your subsequent animation frames. Whenever you're ready to refresh your animation, you call the window.requestAnimationFrame
() method. Once you've called this, the MozBeforePaint event will be fired one time, when it's time for animations to be updated for the window's next animation frame. The timeStamp property of this event will be set to the time when the animation frame is sampled; this is relevant when trying to synchronize mozRequestAnimationFrame animations with SMIL animations or CSS transitions. This allows m...
...iod of time. <!DOCTYPE HTML> <html> <body> <div id="d" style="width:100px; height:100px; background:lime; position:relative;"></div> <script> var d = document.getElementById("d"); var start = window.mozAnimationStartTime; function step(event) { var progress = event.timeStamp - start; d.style.left = Math.min(progress/10, 200) + "px"; if (progress < 2000) { window.mozRequestAnimationFrame
(); } else { window.removeEventListener("MozBeforePaint", step, false); } } window.addEventListener("MozBeforePaint", step, false); window.mozRequestAnimationFrame
(); </script> </body> </html> As you can see, each time the MozBeforePaint event fires, our step
() method is called. This computes the current position for the animating box and updates the box's position on screen, and, if the a...
...); } } window.addEventListener("MozBeforePaint", step, false); window.mozRequestAnimationFrame
(); </script> </body> </html> As you can see, each time the MozBeforePaint event fires, our step
() method is called. This computes the current position for the animating box and updates the box's position on screen, and, if the animation sequence is not yet complete, calls window.requestAnimationFrame
() to schedule the next animation frame to be drawn. When the animation sequence completes, removes the event listener. You may take a look at this example live if you like. ...
Add-on Manager
urns. For example: Components.utils.import("resource://gre/modules/AddonManager.jsm"); AddonManager.getAllAddons(function(aAddons) { // Here aAddons is an array of Addon objects }); // This code will execute before the code inside the callback Notifications about changes to installed add-ons are dispatched to any registered AddonListeners. They must be registered through the addAddonListener
() method. Installing new add-ons New add-ons can be installed by using the getInstallForFile
() or getInstallForURL
() methods on the AddonManager object. These will pass an AddonInstall instance to the callback, which can then be used to install the add-on: Components.utils.import("resource://gre/modules/AddonManager.jsm"); AddonManager.getInstallForURL("http://www.foo.com/test.xpi", function(aI...
...he getInstallForFile
() or getInstallForURL
() methods on the AddonManager object. These will pass an AddonInstall instance to the callback, which can then be used to install the add-on: Components.utils.import("resource://gre/modules/AddonManager.jsm"); AddonManager.getInstallForURL("http://www.foo.com/test.xpi", function(aInstall) { // aInstall is an instance of AddonInstall aInstall.install
(); }, "application/x-xpinstall"); The progress of AddonInstalls can be monitored using an InstallListener. A listener can be registered either for a specific install using the addListener
() method or for all installs using the addInstallListener
() method. Finding updates Add-ons can be checked for updates using the findUpdates
() method. It must be passed an UpdateListener to receive information...
...ateListener to receive information about compatibility information and new update information. Any available update is returned as an AddonInstall which is ready to be downloaded and installed. Detecting add-on changes Requires Gecko 7.0(Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) You can also get lists of add-ons that, at startup, were changed in various ways. The getStartupChanges
() method lets you find out which add-ons were installed, removed, updated, enabled, or disabled at application startup. For example, to take a look at the add-ons that were disabled at startup: Components.utils.import("resource://gre/modules/AddonManager.jsm"); let addonIDs = AddonManager.getStartupChanges(AddonManager.STARTUP_CHANGE_DISABLED); if (addonIDs.length > 0) { // addonIDs is now an ...
DownloadTarget
A DownloadTarget object represents the target of a download, for example a file in the global downloads directory, or a file in the system temporary directory. Method overview Promise refresh
() Properties Attribute Type Description exists Read only Boolean Indicates whether or not the target file exists. This is a dynamic property, which is updated when the download is completed or when the Download.refresh
() method is called. You can use this instead of using file system calls to check for the existence of the file in order to reduce IO overhead. path Read only string The path of the target file. partFilePath Read only string The path of the ".part" file containing the data downloaded so far, or null ...
...wnloading a web page and its required media to disk, the meaning of this property is undefined. It currently indicates the size of the main file (such as the HTML document) rather than the sum of all of the files' sizes, but you must not rely upon this behavior, as it is subject to change. This is a dynamic property, which is updated when the download finishes or whenever the Download.refresh
() method is called. You can use this value from the front-end to reduce file I/O that would be required to check the file directly. Methods refresh
() Updates the state of a finished, failed, or canceled download based on the current state as indicated by the file system. If the download is in progress or has been finalized, this method does nothing and returns a resolved Promise. Call...
...d download based on the current state as indicated by the file system. If the download is in progress or has been finalized, this method does nothing and returns a resolved Promise. Calling this method lets the Download object's properties be updated if the user moves or deletes the target file or its associated ".part" file, which contains a partially-downloaded file's contents. Promise refresh
(); Parameters None. Promise resolves to undefined when the state of the download has been updated. Promise can be rejected with Never. ...
FxAccountsOAuthClient.jsm
The FxAccountsOAuthClient.jsm JavaScript module provides a way for browser services to authenticate with the Firefox Accounts OAuth server. Components.utils.import("resource://gre/modules/FxAccountsOAuthClient.jsm"); Creating a new FxAccountsOAuthClient new FxAccountsOAuthClient(Object options); Method overview launchWebFlow
(); tearDown
(); Attributes parameters Object Returns the set of parameters that initialized the Firefox Accounts OAuth flow. onComplete Function Gets called when the Firefox Accounts OAuth flow 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 FxAc...
...al] 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 implementing the methods described in this article. Methods launchWebFlow
() Opens a new tab at the Firefox Accounts OAuth authorization URL. Registers a WebChannel listener and sets up a callback if needed. Parameters None tearDown
() Call this function to manually release all channels and callbacks that are in use by this client. Parameters None Examples Using the FxAccountsOAuthClient Chrome code let parameters = { oauth_uri: OAUTH_SERVER_ENDPOINT, c...
... FxAccountsOAuthClient Chrome code let parameters = { oauth_uri: OAUTH_SERVER_ENDPOINT, client_id: OAUTH_CLIENT_ID, content_uri: CONTENT_SERVER_URL, state: OAUTH_STATE } let client = new FxAccountsOAuthClient({ parameters: parameters }); client.onComplete = function (tokenData) { // tokenData consists of two properties: "tokenData.state" and "tokenData.code" }; client.launchWebFlow
(); ...
FxAccountsProfileClient.jsm
The FxAccountsProfileClient.jsm JavaScript module provides a way to fetch Firefox Accounts profile information. The modules uses the Firefox Profiler Server API. Components.utils.import("resource://gre/modules/FxAccountsProfileClient.jsm"); Creating a new FxAccountsProfileClient new FxAccountsProfileClient(Object options); Method overview fetchProfile
(); Attributes serverURL URL Profiler server URL. token String Bearer token. Constructor FxAccountsProfileClient
() Creates and returns a new FxAccountsProfileClient object. FxAccountsProfileClient FxAccountsProfileClient( Object options String serverURL, String token ); Parameters serverURL - Firefox Profile server url. token - Firefox Accounts OAuth Bearer token. Return value A...
... Creates and returns a new FxAccountsProfileClient object. FxAccountsProfileClient FxAccountsProfileClient( Object options String serverURL, String token ); Parameters serverURL - Firefox Profile server url. token - Firefox Accounts OAuth Bearer token. Return value A newly created FxAccountsProfileClient object implementing the methods described in this article. Methods fetchProfile
() Fetches Firefox Accounts profile information. Parameters None Return value Promise Resolves: Object - Successful response from the '/profile' endpoint. Rejects: FxAccountsProfileClientError - Profile client error. Examples Using the FxAccountsProfileClient Chrome code let client = new FxAccountsProfileClient({ serverURL: "https://profile.accounts.firefox.com/v1", token: ...
...arameters None Return value Promise Resolves: Object - Successful response from the '/profile' endpoint. Rejects: FxAccountsProfileClientError - Profile client error. Examples Using the FxAccountsProfileClient Chrome code let client = new FxAccountsProfileClient({ serverURL: "https://profile.accounts.firefox.com/v1", token: "FXA_OAUTH_BEARER_TOKEN", }); client.fetchProfile
().then(profile => console.log(profile)); Error Handling The FxAccountsProfileClient.jsm normalizes request and client errors into FxAccountsProfileClientError object. FxAccountsProfileClientError Attributes name String Name of the error FxAccountsProfileClientError code Number Status code of the request errno Number Error number error String...
Promise.jsm
ted. The method returns a new promise that, in turn, is fulfilled or rejected depending on the state of the original promise and on the behavior of the callbacks. For example, unhandled exceptions in the callbacks cause the new promise to be rejected, even if the original promise is fulfilled. See the documentation of the then method for details. Promises may also be created using the new Promise
() constructor. Method overview Deferred defer
(); Obsolete since Gecko 30 Promise resolve([optional] aValue); Promise reject([optional] aReason); Methods defer
() Creates a new pending promise and provides methods to resolve or reject it. Deferred defer
(); Obsolete since Gecko 30 Parameters None. Return value A new object, containing the new promise in the ...
... Promise resolve( aValue ); Parameters aValue Optional If this value is not a promise, including undefined, it becomes the fulfillment value of the returned promise. ...
...esolve( aValue ); Parameters aValue Optional If this value is not a promise, including undefined, it becomes the fulfillment value of the returned promise. If this value is a promise, then the returned promise will be resolved with the value, i.e. it will eventually assume the same state as the provided promise. Return value A promise that can be pending, fulfilled, or rejected. reject
() Creates a new promise rejected with the specified reason. Promise reject( aReason ); Parameters aReason Optional The rejection reason for the returned promise. Although the reason can be undefined, it is generally an Error object, like in exception handling. Note: This argument should not be a promise. Specifying a rejected promise would make the rejection reason equal to the reject...
Deferred
If the associated promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. ...
...If the associated promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. Note: This function is exactly same as Promise constructor's resolve argument, and can be called with any value of this. ...
... pending promise value as its resolution. void resolve( aValue ); Parameters aValue Optional If this value is not a promise, including undefined, it becomes the fulfillment value of the associated promise. If this value is a promise, then the associated promise will be resolved to the passed promise, and follow the state as the provided promise (including any future transitions). reject
() Rejects the associated promise with the specified reason. If the promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. Note: This function is exactly same as Promise constructor's reject argument, and can be called with any value of this. void reject( aReason ); Parameters aReason Optional The rejection reason for the associa...
gettext
a web sites and not to the development of Gecko-based extensions or applications. Plurals gettext lets you define and use singular and plural forms of a string. To take advantage of this functionality, you need to use a different keyword (i.e. different gettext function name) for string which are supposed to support plurals. For instance, in PHP the default keyword for regular messages is gettext
() and _
(). For messages with plural support, the default keyword is ngettext
(). A definition of a string with plurals takes three arguments: the singular form of the English string, the plural form of the English string, and the number basing on which the function will return the correct (singular or plural) form of the string. Consider the following code snippet: <?php $num = 1; printf(ng...
...singular or plural) form of the string. Consider the following code snippet: <?php $num = 1; printf(ngettext("%d user likes this.", "%d users like this.", $num), $num); ?> Depending on the value of the $num variable, this code will either use the singular ("user likes) or the plural ("users like") form of the string. Notice that you need to pass the $num variable twice. First in the ngettext
() call, where it will be used to determine which form of the string will be returned. In the above example, $num equals 1, so the string returned (for English) will be %d user likes this. The second time the $num variable is passed in the printf
() call, which at this point of interpretation looks something like printf("%d user likes this.", $num);. The %d in the first argument (which is the string ...
...s this.", "%d users like this.", $num, 'Another unique context string'), $num); ?> This code produces the following output: A simple string. A string with context. 1 user likes this. 4 users like this. To extract the strings from the PHP file, use xgettext. You can specify the function calls to look for with the --keyword option. For example, --keyword=n___:1,2,4c tells xgettext to look for n___
() calls, and extract the first argument as the singular string, the second argument as the plural string and the fourth argument as the context (the third argument is reserved for the number in this example). xgettext --language=PHP \ --add-comments=L10N \ --keyword=___:1 \ --keyword=___:1,2c \ --keyword=n___:1,2 \ --keyword=n___:1,2,4c \ file.p...
Investigating leaks using DMD heap scan mode
your patch creates before trying this. The particular steps given below are intended for the case where the leaked object is alive all the way through shutdown. You could modify these steps for leaks that go away in shutdown by collecting a CC and DMD log prior to shutdown. However, in that case it may be easier to use refcount logging, or rr with a conditional breakpoint set on calls to Release
() for the leaking object, to see what object actually does the release that causes the leaked object to go away. Prerequisites A debug DMD build of Firefox. This page describes how to do that. This should probably be an optimized build. Non-optimized DMD builds will generate better stack traces, but they can be so slow as to be useless. The build is going to be very slow, so you may need to di...
...log to be taken very late in XPCOM shutdown, and the location for that log to be saved. Like with the CC log, we want this log very late to avoid as many non-leaking things as possible. MOZ_DMD_LOG_PROCESS=tab: As with the CC, this means that we only want these logs in content processes, in order to make shutdown faster. The allowed values here are the same as those returned by XRE_GetProcessType
(), so adjust as needed. Finally, the --dmd option need to be passed in so that DMD will be run. --mode=scan is needed so that when we get a DMD log the entire contents of each block of memory is saved for later analysis. With that command line in hand, you can start Firefox. Be aware that this may take multiple minutes if you have optimization disabled. Once it has started, go through the steps...
...nalyze. Example analysis of block_analyzer.py results In one debugging session where I was investigating the leak from bug 1451985, I eventually reduced the list of entries until this was the most suspicious looking entry: 0x7f0892f29630 size = 392 bytes at byte offset 56 mozilla::dom::ScriptLoader::ProcessExternalScript[...] [...] I went to that line of ScriptLoader::ProcessExternalScript
(), and it contained a call to ScriptLoader::CreateLoadRequest
(). Fortunately, this method mostly just contains two calls to new, one for ScriptLoadRequest and one for ModuleLoadRequest. (This is where an unoptimized build comes in handy, as it would have pointed out the exact line. Unfortunately, in this particular case, the unoptimized build was so slow I wasn't getting any logs.) I then looked th...
JS::PerfMeasurement
n possibly be measured." PerfMeasurement::NUM_MEASURABLE_EVENTS This constant equals the total number of events defined by the API - not necessarily the total number of events that a particular OS allows you to measure. (At time of writing, Linux allows all the above events to be measured, and we don't have back ends for any other operating system. static bool PerfMeasurement::canMeasureSomething
() This class method returns true if and only if some -- not necessarily all -- events can be measured by the current build of SpiderMonkey, running on the current OS. At present, it returns true on Linux when the <linux/perf_event.h> API is available (kernel 2.6.31 or later), and false everywhere else. PerfMeasurement::PerfMeasurement(EventMask toMeasure) The constructor creates a new profiling ob...
... measured by the current build of SpiderMonkey, running on the current OS. At present, it returns true on Linux when the <linux/perf_event.h> API is available (kernel 2.6.31 or later), and false everywhere else. PerfMeasurement::PerfMeasurement(EventMask toMeasure) The constructor creates a new profiling object, which measures some subset of the requested events. PerfMeasurement::~PerfMeasurement
() Take care not to leak profiling objects, as they may be holding down expensive OS-level state. EventMask eventsMeasured Instances of PerfMeasurement expose this constant. It will not have any more bits set than were set in the mask passed to the constructor, but if the OS cannot or will not measure all of the requested events, then only those events that will actually be measured have their bits...
... Instances of PerfMeasurement expose this constant. It will not have any more bits set than were set in the mask passed to the constructor, but if the OS cannot or will not measure all of the requested events, then only those events that will actually be measured have their bits set. All the counter variables for events that are not being measured will have the fixed value (uint64)-1. void start
() Call this on a PerfMeasurement instance to start timing. void stop
() And call this to stop timing again. The counter variables do not update in real time; they only change when stop is called. Counter values are accumulated across many start/stop cycles, and you can modify their values if you want; stop simply adds counts read back from the OS to whatever is already in each counter. void reset(...
Memory reporting
orter, nsIMemoryReporter) Note that MOZ_DEFINE_MALLOC_SIZE_OF defines a function of type mozilla::MallocSizeOf that is specific to this memory reporter (and will be identified as such in DMD's output). And MOZ_COLLECT_REPORT is a macro that makes things a bit shorter. An Example Involving Inheritance Things are a little trickier when inheritance is involved. An example: class B { virtual foo
() { ... } virtual size_t SizeOfExcludingThis(nsMallocSizeOfFun aMallocSizeOf) const { return ... // measure things pointed to by B-specific fields } virtual size_t SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf) const { return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf); } // data members }; class D : public B { virtual foo
() { ... } virtual size_t S...
...you're measuring multiple entities and summing their measurements. For example: void FooBar::AddSizeOfExcludingThis(nsMallocSizeOfFun aMallocSizeOf, size_t *aFooSizeOut, size_t* aBarSizeOut) const { *aFooSizeOut += ...; *aBarSizeOut += ...; } Alternatively, you could create a struct: struct FooBarSizes { size_t mFoo; size_t mBar; FooBarSizes
() { mozilla::PodZero(this); } } void FooBar::AddSizeOfExcludingThis(nsMallocSizeOfFun aMallocSizeOf, FooBarSizes* aSizes) const { aSizes->mFoo += ...; aSizes->mBar += ...; } Note the Add prefix that makes this incrementing behaviour clear. Obviously, if you increment you have to zero the values at some point. When using a struct, its constructor is the obvi...
... might even require some way to mark objects that have been counted (and then a way to unmark them once the measurement is complete). It's easy to get confused as to whether you should use SizeOfIncludingThis or SizeOfExcludingThis. A good rule of thumb: if you're calling the method via a pointer, you usually want the former, otherwise you want the latter. For example: foo->SizeOfIncludingThis
() // yes foo.SizeOfExcludingThis
() // yes foo.SizeOfIncludingThis
() // no foo->SizeOfExcludingThis
() // no Sometimes memory reporters are stand-alone objects, like the MyStringReporter example above. But often you'll have a singleton object that needs measuring, in which case it is usually better not to have a separate reporter object, but instead for the singleton object to implement nsIMe...
L20n Javascript API
You can listen to the ready event (emitted by the Context instance when all the resources have been compiled) and use ctx.getSync and ctx.getEntitySync to get translations synchronously. Alternatively, you can register callbacks to execute when the context is ready (or when globals change and translations need to be updated) with ctx.localize. ...
...; ctx.requestLocales('fr-CA', 'fr'); If requestedLocales argument list is empty or undefined, the default locale from registerLocales will be used. ctx.requestLocales('pl'); If registerLocales hasn't been called, the special i-default locale is used, which means that the following minimal code is valid and will result in a fully operational Context instance. var ctx = L20n.getContext
(); ctx.addResource('<hello "Hello, world!">'); ctx.requestLocales
(); requestLocales can be called multiple times after the Context instance emitted the ready event, in order to change the current language fallback chain, for instance if requested by the user. ctx.supportedLocales A read-only property which holds the current fallback chain of locales which was negotiated between all the availab...
...er to change the current language fallback chain, for instance if requested by the user. ctx.supportedLocales A read-only property which holds the current fallback chain of locales which was negotiated between all the available locales, the default locale and the user's preferred locales. ctx.registerLocales('en-US', ['en-US', 'fr', 'pl']); ctx.requestLocales('fr-CA', 'fr'); ctx.ready(function
() { // ctx.supportedLocales == ['fr']; }); ctx.addResource(text: String) Add a string as the content of a resource to the Context instance. The resource is added to all registered locales. ctx.addResource('<hello "Hello, world!">'); ctx.linkResource(uri: String) Add a resource identified by a URL to the Context instance. The resource is added to all registered locales. ctx.linkResourc...
NSS Sample Code sample4
ificate *cert = NULL; SECKEYPublicKey *pubkey = NULL; SECKEYPrivateKey *pvtkey = NULL; int modulus_len, i, outlen; char *buf1 = NULL; char *buf2 = NULL; /* Initialize NSS */ PK11_SetPasswordFunc(passwdcb); rv = NSS_Init("."); if (rv != SECSuccess) { fprintf(stderr, "NSS initialization failed (err %d)\n", PR_GetError
()); goto cleanup; } cert = PK11_FindCertFromNickname("TestCA", NULL); if (cert == NULL) { fprintf(stderr, "Couldn't find cert TestCA in NSS db (err %d)\n", PR_GetError
()); goto cleanup; } pubkey = CERT_ExtractPublicKey(cert); if (pubkey == NULL) { fprintf(stderr, "Couldn't extract public key from cert TestCA (err %d)\n", PR_GetError
()); ...
...tialize buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= (i %26) + 'A'; } buf1[modulus_len-1] = '\0'; fprintf(stderr, "Buffer being encrypted = \n%s\n", buf1); /* encrypt buf1, result will be in buf2 */ rv = PK11_PubEncryptRaw(pubkey, buf2, buf1, modulus_len, NULL); if (rv != SECSuccess) { fprintf(stderr, "Encrypt with Public Key failed (err %d)\n", PR_GetError
()); goto cleanup; } pvtkey = PK11_FindKeyByAnyCert(cert, NULL); if (pvtkey == NULL) { fprintf(stderr, "Couldn't find private key for cert TestCA (err %d)\n", PR_GetError
()); goto cleanup; } /* clear buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= '\0'; } /* decrypt buf2, result will be in buf1 */ rv = PK11_PubDecryptRaw(pvtkey, buf1, &outlen, modu...
..., PR_GetError
()); goto cleanup; } /* clear buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= '\0'; } /* decrypt buf2, result will be in buf1 */ rv = PK11_PubDecryptRaw(pvtkey, buf1, &outlen, modulus_len, buf2, modulus_len); if (rv != SECSuccess) { fprintf(stderr, "Decrypt with Private Key failed (err %d)\n", PR_GetError
()); goto cleanup; } fprintf(stderr, "Result of decryption, outlen = %d\n", outlen); fprintf(stderr, "Result of decryption, buf = \n%s\n", buf1); exit(0); cleanup: if (cert) CERT_DestroyCertificate(cert); if (pubkey) SECKEY_DestroyPublicKey(pubkey); if (pvtkey) SECKEY_DestroyPrivateKey(pvtkey); if (buf1) free(buf1); if (buf2) free(buf2); exit(1); } cha...
PKCS #11 Module Specs
oted, then the value is terminated with and ending quote of the form ', ", ), ], }, or > matching the respective starting quote. Ending quotes can be escaped. Embedded '\' charaters are considered escape characters for the next character in the stream. Note that case must be preserved in the values. ...
... In additions applications/libraries should be able to ignore additional name value pairs which are used to specify configuration for other applications. Of course these application/libraries should be able to parse their own name/value pairs. Each of these name/value pairs are optional. ...
...re passed to the PKCS #11 module. If the application/library does not find its application/library specific data, it should use it's defaults for this pkcs #11 library. Parameter Passing If the parameter is specified, the application/library will strip the value out, processing any outter quotes and escapes appropriately, and pass the parameter to the pkcs #11 library when it calls C_Initialize
(). A new CK_C_INITIALIZE_ARGS structure is defined as typedef struct CK_C_INITIALIZE_ARGS { CK_CREATEMUTEX CreateMutex; CK_DESTROYMUTEX DestroyMutex; CK_LOCKMUTEX LockMutex; CK_UNLOCKMUTEX UnlockMutex; CK_FLAGS flags; CK_VOID_PTR LibraryParameters; CK_VOID_PTR pReserved; } CK_C_INITIALIZE_ARGS; Applications/libraries must set LibraryParameters to NULL if no parameter value is spec...
NSS PKCS11 Functions
ne of these values: If successful, SECSuccess. If unsuccessful, SECFailure. Description SECMOD_UnloadUserModule detaches a module from the nss trust domain and unloads it. The module should have previously been loaded by SECMOD_LoadUserModule. SECMOD_CloseUserDB Close an already opened user database. NOTE: the database must be in the internal token, and must be one created with SECMOD_OpenUserDB
(). Once the database is closed, the slot will remain as an empty slot until it's used again with SECMOD_OpenUserDB
(). Syntax #include <pk11pub.h> SECStatus SECMOD_CloseUserDB(PK11SlotInfo *slot) Parameters This function has the following parameter: slot A pointer to a slot info structure. This slot must a a slot created by SECMOD_OpenUserDB
() at some point in the past. Returns The function retu...
...ftoken at initialization time under the 'tokens' options. For example, if you would normally specify tokens=<0x4=[configdir='./mybackup' tokenDescription='Backup']> to softoken if you at init time, then you could specify "configdir='./mybackup' tokenDescription='Backup'" as your module spec here to open the database ./mybackup on the fly. The slot ID will be calculated for you by SECMOD_OpenUserDB
(). Typical parameters here are configdir, tokenDescription and flags. a Full list is below: configDir The location of the databases for this token. If configDir is not specified, and noCertDB and noKeyDB is not specified, the load will fail. certPrefix Cert prefix for this token. keyPrefix Prefix for the key database for this token. (if not specified, certPrefix will be used). tokenDescription The ...
... lock tables.When this flag is not specified, Softoken will allocatelarge tables to prevent lock contention. For more info on module strings see PKCS11_Module_Specs. This function will return a reference to a slot. The caller is responsible for freeing the slot reference when it is through. Freeing the slot reference will not unload the slot. That happens with the corresponding SECMOD_CloseUserDB
() function. Until the SECMOD_CloseUserDB function is called, the newly opened database will be visible to any NSS calls search for keys or certs. PK11_FindCertFromNickname Finds a certificate from its nickname. Syntax #include <pk11pub.h> #include <certt.h> CERTCertificate *PK11_FindCertFromNickname( char *nickname, void *passwordArg); Parameters This function has the following parameter...
SpiderMonkey compartments
mes that all objects referenced from outside the compartment are live, and then walks the object graph inside the compartment. Objects that are found to be disconnected from the graph are discarded. ...
...rom outside the compartment are live, and then walks the object graph inside the compartment. Objects that are found to be disconnected from the graph are discarded. ...
...ive, and then walks the object graph inside the compartment. Objects that are found to be disconnected from the graph are discarded. With this new per-compartment garbage collection we shortcut having to walk unrelated heap areas of a window or tab that triggered a garbage collection. ...
Creating JavaScript jstest reftests
cted, actual, '3==1+2'); compareSource compareSource(expected, actual, description) is used to test if the decompilation of a JavaScript object (conversion to source code) matches an expected value. Note that tests which use compareSource should be located in the decompilation sub-suite of a suite. For example, to test the decompilation of a simple function you could write: var f = (function
() { return 1; }); expect = 'function
() { return 1; }'; actual = f + ''; compareSource(expect, actual, 'decompile simple function'); Handling shell or browser specific features jstests run both in the browser and in the JavaScript shell. If your test needs to use browser-specific features, either: make the test silently pass if those features aren't present; or write a mochitest instead (pr...
...ests run both in the browser and in the JavaScript shell. If your test needs to use browser-specific features, either: make the test silently pass if those features aren't present; or write a mochitest instead (preferred); or at the top of the test, add the comment // skip-if(xulRuntime.shell), so that it only runs in the browser. If your test needs to use shell-specific features, like gc
(), either: make the test silently pass if those features aren't present; or make it a jit-test (so that it never runs in the browser); or at the top of the test, add the comment // skip-if(!xulRuntime.shell), so that it only runs in the shell. It is easy to make a test silently pass; anyone who has written JS code for the Web has written this kind of if-statement: if (typeof gc === 'functio...
...res aren't present; or make it a jit-test (so that it never runs in the browser); or at the top of the test, add the comment // skip-if(!xulRuntime.shell), so that it only runs in the shell. It is easy to make a test silently pass; anyone who has written JS code for the Web has written this kind of if-statement: if (typeof gc === 'function') { var arr = []; arr[10000] = 'item'; gc
(); assertEq(arr[10000], 'item', 'gc must not wipe out sparse array elements'); } else { print('Test skipped: no gc function'); } reportCompare(0, 0, 'ok'); Handling abnormal test terminations Some tests can terminate abnormally even though the test has technically passed. Earlier we discussed the deprecated approach of using the -n naming scheme to identify tests whose PASSED, FAILED sta...
Exact Stack Rooting
and more expensive than using an extra reserved slot, or even just putting a new property on the object. Class FooClass = { "FooPrototype", /* name */ JSCLASS_HAS_PRIVATE | JSCLASS_HAS_RESERVED_SLOTS(1), /* flags */ JS_PropertyStub, /* addProperty */ JS_PropertyStub, /* delProperty */ ... etc ... }; RootedObject obj(cx, NewObject(cx, &FooClass, NullPtr
(), NullPtr
(), &obj)); RootedValue v(cx, OBJECT_TO_VALUE(otherGCThing)); JSObject::SetReservedSlot(obj, 0, v); Storing a GCPointer on the CHeap TODO: Tracing and HeapPtr Storing a GCPointer on the CStack GCPointers stored on the CStack are special. Unlike other GCPointers, they are not traced as part of the GC. Instead, every pointer on the CStack should be considered part of the RootSet. To th...
...h constructor syntax. Sorry. Note 2: In C++, destructors are required to run in declaration order, 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, ...
...ire class of bugs where return values are not rooted properly before the next JS-API call. JS::NullPtr NULL (or nullptr) does not implicitly convert to a js::HandleT. For places where you want to pass a NULL value into a function taking a js::HandleT, you can construct and pass a new NullPtr instance. You are free to use these as temporaries. RootedObject obj(cx, JS_NewObject(cx, clasp, NullPtr
(), NullPtr
()); Common Pitfalls The C++ type system allows us to eliminate the possibility of most common errors; however, there are still a few things that you can get wrong that the compiler cannot help you with. There is basically never a good reason to do any of these. If you think you do need to do one of these, ask on one of SpiderMonkey's support forums: maybe we've already solved your pro...
Invariants
.) All JSShapes in dictionary-mode objects have the IN_DICTIONARY flag set. All JSShapes in property trees have it cleared. If an object is inextensible, its dslots will never again change. (We don't bother locking when accessing slots of a sealed object. The locking is going away regardless.) Compartments Suppose obj = JS_GetScopeChain(cx) is not null. Then cx->compartment == obj->compartment
(). When a new object is created, it is automatically created in cx->compartment, but its parent and prototype are often determined by examining the scope chain. The object and its proto and parent must be in the same compartment. So it is utterly crucially important that this invariant always be true if objects are being created. The public API for compartment-hopping, JSAutoEnterCompartment, and ...
... trace-jit trace stays within a single compartment (indeed, a single global object) end-to-end. Lifetime invariants In some places, pointers to JSObjects and JSStrings must refer to live heap objects, but this is not a hard fast rule, especially for strings. Some JSStrings are allocated on the stack for quick operations. Some commonly used strings are allocated statically; see JSString::isStatic
(). Most JSContext pointers must point to live contexts, but JSTitle::ownercx may point to one that has been destroyed! So code must check js_ValidContextPointer(ownercx) before dereferencing it. Shape invariants The shape guarantees hold whenever the property cache is enabled. Also, we never change the shape of the global object on trace. (Here "the global object" refers to the object at the e...
...request. With a few exceptions (known to brendan and probably jst and mrbkap), we never call a JSAPI callback with a property locked. (That would risk deadlock too.) Name instructions The first operand to a JSOP_SETNAME instruction is always produced by a preceding JSOP_BINDNAME instruction. (Taken together, ECMA 262-3 ?11.13.1 and ECMA 262-3 ?10.1.4 specify that in an assignment such as x = f
(), the name lookup for x occurs before f is called. JSOP_BINDNAME performs this lookup.) The rules below (not exactly invariants) govern the bytecode emitted for NameExpressions. Background: The fastest instructions for NameExpressions are fat opcodes that combine a load with additional operations, as in JSOP_INCLOCAL or JSOP_GETLOCALPROP. Failing that, JSOP_{GET,CALL,SET}LOCAL and JSOP_{GET,CALL...
JSAutoByteString
Context *cx, JSString *str) Call JS::LossyTwoByteCharsToNewLatin1CharsZ, or allocate string and copy the content of JSLinearString::latin1Chars, and take the ownership of the string. This may fail if str is not linear. char *encodeUtf8(JSContext *cx, JS::HandleString str) Call JS_EncodeStringToUTF8 and take ownership of the returned string, and return the string. ...
...may fail if str is not linear. char *encodeUtf8(JSContext *cx, JS::HandleString str) Call JS_EncodeStringToUTF8 and take ownership of the returned string, and return the string. void clear
() Free the owned string. You should call this before calling encode* methods or initBytes method if a string is already owned, otherwise the string will never be freed. char *ptr
() const Return a pointer to the owned string. This could be NULL if no string is owned. bool operator!
() const Return true if no string is owned. size_t length
() const Return the length of the owned string. Return 0 if no string is owned. Description JSAutoByteString takes the ownership of string and frees it in destructor. If JSAutoByteString instance is initial...
..., str); style, it calls JS_EncodeString(cx, str) to get the string to take ownership. If JSAutoByteString instance is initialized with JSAutoByteString bytes; style, it does not own any string. You can call some methods to take ownership of other string. Note that the JS_EncodeString call in constructor and some 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... */ /* when leaving this scope, the string returned by JS_EncodeString is freed. */ } Use method to encode stri...
JS_THREADSAFE
removed that feature. Each thread that uses the JavaScript engine must essentially operate in a totally separate region of memory. Requests In a JS_THREADSAFE build, the application must separate code that uses the JSAPI from code that performs blocking I/O or time-consuming calculations. A request is a region of code that uses the JSAPI. Requests must be bracketed with calls to JS_BeginRequest
() and JS_EndRequest
(). JS_BeginRequest(cx); /* ... do JSAPI stuff ... */ JS_EndRequest(cx); A request is always associated with a specific JSContext and runs from start to finish on a single thread. Most JSAPI functions require the caller to be in a request. In this reference, these JSAPI functions are marked with the words "Requires request", like this: Name Type Description ...
...from within a request. These callbacks are (unreliably!) documented with the words "Provides request", like this: Name Type Description cx JSContext * The context in which the event ocurred. Provides request. In JS_THREADSAFE builds, the JavaScript engine calls this callback only from within an active request on cx. The callback does not need to call JS_BeginRequest
()). In particular, JSNative callbacks provide a request. This means that any potentially long-running operation in a native must be bracketed with calls to JS_SuspendRequest
() and JS_ResumeRequest
(). JSBool socket_recv(JSContext *cx, unsigned int argc, jsval *vp) { ... rc = JS_SuspendRequest(cx); read_size = recv(socket, buf, size, flags); JS_ResumeRequest(cx, rc); ... }...
...s. But in multithreaded programs, if you break the rules, your program is more likely to crash. This is because in single-threaded programs, a random call into the JSAPI is actually pretty unlikely to trigger GC, especially if the calling thread has not been using up a lot of memory. In a multithreaded program, even if the calling thread has been idle, other threads may be active or may call JS_GC
(). The above rules mean that at any given moment, there can be either (a) multiple threads in active requests, or (b) one thread doing GC and all requests suspended. When one thread calls JS_GC or otherwise finds that garbage collection is necessary, it must wait for all other threads that are in requests to pause before garbage collection can occur. To keep this wait time to a minimum, applicatio...
Parser API
object, which can be used to produce AST nodes in custom data formats. The expected callback methods are described under Builder Objects. target String Default: script A type of the parsing target, can be either script or module. If parsing fails due to a syntax error, an instance of SyntaxError is thrown. The syntax error object thrown by Reflect.parse
() has the same message property as the syntax error that would be thrown by eval(src). The lineNumber and fileName properties of the syntax error object indicate the source location of the syntax error. Node objects By default, Reflect.parse
() produces Node objects, which are plain JavaScript objects (i.e., their prototype derives from the standard Object prototype). All node types implement the ...
...L { type: "XMLCdata"; contents: string; } An XML CDATA node. interface XMLComment <: XML { type: "XMLComment"; contents: string; } An XML comment. interface XMLProcessingInstruction <: XML { type: "XMLProcessingInstruction"; target: string; contents: string | null; } An XML processing instruction. Builder objects The optional builder parameter to Reflect.parse
() makes it possible to construct user-specified data from the parser, rather than the default Node objects. Builder objects may contain any of the callback methods described in this section. Each callback can produce any custom, user-defined datatype; these are referred to below as CustomExpression, CustomStatement, etc. Note: Because this library uses null for optional nodes, it is recommended t...
...ontain any of the callback methods described in this section. Each callback can produce any custom, user-defined datatype; these are referred to below as CustomExpression, CustomStatement, etc. Note: Because this library uses null for optional nodes, it is recommended that user-defined datatypes not use null as a representation of an AST node. If the loc option is enabled (see the Reflect.parse
() options above), then each callback is provided with the source location information of the parsed node as an extra parameter. All builder callbacks are optional. When a callback is missing, the default format is used, but the provided builder methods are still used recursively for sub-nodes. Programs program(body[, loc]) body: [ CustomStatement ] loc: SourceLocation Returns: CustomProgram ...
Using RAII classes in Mozilla
the class. These macros are provided in GuardObjects.h. In the common case, using these macros involves these three additions to a class: class MOZ_RAII nsAutoScriptBlocker { public: explicit nsAutoScriptBlocker(JSContext *cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) { // Note: No ',' before macro MOZ_GUARD_OBJECT_NOTIFIER_INIT; nsContentUtils::AddScriptBlocker(cx); } ~nsAutoScriptBlocker
() { nsContentUtils::RemoveScriptBlocker
(); } private: MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER }; MOZ_GUARD_OBJECT_NOTIFIER_PARAM is added to the end of the constructor's parameter list. MOZ_GUARD_OBJECT_NOTIFIER_INIT is added as a statement in the constructor. MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER is added where private members should be declared. However, there are some variations for special ...
...ts, then you have to use the MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM macro instead. (This is needed because the macro adds a parameter only when DEBUG is defined, and in this case, it can't add the leading comma.) class MOZ_RAII nsAutoScriptBlocker { public: explicit nsAutoScriptBlocker(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; nsContentUtils::AddScriptBlocker
(); } ~nsAutoScriptBlocker
() { nsContentUtils::RemoveScriptBlocker
(); } private: MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER }; Second, if the constructor is not inline, it needs the parameter added in its implementation as well. In this case, the implementation must use the MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL macro to add to the implementation: nsAutoScriptBlocker::nsAutoScriptBlocker(JSC...
...In particular, a class derived from a class using these macros does not use MOZ_GUARD_OBJECT_NOTIFIER_INIT or MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER, but instead uses either MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT or MOZ_GUARD_...
Retrieving part of the bookmarks tree
ng Places. Get the query and options objects All querying is done through the history service. First, you need to get an empty query and options objects from the history service: var historyService = Components.classes["@mozilla.org/browser/nav-history-service;1"] .getService(Components.interfaces.nsINavHistoryService); var options = historyService.getNewQueryOptions
(); var query = historyService.getNewQuery
(); Find the folder you want to get Known folder IDs are retrieved from the bookmarks service. Attributes defined in /toolkit/components/places/public/nsINavBookmarksService.idl are: bookmarksMenuFolder, tagsFolder, unfiledBookmarksFolder and toolbarFolder. You can also get folder IDs from a previous query. This example will get the ID of the bookmarks tool...
...lders and descend into the hierarchy. You will want to read the section "Using the results" in Places:Query System to understand the different result types. ...
...will want to read the section "Using the results" in Places:Query System to understand the different result types. ...
Using the Places favicon service
vicon-service;1, so to gain access to the favicon service, you should do something like this: var faviconService = Components.classes["@mozilla.org/browser/favicon-service;1"] .getService(Components.interfaces.nsIFaviconService); Caching The favicon service stores an expiration time for each favicon. This time is used by nsIFaviconService.setAndLoadFaviconForPage
() to determine if the data is fresh or needs reloading from the server. If you are manually loading favicon data, you can specify the expiration time yourself. Otherwise, nsIFaviconService.setAndLoadFaviconForPage
() will use the default expiration time. Currently, the default expiration time is set to one day in the future. This makes sure that we aren't obsessively reloading favicons into the data...
...ion is handled by browser/components/places/src/nsNavHistoryExpire.cpp as described in Places Design. The expiration time is only used to determine whether data should be reloaded from the network (or cache) or whether the version in the database is fresh enough. Getting favicon images You can use favicons in the browser UI using special annotation URIs. nsIFaviconService.getFaviconImageForPage
() returns an annotation URI for the favicon for a given page, and nsIFaviconService.getFaviconLinkForIcon
() returns an annotation URI for the given favicon. The annotation service's "moz-anno:" protocol handler notices annotations called "favicon" and forwards these to the favicon service. These annotation URIs are described in more detail in Using the Places annotation service. You should always u...
...If the page has no favicon, or we have never heard of the page, this function will return a "chrome:" URI of the default favicon. This allows efficient caching, since the default favicon will probably be cached in its decoded form by the image library. ...
Using the Places tagging service
URI, to retrieve URIs for a given tag, and to retrieve all tags for a URI. Initiating the tagging service Before using the tagging service, you need to obtain a reference to an instance of it: var taggingSvc = Components.classes["@mozilla.org/browser/tagging-service;1"] .getService(Components.interfaces.nsITaggingService); Tagging a URI The nsITaggingService.tagURI
() method tags a URL with the given set of tags. Current tags set for the URL persist, and tags which are already set for the given URL are ignored. taggingSvc.tagURI(uri("http://example.com/"), ["tag 1"]); //First argument = URI //Second Argument = Array of tag(s) where uri
() is probably similar to makeURI
(). Untagging a URI nsITaggingS...
...URL with the given set of tags. Current tags set for the URL persist, and tags which are already set for the given URL are ignored. taggingSvc.tagURI(uri("http://example.com/"), ["tag 1"]); //First argument = URI //Second Argument = Array of tag(s) where uri
() is probably similar to makeURI
(). Untagging a URI nsITaggingService.untagURI
() removes tags from a URL. ...
...ntagging a URI nsITaggingService.untagURI
() removes tags from a URL. From the given set of tags, a tag is ignored if it isn't set for the given URL. tagginSvc.untagURI(uri("http://example.com/"), ["tag 1"]); //First argument = URI //Second Argument = Array of tag(s) Finding all URLs with a given tag The nsITaggingService.getURIsForTag
() method returns an array of all URLs tagged with the given tag. var tag1uris = taggingSvc.getURIsForTag("tag 1"); //"tag 1" = given tag Getting all tags associated with a URL The nsITaggingService.getTagsForURI
() method returns an array of all tags set for the given URL. var tags = taggingSvc.getTagsForURI(uri("http://example.com/", {})); //tags = an array of tags stored in http://example.c...
extIApplication
This content covers features introduced in Thunderbird 3 The extIApplication is defined in toolkit/components/exthelper/extIApplication.idl. Implemented via XPCOM service for extIApplication: see the instructions on the FUEL (Firefox), STEEL (Thunderbird) and SMILE (SeaMonkey) pages. Method overview boolean quit
() boolean restart
() void getExtensions(extIExtensionsCallback aCallback) Attributes The following interfaces are available to all applications: Attribute Type Description id readonly attribute AString The id of the application. name readonly attribute AString The name of the application. version readonly attribute AString The version number of the application. console ...
...tion. version readonly attribute AString The version number of the application. console readonly attribute extIConsole The console object for the application. extensions readonly attribute extIExtensions The extensions object for the application. Contains a list of all installed extensions. Not available anymore on Gecko 2.0 (see [1]), use getExtensions
() instead Obsolete since Gecko 2.0 prefs readonly attribute extIPreferenceBranch The preferences object for the application. Defaults to an empty root branch. storage readonly attribute extISessionStorage The storage object for the application. events readonly attribute extIEvents The events object for the application. supports: "load", "ready", "qu...
...nly available to Firefox: Attribute Type Description bookmarks readonly attribute fuelIBookmarkRoots The root bookmarks object for the application. windows readonly attribute nsIVariant An array of browser windows within the application. activeWindow readonly attribute fuelIWindow The currently active browser window. Methods quit
() Attempts to shutdown the application. It is possible for the shutdown to be canceled. boolean quit
() Return value boolean value indicating whether the shutdown was successful. restart
() Attempts to restart the application. It is possible for the restart to be canceled. boolean restart
() Return value boolean value indicating whether the restart was successful. getExtensions(aCallback) ...
Detailed XPCOM hashtable guide
ry-class in a pre-defined format. This entry class contains the key and the data that you are hashing (just like PLDHash, above). It also declares functions that manipulate the key. In most cases, the functions of this entry class can be entirely inline. For examples of entry classes, see the declarations at xpcom/glue/nsHashKeys.h. The template parameter is the entry class. You must use the Init
() function to initalize the table properly. At this point, use the functions PutEntry/GetEntry/RemoveEntry to alter the hashtable. The Iterator class will do iteration, but beware that the iteration will occur in a seemingly-random order (no sorting). nsTHashtables can be allocated on the stack, as class members, or on the heap. Entry pointers can and do change when items are added to or remove...
...e is an XPCOM interface such as nsISupports or nsIDOMNode nsClassHashtable<KeyClass, T> - T is any C++ class. The hashtable stores a pointer to the object, and deletes that object when the entry is removed. The important files to read are xpcom/glue/nsBaseHashtable.h and xpcom/glue/nsHashKeys.h. These classes can be used on the stack, as a class member, or on the heap. Initialize using the Init
() function; you can specify whether you need thread-safety at this time. Use the Put
(), Get
(), and Remove
() methods to alter the table. Using nsTHashtable as a hash-set A hash set only tracks the existence of keys: it does not associate data with the keys. This can be done using nsTHashtable<nsSomeHashKey>. The appropriate entries are GetEntry and PutEntry. Future Plans nsISimpleEnumerator supp...
...asses as well, as needed. Hash Functions All of the above hashtables need a Hash Function. This function converts the key into a semi-unique integer. The mozilla codebase already contains hash functions for most key types, including narrow and wide strings, pointers, and most binary data: void* (or nsISupports*) cast using NS_PTR_TO_INT32 char* string nsCRT::HashCode
() PRUnichar* string nsAString HashString
() nsACString nsID& nsIDHashKey::HashKey
() Writing a good hash function is well beyond the scope of this document, and has been discussed extensively in computer-science circles for many years. There are many different types of hash functions. Mozilla has tuned a good general-purpose hash algorithm for strings ...
Receiving startup notifications
startup Sent when XPCOM finishes starting up. Most application features are not yet available at this point, but XPCOM itself is. app-startup Sent when the application has finished starting up. final-ui-startup Sent just before the first application window is displayed. Registering with the Category Manager To register with the Category Manager, simply call its nsICategoryManager.AddCategoryEntry
() method: categoryManager->AddCategoryEntry(APPSTARTUP_CATEGORY, "mycomponentname", "contract-id", PR_TRUE, PR_TRUE, getter_Copies(previous)); This causes your component to be instantiated using nsIComponentManager.createInstance
(). If you want your component to b...
...service," to the contract ID: categoryManager->AddCategoryEntry(APPSTARTUP_CATEGORY, "mycomponentname", "service,contract-id", PR_TRUE, PR_TRUE, getter_Copies(previous)); With "service," specified, the component is instantiated using nsIComponentManager.getService
(). ...
...s(previous)); With "service," specified, the component is instantiated using nsIComponentManager.getService
(). In either case, there's no need to additionally register for the startup notifications. Simply registering with the Category Manager is enough. What happens next Once you've registered with the Category Manager, at Mozilla startup time (or when the embedding application's NS_InitEmbedding
() function is called), the AppStartupNotifier component is instantiated, and its Observe
() method is called; this in turn enumerates all components in the app-startup category and sends them the appropriate notifications. ...
mozilla::services namespace
The services C++ namespace offers an easy and efficient alternative for obtaining a service as compared to the indirect XPCOM approach: GetService
(), CallGetService
(), etc methods are expensive and should be avoided when possible. To use it, you first need to include the header into your C++ file: #include "mozilla/Services.h" Then you can obtain references to services by simply accessing them from the mozilla::services namespace. ...
...GetService
(), etc methods are expensive and should be avoided when possible. To use it, you first need to include the header into your C++ file: #include "mozilla/Services.h" Then you can obtain references to services by simply accessing them from the mozilla::services namespace. ...
...leService nsIStringBundleService String Bundle Service GetToolkitChromeRegistryService nsIToolkitChromeRegistry Toolkit Chrome Registry service GetXULChromeRegistryService nsIXULChromeRegistry XUL Chrome Registry service GetXULOverlayProviderService nsIXULOverlayProvider XUL Overlay Provider service More services will be added as needed. See also Services.jsm nsIServiceManager.getService
() ...
How to build a binary XPCOM component using Visual Studio
PECIALTHING_IMPL_H__ #include "comp.h" #include "nsStringAPI.h" #define SPECIALTHING_CONTRACTID "@starkravingfinkle.org/specialthing;1" #define SPECIALTHING_CLASSNAME "SpecialThing" #define SPECIALTHING_CID { 0x245626, 0x5cc1, 0x11db, { 0x96, 0x73, 0x0, 0xe0, 0x81, 0x61, 0x16, 0x5f } } class CSpecialThing : public ISpecialThing { public: NS_DECL_ISUPPORTS NS_DECL_ISPECIALTHING CSpecialThing
(); private: ~CSpecialThing
(); protected: /* additional members */ nsString mName; }; #endif CPP file: #include "comp-impl.h" NS_IMPL_ISUPPORTS1(CSpecialThing, ISpecialThing) CSpecialThing::CSpecialThing
() { /* member initializers and constructor code */ mName.Assign(L"Default Name"); } CSpecialThing::~CSpecialThing
() { /* destructor code */ } /* attribute AString name; */ NS_IMETHODI...
...onent in a XULRunner application, you need to "install" the component, "clear" the component registry, and use the component from JavaScript. Install Component: Copy your XPT and DLL files to the {app}/components folder. You should not put your component in the xulrunner/components folder. Clear Registry: Increment the BuildID in your {app}/application.ini. ...
...nt from JavaScript. Install Component: Copy your XPT and DLL files to the {app}/components folder. You should not put your component in the xulrunner/components folder. Clear Registry: Increment the BuildID in your {app}/application.ini. ...
Components.utils.createObjectIn
Components.utils.createObjectIn creates a new JavaScript object in the scope of the specified object's compartment. 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/. Syntax var newObject = Components.utils.createObjectIn(obj, options); ...
... To create an object with a specified name, use defineAs: var foo = Com...
...bjectIn(myWindow); var propList = { name: genPropDesc("name"), date: genPropDesc("date"), id: genPropDesc("id"), func: genPropDesc(function
() { alert("Called func!"); }) }; Object.defineProperties(myObject, propList); Components.utils.makeObjectPropsNormal(myObject); This sets up the new object in the scope of the object myWindow, then adds properties by calling Object.defineProperties
(), then normalizes them by calling Components.utils.makeObjectPropsNormal
(). To create an object with a specified name, use defineAs: var foo = Components.utils.createObjectIn(myWindow, {defineAs: "foo"}); Now the target compartment's window has a new global object named foo. ...
Components.utils.evalInWindow
ned in web content. Even so, while the code is being evaluated it is in the content's context, so the caller has to be prepared for the possibility that the content could have redefined behavior (for example, a setter in the script may have been redefined to do something unexpected). This function is made available as a global in sandboxes which have the wantExportHelpers option set in the Sandbox
() constructor. Syntax var result = Components.utils.evalInWindow(script, window); Parameters script : string The script to evaluate in the other window. window : object The window in which to evaluate the script. Returns The result of evaluating the script. If this is just native (for example, a DOM node), then the function relies on XrayWrappers to wrap the returned content, oth...
...e restrictions on the sorts of things that can be returned: in particular, the result can't contain any functions, because functions can't be structured-cloned. ...
...tion1","node":{}} The add-on code can modify the variable as well, of course: // add-on-script.js Components.utils.evalInWindow("someLocalVariable.newProp = 42", contentWindow); // page-script.js console.log(window.someLocalVariable.newProp); // 42 But note that the add-on script must trust that the page script has not redefined the setter on someLocalVariable: unlike XrayWrappers, evalInWindow
() does not provide x-ray vision. If the returned object contains a function, calls to evalInWindow
() will throw an error: // page-script.js function bar
() { } var someLocalVariableContainingAFunction = {name: "selection1", foo : bar}; // add-on-script.js Components.utils.evalInWindow("someLocalVariableContainingAFunction", contentWindow); // ERROR, function can't be cloned ...
Components.utils.schedulePreciseGC
code is executing. This is useful particularly when testing for memory leaks, because normal garbage collection is conservative when JavaScript code is running to ensure that in-use memory isn't inadvertently collected. Note: Garbage collection is a very expensive operation and should only be forced when it is known to be absolutely necessary. Requires chrome privileges. ...
...n testing for memory leaks, because normal garbage collection is conservative when JavaScript code is running to ensure that in-use memory isn't inadvertently collected. Note: Garbage collection is a very expensive operation and should only be forced when it is known to be absolutely necessary. Requires chrome privileges. ...
...rtently collected. Note: Garbage collection is a very expensive operation and should only be forced when it is known to be absolutely necessary. Requires chrome privileges. Using schedulePreciseGC
() When you call Components.utils.schedulePreciseGC
(), you specify a callback that is executed in once the scheduled garbage collection has been completed: Components.utils.schedulePreciseGC( function
() { // This code is executed when the garbage collection has completed } ); Since the garbage collection doesn't occur until some time in the future (unlike, for example, Components.utils.forceGC
(), which causes garbage collection immediately but isn't able to collect all JavaScript-related memory), the callback lets you know when that's been finished. ...
Using components
Cm: manager, Ce: Exception, } = Components; Here is a full breakdown of what is contained in Components. ...
...nents. ...
...t nsXPCComponents_Constructor] QueryInterface=function QueryInterface
() { [native code] } interfacesByID=[object nsXPCComponents_InterfacesByID] classesByID=[object nsXPCComponents_ClassesByID] stack=JS frame :: Scratchpad/4 :: cDump :: line 8 manager=[xpconnect wrapped nsIComponentManager] ID=[object nsXPCComponents_ID] Exception=[object nsXPCComponents_Exception] reportError=function reportError
() { [native code] } canCreateWrapper=function canCreateWrapper
() { [native code] } canCallMethod=function canCallMethod
() { [native code] } canGetProperty=function canGetProperty
() { [native code] } canSetProperty=function canSetProperty
() { [native code] } ...
Monitoring HTTP activity
vityObserver interface, which you can implement in your code to monitor HTTP transactions in real time, receiving a callback as the transactions take place. Creating an HTTP activity observer To observe HTTP activity, you need to implement the nsIHttpActivityObserver interface within your code. This is very simple, requiring you to implement a single method, nsIHttpActivityObserver.observeActivity
(), which gets called each time an action of interest takes place on the HTTP channel. // Define a reference to the interfacevar nsIHttpActivityObserver = Components.interfaces.nsIHttpActivityObserver; var httpObserver = { observeActivity: function(aHttpChannel, aActivityType, aActivitySubtype, aTimestamp, aExtraSizeData, aExtraStringData) { if (aActivityType == nsIHttpActivityObserve...
...ase nsIHttpActivityObserver.ACTIVITY_SUBTYPE_RESPONSE_HEADER: // received response header break; case nsIHttpActivityObserver.ACTIVITY_SUBTYPE_RESPONSE_COMPLETE: // received complete HTTP response break; } } } }; Then you need to install your activity observer. ...
... .getService(Components.interfaces.nsIHttpActivityDistributor); activityDistributor.addObserver(httpObserver); Observable activities There are two classes of observable activities: those that occur at the socket level and those that occur at the HTTP transaction level. Observable socket activities When the activity type reported to your nsIHttpActivityObserver.observeActivity
() method is ACTIVITY_TYPE_SOCKET_TRANSPORT, the activity subtype, which indicates the specific type of activity that occurred, will be a socket transport status code. Observable HTTP activities When the activity type is ACTIVITY_TYPE_HTTP_TRANSACTION, the activity subtype will be one of the activity subtype constants. These include the ability to monitor outgoing HTTP request headers and bodies as ...
BeginReading
<< XPCOM API Reference Summary The BeginReading function returns a const pointer to the first element of the string's internal buffer. const char_type* BeginReading
() const; Remarks The resulting character array is not necessarily null-terminated. The length of the array is determined by the result of the Length method. ...
...ing's internal buffer. const char_type* BeginReading
() const; Remarks The resulting character array is not necessarily null-terminated. The length of the array is determined by the result of the Length method. ...
...* BeginReading
() const; Remarks The resulting character array is not necessarily null-terminated. The length of the array is determined by the result of the Length method. ...
BeginReading
<< XPCOM API Reference Summary The BeginReading function returns a const pointer to the first element of the string's internal buffer. const char_type* BeginReading
() const; Remarks The resulting character array is not necessarily null-terminated. The length of the array is determined by the result of the Length method. ...
...ernal buffer. const char_type* BeginReading
() const; Remarks The resulting character array is not necessarily null-terminated. The length of the array is determined by the result of the Length method. ...
...
() const; Remarks The resulting character array is not necessarily null-terminated. The length of the array is determined by the result of the Length method. ...
RefPtr
RefPtr (formerly known as nsRefPtr, see bug 1207245) is a general class to implement reference counting pointers for objects. It is similar to nsCOMPtr, but does not require that the type be an XPCOM interface. Like with nsCOMPtr, it is the responsibility of the object itself to implement reference counting. This is done using the functions AddRef
() and Release
(), which respectively modify a variable of type nsAutoRefCnt, which basically is a wrapper around a count of the number of references refering to the class. When should I use nsCOMPtr versus RefPtr? The rules are simple: use nsCOMPtr to hold pointers to XPCOM interfaces, and use RefPtr to hold pointers to concrete class, even if the concrete class implements one or more XPCOM interfaces. So for XPCOM interfaces: nsCOMPtr<...
...old pointers to concrete class, even if the concrete class implements one or more XPCOM interfaces. So for XPCOM interfaces: nsCOMPtr<nsISupports> a; nsCOMPtr<nsIFoo> foo; And for concrete classes: RefPtr<nsFoo> foo; // class that implements nsIFoo; RefPtr<Bar> bar; // some random class that I want ref-counted but has nothing to do with XPCOM: // Just implement AddRef
() and Release
() and it will work with RefPtr It is important that nsCOMPtr is not used to hold a pointer to a concrete class since this can cause compile time errors or runtime errors. Bug 756640 is on file to enforce this rule but hasn't yet been fixed. While RefPtr should not generally be used to hold a pointer to an XPCOM interface, this is flexible. There are no technical problems with doing...
...? memory leak? QI failure and null-deref crashes?. Note: in the above example, "nsCOMPtr<nsFoo>" might compile and work OK (it won't if your XPCOM class multiply-inherits nsISupports). But this is considered Bad Form, and may soon be made a compile-time error. Don't do it! Can I QueryInterface a RefPtr to get a nsCOMPtr from the object it points to? Sure. Instead of using "do_QueryInterface
()" (which is used for nsCOMPtrs), use "do_QueryObject
()", which works with RefPtrs: // Let's say nsFoo implements nsIFoo and nsIBar XPCOM interfaces: RefPtr<nsFoo> foo = new nsFoo
(); nsCOMPtr<nsIBar> bar(do_QueryObject(foo)); MOZ_ASSERT(bar, "Yikes someone changed the base classes of nsFoo"); Can I QueryInterface an nsCOMPtr back to a RefPtr? Yes. If the concrete class has its own XPCOM IID (no...
IAccessibleHypertext
other documents. A typical implementation is to implement this interface on the smallest text object such as a paragraph of text. Method overview [propget] HRESULT hyperlink([in] long index, [out] IAccessibleHyperlink hyperlink ); [propget] HRESULT hyperlinkIndex([in] long charIndex, [out] long hyperlinkIndex ); [propget] HRESULT nHyperlinks([out] long hyperlinkCount ); Methods hyperlink
() Returns the specified link. The returned IAccessibleHyperlink object encapsulates the hyperlink and provides several kinds of information describing it. [propget] HRESULT hyperlink( [in] long index, [out] IAccessibleHyperlink hyperlink ); Parameters index This 0 based index specifies the hyperlink to return. hyperlink If the given index is valid, that is it lies in the interval from 0 to th...
...perlink ); Parameters index This 0 based index specifies the hyperlink to return. hyperlink If the given index is valid, that is it lies in the interval from 0 to the number of links minus one, a reference to the specified hyperlink object is returned. If the index is invalid then a null pointer is returned. Return value E_INVALIDARG if bad [in] passed, [out] value is null. S_OK. hyperlinkIndex
() Returns the index of the hyperlink that is associated with this character index. This is the case when a link spans the given character index. [propget] HRESULT hyperlinkIndex( [in] long charIndex, [out] long hyperlinkIndex ); Parameters charIndex A 0 based index of the character for which to return the link index. If IAccessibleText is used to represent the text containing the link, then t...
...e character index is only valid if it is greater than or equal to zero and lower than the number of characters in the text. hyperlinkIndex The 0 based index of the hyperlink that is associated with this character index, or -1 if charIndex is not on a link. Return value E_INVALIDARG if bad [in] passed, [out] value is null. S_FALSE if there is nothing to return, [out] value is -1. S_OK. nHyperlinks
() Returns the number of links and link groups contained within this hypertext paragraph. [propget] HRESULT nHyperlinks( [out] long hyperlinkCount ); Parameters hyperlinkCount The number of links and link groups within this hypertext paragraph. Returns 0 if there is no link. Return value S_OK. See also IAccessibleHyperlink ...
IAccessibleImage
s/ia2/AccessibleImage.idlNot scriptable This interface represents images and icons. 1.0 66 Introduced Gecko 1.9 Inherits from: IUnknown Last changed in Gecko 1.9 (Firefox 3) This interface is used for a representation of images like icons on buttons. IAccessibleImage only needs to be implemented in certain situations. Some examples are: The accessible name and description
() are not enough to fully describe the image, for example when the accessible description
() is used to define the behavior of an actionable image and the image itself conveys semantically significant information. The user can edit the content that includes an image and therefore the user needs to be able to review the image's position. Method overview [propget] HRESULT description([out] BSTR de...
...The user can edit the content that includes an image and therefore the user needs to be able to review the image's position. Method overview [propget] HRESULT description([out] BSTR description ); [propget] HRESULT imagePosition([in] enum IA2CoordinateType coordinateType, [out] long x, [out] long y ); [propget] HRESULT imageSize([out] long height, [out] long width ); Methods description
() Returns the localized description of the image. [propget] HRESULT description( [out] BSTR description ); Parameters description The localized description of the image. Return value S_FALSE if there is nothing to return, [out] value is null. S_OK. imagePosition
() Returns the coordinates of the image. [propget] HRESULT imagePosition( [in] enum IA2CoordinateType coordinateType, [out] long x...
...[propget] HRESULT imageSize( [out] long height, [out] long width ); Parameters height The height of the image. width The width of the image. ...
amIWebInstallListener
nsIURI aUri, [array, size_is(aCount)] in nsIVariant aInstalls, [optional] in PRUint32 aCount); boolean onWebInstallRequested(in nsIDOMWindow aWindow, in nsIURI aUri, [array, size_is(aCount)] in nsIVariant aInstalls, [optional] in PRUint32 aCount); Note: Prior to Gecko 8.0, all references to nsIDOMWindow used in this interface were nsIDOMWindowInternal. Methods onWebInstallBlocked
() Called when the website is not allowed to directly prompt the user to install add-ons. boolean onWebInstallBlocked( in nsIDOMWindow aWindow, in nsIURI aUri, [array, size_is(aCount)] in nsIVariant aInstalls, in PRUint32 aCount Optional ); Parameters aWindow The window that triggered the installs. aUri The URI of the site that triggered the installs. aInstalls The ...
...rray, size_is(aCount)] in nsIVariant aInstalls, in PRUint32 aCount Optional ); Parameters aWindow The window that triggered the installs. aUri The URI of the site that triggered the installs. aInstalls The AddonInstalls that were blocked. aCount Optional The number of AddonInstalls. Return value true if the caller should start the installs. onWebInstallDisabled
() Called when installation by websites is currently disabled. void onWebInstallDisabled( in nsIDOMWindow aWindow, in nsIURI aUri, [array, size_is(aCount)] in nsIVariant aInstalls, in PRUint32 aCount Optional ); Parameters aWindow The window that triggered the installs. aUri The URI of the site that triggered the installs. aInstalls The AddonInstalls that were block...
...isabled( in nsIDOMWindow aWindow, in nsIURI aUri, [array, size_is(aCount)] in nsIVariant aInstalls, in PRUint32 aCount Optional ); Parameters aWindow The window that triggered the installs. aUri The URI of the site that triggered the installs. aInstalls The AddonInstalls that were blocked. aCount Optional The number of AddonInstalls. onWebInstallRequested
() Called when a website wants to ask the user to install add-ons. boolean onWebInstallRequested( in nsIDOMWindow aWindow, in nsIURI aUri, [array, size_is(aCount)] in nsIVariant aInstalls, in PRUint32 aCount Optional ); Parameters aWindow The window that triggered the installs. aUri The URI of the site that triggered the installs. aInstalls The AddonInstalls that we...
imgICache
image cache requests to use the permanent storage cache (ie. any images from windows in private browsing mode will not be present in the cache returned from a call with a null parameter). ...
... void clearCache(in boolean chrome); nsIProperties findEntryProperties(in nsIURI uri); void removeEntry(in nsIURI uri); Methods clearCache
() Evict images from the cache. void clearCache( in boolean chrome ); Parameters chrome If true, evict only chrome images. If false, evict everything except chrome images. findEntryProperties
() Find Properties Used to get properties such as 'type' and 'content-disposition' 'type' is a nsISupportsCString containing the images' mime type such as 'image/png' 'content-disposition' will be a nsISupportsCString containing the header If you call this before any data has been loaded from a URI, it will succeed, but come back empty. nsIProperties findEntryProperties( in nsIURI uri ); Paramete...
... containing the images' mime type such as 'image/png' 'content-disposition' will be a nsISupportsCString containing the header If you call this before any data has been loaded from a URI, it will succeed, but come back empty. nsIProperties findEntryProperties( in nsIURI uri ); Parameters uri The URI to look up. Return value null if the URL was not found in the cache. removeEntry
() Evict images from the cache. void removeEntry( in nsIURI uri ); Parameters uri The URI to remove. Exceptions thrown NS_OK If a uri was removed from the cache. NS_ERROR_NOT_AVAILABLE If a uri was unable to be removed from the cache. ...
imgIDecoder
modules/libpr0n/public/imgIDecoder.idlScriptable Base class for a decoder that reads an image from an input stream and sends it to an imgILoader object. Inherits from: nsISupports Last changed in Gecko 1.7 This interface is the base class for decoders for specific image formats. Method overview void close
(); void flush
(); void init(in imgILoad aLoad); unsigned long writeFrom(in nsIInputStream inStr, in unsigned long count); Methods close
() Closes the stream. void close
(); Parameters None. flush
() Flushes the stream. void flush
(); Parameters None. init
() Initializes an image decoder. void init( in imgILoad aLoad ); Parameters aLoad An imgILoad object to receive the decoded image data. This object also implements the imgID...
..., in unsigned long count); Methods close
() Closes the stream. void close
(); Parameters None. flush
() Flushes the stream. void flush
(); Parameters None. init
() Initializes an image decoder. void init( in imgILoad aLoad ); Parameters aLoad An imgILoad object to receive the decoded image data. This object also implements the imgIDecoderObserver interface; you should QueryInterface
() it to that interface and call its notification methods while handling the decode operation. You should always pass null as the first two parameters of the notification APIs. writeFrom
() Writes data into the stream from an input stream. Implementer's note: This method is defined by this interface in order to let the output stream efficiently copy the data from the input stream into its internal...
...unsigned long writeFrom( in nsIInputStream inStr, in unsigned long count ); Parameters inStr The stream from which to read the encoded image data. count The maximum number of bytes to write to the image. Return value The number of bytes actually written to the image, or undefined if an error occurred. ...
imgILoader
imgIRequest loadImage( in nsIURI aURI, in nsIURI aInitialDocumentURL, in nsIURI aReferrerURI, in nsIPrincipal aLoadingPrincipal, in nsILoadGroup aLoadGroup, in imgIDecoderObserver aObserver, in nsISupports aCX, in nsLoadFlags aLoadFlags, in nsISupports cacheKey, in imgIRequest aRequest, in nsIChannelPolicy channelPolicy ); Parameters ...
...ent. aLoadGroup Loadgroup to put the image load into. aObserver The observer (may be null) aCX Some random data. aLoadFlags Load flags for the request. cacheKey aRequest A newly created, unused imgIRequest object or null for one to be created for you. libpr0n does NOT keep a strong ref to the observer; this prevents reference cycles. This means that callers of loadImage should make sure to Cancel
() the resulting request before the observer goes away. channelPolicy Return value loadImageWithChannel
() Start the load and decode of an image. libpr0n does NOT keep a strong ref to the observer; this prevents reference cycles. This means that callers of loadImageWithChannel should make sure to Cancel
() the resulting request before the observer goes away. imgIRequest loadImageWithChannel( in n...
...thod is called, and there must have been no OnDataAvailable calls for it yet. aObserver The observer (may be null) cx Some random data. aListener A listener that you must send the channel's notifications and data to. Can be null, in which case imagelib has found a cached image and is not interested in the data. aChannel will be canceled for you in this case. Return value supportImageWithMimeType
() Checks if a decoder for the an image with the given mime type is available. boolean supportImageWithMimeType( in string mimeType ); Parameters mimeType The type to find a decoder for. Return value true if a decoder is available, false otherwise. ...
mozIAsyncHistory
void getPlacesInfo( in jsval aPlaceIdentifiers, in mozIVisitInfoCallback aCallback ); Parameters aPlaceIdentifiers The URI for which to determine the visited status. aCallback An object implementing the mozIVisitedStatus...
...onous request to determine whether or not a given URI has been visited; you must implement a callback to receive the result of the request. void getPlacesInfo( in jsval aPlaceIdentifiers, in mozIVisitInfoCallback aCallback ); Parameters aPlaceIdentifiers The URI for which to determine the visited status. aCallback An object implementing the mozIVisitedStatusCallback.isVisited
() method. If there's no information available for a given place, aCallback is called with a stub place info object, containing just the provided data (GUID or URI). isURIVisited
() Starts an asynchronous request to determine whether or not a given URI has been visited; you must implement a callback to receive the result of the request. void isURIVisited( in nsIURI aURI, in mozIVisitedStatusCall...
...sited; you must implement a callback to receive the result of the request. void isURIVisited( in nsIURI aURI, in mozIVisitedStatusCallback aCallback ); Parameters aURI The places for which to retrieve information, identified by either a single place GUID, a single URI, or a JS array of URIs and/or GUIDs. aCallback An object implementing the mozIVisitedStatusCallback.isVisited
() method; this method will be called with the results once the request has been completed. updatePlaces
() Adds a set of visits for one or more mozIPlaceInfo objects, and updates each mozIPlaceInfo's title or GUID. Note that this lets you add to history even in Private Browsing mode; if that's not desired you can first check whether the window is in Private Browsing mode. void updatePlaces( in m...
mozIStorageBindingParamsArray
The mozIStorageBindingParamsArray interface is a container for mozIStorageBindingParams objects, and is used to store sets of bound parameters that will be used by the mozIStorageStatement.executeAsync
(). storage/public/mozIStorageBindingParamsArray.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Inherits from: nsISupports You can only create these objects by calling the mozIStorageStatement.newBindingParamsArray
(). ...
...amsArray.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Inherits from: nsISupports You can only create these objects by calling the mozIStorageStatement.newBindingParamsArray
(). Method overview void addParams(in mozIStorageBindingParams aParameters); mozIStorageBindingParams newBindingParams
(); Attributes Attribute Type Description length unsigned long The number of mozIStorageBindingParams objects in the array. Methods addParams
() Adds the specified set of parameters to the end of the array. The appended parameters will be used when mozIStorageStatement.executeAsync
() is called. void addParams( in mozIStorageBindingParams aParameters...
...ms objects in the array. Methods addParams
() Adds the specified set of parameters to the end of the array. The appended parameters will be used when mozIStorageStatement.executeAsync
() is called. void addParams( in mozIStorageBindingParams aParameters ); Parameters aParameters The mozIStorageBindingParams object containing the parameters to append to the array. newBindingParams
() Creates and returns a new, empty, mozIStorageBindingParams object to which you can add parameters and their values for binding. mozIStorageBindingParams newBindingParams
(); Parameters None. ...
mozIStorageVacuumParticipant
ormation to allow a database to be periodically vacuumed by the Storage service. 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) To create an instance of this interface, use the Category Manger, with the category "vacuum-participant". Add more details here. Method overview boolean onBeginVacuum
(); void onEndVacuum(in boolean aSucceeded); Attributes Attribute Type Description databaseConnection mozIStorageConnection A connection to the database file to be vacuumed. expectedDatabasePageSize long The expected page size, in bytes, for the database. The vacuum manager will try to correct the page size when the browser is idle, using this value as a target. Valid page sizes are in ...
...is using the WAL journal node and the current page size is not the expected one, the journal node will be changed to TRUNCATE because WAL doesn't allow page size changes. The vacuum manager will try to restore WAL mode, but this will only work reliably if the participant properly resets statements. If the attempt to restore the journal node fails, it will remain TRUNCATE. Methods onBeginVacuum
() Called when a vacuum operation begins. Once you receive this notification, you should avoid using the database until onEndVacuum
() is called. boolean onBeginVacuum
(); Parameters None. Return value Return true to allow the vacuum operation to proceed, or false if you don't want the database to be vacuumed. You may wish to return false, for example, if you're in the middle of an operation that you...
... receive this notification, you should avoid using the database until onEndVacuum
() is called. boolean onBeginVacuum
(); Parameters None. Return value Return true to allow the vacuum operation to proceed, or false if you don't want the database to be vacuumed. You may wish to return false, for example, if you're in the middle of an operation that you don't want to (or can't) interrupt. onEndVacuum
() Called when a vacuum operation ends. void onEndVacuum( in boolean aSucceeded ); Parameters aSucceeded true if the vacuum operation was successful, or false if it wasn't successful. ...
ExtendSelection
<< nsIAccessible Page Summary This method extends the current selection from its current accessible anchor node to this accessible. ...
... << nsIAccessible Page Summary This method extends the current selection from its current accessible anchor node to this accessible. ...
... << nsIAccessible Page Summary This method extends the current selection from its current accessible anchor node to this accessible. ...
GetRelations
<< nsIAccessible Page Summary This method returns multiple accessible relations for this accessible object. nsIArray getRelations
(); Return value Returns nsIArray array of accessible relations for this object, every accessible relation object implements nsIAccessibleRelation interface. ...
... << nsIAccessible Page Summary This method returns multiple accessible relations for this accessible object. nsIArray getRelations
(); Return value Returns nsIArray array of accessible relations for this object, every accessible relation object implements nsIAccessibleRelation interface. ...
... << nsIAccessible Page Summary This method returns multiple accessible relations for this accessible object. nsIArray getRelations
(); Return value Returns nsIArray array of accessible relations for this object, every accessible relation object implements nsIAccessibleRelation interface. ...
NumActions
<< nsIAccessible Page Summary The number of accessible actions associated with this accessible. ...
... << nsIAccessible Page Summary The number of accessible actions associated with this accessible. ...
... << nsIAccessible Page Summary The number of accessible actions associated with this accessible. ...
RelationsCount
<< nsIAccessible Page Summary Returns the number of accessible relations for this object. ...
... << nsIAccessible Page Summary Returns the number of accessible relations for this object. ...
... << nsIAccessible Page Summary Returns the number of accessible relations for this object. ...
TakeSelection
<< nsIAccessible Page Summary This method selects this accessible node only. void takeSelection
(); Exceptions thrown NS_ERROR_FAILURE Indicates that the accessible is unattached from the accessible tree. ...
... << nsIAccessible Page Summary This method selects this accessible node only. void takeSelection
(); Exceptions thrown NS_ERROR_FAILURE Indicates that the accessible is unattached from the accessible tree. ...
... << nsIAccessible Page Summary This method selects this accessible node only. void takeSelection
(); Exceptions thrown NS_ERROR_FAILURE Indicates that the accessible is unattached from the accessible tree. ...
nsIAccessibleHyperLink
accessible/public/nsIAccessibleHyperLink.idlScriptable A cross-platform interface that supports hyperlink-specific properties and methods. Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) Method overview nsIAccessible getAnchor(in long index); Note: Renamed from getObject in Gecko 1.9 nsIURI getURI(in long index); boolean isSelected
(); Obsolete since Gecko 1.9 boolean isValid
(); Obsolete since Gecko 1.9 Attributes Attribute Type Description anchorCount long The number of anchors within this Hyperlink. Is normally 1 for anchors. This anchor is, for example, the visible output of the html:a tag. With an Image Map, reflects the actual areas within the map. Read only. Note: Renamed fro...
...ndex. Note: ARIA hyperlinks do not have an anchor accessible to point to, since clicks are processed via JavaScript. Note: In the case of an image map there is more than one link represented by this accessible. nsIAccessible getAnchor( in long index ); Parameters index The 0-based index whose object is to be returned. Return value The nsIAccessible object at the desired index. ...
.... getURI
() Returns the URI at the given index. Note: ARIA hyperlinks do not have an URI to point to, since clicks are processed via JavaScript. Therefore this property does not work on ARIA links. nsIURI getURI( in long index ); Parameters index The 0-based index of the URI to be returned. Return value The nsIURI object containing the specifications for the URI. isSelected
() Obsolete since Gecko 1.9 (Firefox 3) Note: Has been replaced by the selected attribute. boolean isSelected
(); Parameters None. Return value true if the element currently has the focus. isValid
() Obsolete since Gecko 1.9 (Firefox 3) Note: Has been replaced by the valid attribute. boolean isValid
(); Parameters None. Return value true if the ...
nsIAccessibleTreeCache
accessible. accessible/public/nsIAccessibleTreeCache.idlNot scriptable Please add a summary to this article. Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) Inherits from: nsISupports Method overview nsIAccessible getCachedTreeitemAccessible(in long aRow, in nsITreeColumn aColumn); void invalidateCache(in long aRow, in long aCount); void treeViewChanged
(); void treeViewInvalidated(in long aStartRow, in long aEndRow, in long aStartCol, in long aEndCol); Methods getCachedTreeitemAccessible
() Returns the tree item from the cache for the cell in the specified row and column; the nsIAccessible is created if it doesn't already exist in the cache. nsIAccessible getCachedTreeitemAccessible( in long aRow, in nsITreeColumn aColumn ); Parameters ...
...ow and column; the nsIAccessible is created if it doesn't already exist in the cache. nsIAccessible getCachedTreeitemAccessible( in long aRow, in nsITreeColumn aColumn ); Parameters aRow The row index. aColumn The column object. If is is null then the primary column is used. It makes sense for ATK only. Return value The nsIAccessible corresponding to the specified tree cell. invalidateCache
() Invalidates the number of cached treeitem accessibles. void invalidateCache( in long aRow, in long aCount ); Parameters aRow Row index the invalidation starts from. aCount The number of treeitem accessibles to invalidate, the number sign specifies whether rows have been inserted (plus) or removed (minus) treeViewChanged
() Invalidates children created for the previous tree view. void treeVi...
...tes the number of cached treeitem accessibles. void invalidateCache( in long aRow, in long aCount ); Parameters aRow Row index the invalidation starts from. aCount The number of treeitem accessibles to invalidate, the number sign specifies whether rows have been inserted (plus) or removed (minus) treeViewChanged
() Invalidates children created for the previous tree view. void treeViewChanged
(); Parameters None. treeViewInvalidated
() Fires name change events for invalidated area of tree. void treeViewInvalidated( in long aStartRow, in long aEndRow, in long aStartCol, in long aEndCol ); Parameters aStartRow Row index invalidation starts from. aEndRow Row index invalidation ends, -1 means the last row index. aStartCol Column index invalidation starts from. aEndCol Column index ...
nsIAlertsService
Note: If you are calling this function from JavaScript, you should wrap it in a try/catch because it can fail on Mac OS X prior to Firefox 22. void showAlertNotification( in AString imageUrl, in AString title, in AString text, in boolean textClickable, Optional in AString cookie, Optional in nsIObserver alertListener, Optional in AString name, Opti...
...hen hovered the notification background becomes lighter and the cursor turns to a pointer. Prior to Gecko 32 the text was made to look like a link. cookie Optional A blind cookie the alert passes back to the consumer during alert listener callbacks. alertListener Optional An object to receive callbacks from the alert; may be null if you don't care about callbacks. It must implement an observe
() method that accepts three parameters: subject: always null. topic: "alertfinished" when the alert disappears, "alertclickcallback" if the user clicks the text or "alertshow" (since Gecko 22) when the alert is shown. data: The value of the cookie parameter passed into the showAlertNotification method. name Optional A name for the notification; this is not displayed in the alert. How...
...lertshow') { console.log('just showed notification'); } else if (aTopic == 'alertfinished') { console.log('just alertfinished') } } }; as.showAlertNotification('chrome://branding/content/icon64.png', 'StackOverflow - New Messages', 'There are ## new messages. Click here to focus the tab', true, null, notifListener, 'StackOverflow Notifier'); closeAlert
() Closes alerts created by the service. void closeAlert( in AString name, Optional in nsIPrincipal principal Optional ); Parameters name The name of the notification to close. If no name is provided then only a notification created with no name (if any) will be closed. principal The title for the alert. See also Alerts and Notifications Bug 782211 - Implement notification API...
nsIAnnotationObserver
If aName is empty, then ALL annotations for the given item have been deleted. This is not called when annotations are expired (normally happens when the application exits). void onItemAnnotationRemoved( in long long aItemId, in AUTF8String aName ); Parameters aItemId The item whose annotation is to be deleted. aName The annota...
...annotation is deleted for an item. If aName is empty, then ALL annotations for the given item have been deleted. This is not called when annotations are expired (normally happens when the application exits). void onItemAnnotationRemoved( in long long aItemId, in AUTF8String aName ); Parameters aItemId The item whose annotation is to be deleted. aName The annotation name. onItemAnnotationSet
() This method is called when an annotation value is set for an item. It could be a new annotation, or it could be a new value for an existing annotation. void onItemAnnotationSet( in long long aItemId, in AUTF8String aName ); Parameters aItemId The item on which the annotation is to be set. aName The annotation name. onPageAnnotationRemoved
() Called when an annotation is deleted for a URI. I...
...lled when an annotation is deleted for a URI. If aName is empty, then ALL annotations for the given URI have been deleted. This is not called when annotations are expired (normally happens when the application exits). void onPageAnnotationRemoved( in nsIURI aURI, in AUTF8String aName ); Parameters aURI The URI whose annotation is to be deleted. aName The annotation name. onPageAnnotationSet
() This method is called when an annotation value is set for a URI. It could be a new annotation, or it could be a new value for an existing annotation. void onPageAnnotationSet( in nsIURI aPage, in AUTF8String aName ); Parameters aPage The URI on which the annotation is to be set. aName The annotation name. See also Places Using the Places annotation service Using the Places favicon service...
nsIApplicationCacheChannel
netwerk/base/public/nsIApplicationCacheChannel.idlScriptable This interface is implemented by communication channels that support application caches. 1.0 66 Introduced Gecko 1.9.1 Inherits from: nsIApplicationCacheContainer Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview void markOfflineCacheEntryAsForeign
(); Attributes Attribute Type Description chooseApplicationCache boolean When true, the channel will choose an application cache if one was not explicitly provided and none is available from the notification callbacks. The default value is false. This attribute will not be transferred through a redirect. Exceptions thrown NS_ERROR_ALREADY_OPENED If set after calling AsyncOpen
() on the channel. ...
... attribute will not be transferred through a redirect. Exceptions thrown NS_ERROR_ALREADY_OPENED If set after calling AsyncOpen
() on the channel. inheritApplicationCache boolean true if the channel will ask its notification callbacks for an application cache if one is not explicitly provided. The default value is true. Exceptions thrown NS_ERROR_ALREADY_OPENED If set after calling AsyncOpen
() on the channel. loadedFromApplicationCache PRBool true if the resource was loaded from the application cache, otherwise false. This value may be false even if the resource is assigned to an application cache if, for example, it was loaded as a fallback. Read only. Methods markOfflineCacheEntryAsForeign
() A shortcut method to mark the cache item of this channel as 'foreign'. See the 'cache ...
...herwise false. This value may be false even if the resource is assigned to an application cache if, for example, it was loaded as a fallback. Read only. Methods markOfflineCacheEntryAsForeign
() A shortcut method to mark the cache item of this channel as 'foreign'. See the 'cache selection algorithm' and CACHE_SELECTION_RELOAD action handling in nsContentSink. void markOfflineCacheEntryAsForeign
(); Parameters None. See also Offline resources in Firefox nsIApplicationCache nsIApplicationCacheContainer nsIApplicationCacheService nsIApplicationCacheNamespace nsIDOMOfflineResourceList ...
nsIArray
if an interface provides access to an nsIArray, that the array should not be QueryInterfaced to an nsIMutableArray for modification. If the interface in question had intended the array to be modified, it would have returned an nsIMutableArray! null is a valid entry in the array, and as such any nsISupports parameters may be null, except where noted. ...
...ll, except where noted. Method overview nsISimpleEnumerator enumerate
(); unsigned long indexOf(in unsigned long startIndex, in nsISupports element); void queryElementAt(in unsigned long index, in nsIIDRef uuid, [iid_is(uuid), retval] out nsQIResult result); Attributes Attribute Type Description length unsigned long The number of elements in the array. Read only. Methods enumerate
() Enumerate the array. nsISimpleEnumerator enumerate
(); Parameters None. Return value A new enumerator positioned at the start of the array. Exceptions thrown NS_ERROR_FAILURE If the array is empty (to make it easy to detect errors). NS_ERROR_OUT_OF_MEMORY If there is not enough memory to complete the operation. indexOf
() Get the position of a specific element. Note that since null is a valid in...
...Of( in unsigned long startIndex, in nsISupports element ); Parameters startIndex The initial element to search in the array. To start at the beginning, use 0 as the startIndex. element The element you are looking for. Return value A number >= startIndex which is the position of the element in the array. Exceptions thrown NS_ERROR_FAILURE If the element was not in the array. queryElementAt
() Retrieve a specific element of the array, and QueryInterface it to the specified interface. null is a valid result for this method, but exceptions are thrown in other circumstances. void queryElementAt( in unsigned long index, in nsIIDRef uuid, [iid_is(uuid), retval] out nsQIResult result ); Parameters index Position of element. uuid The IID of the requested interface. result The object, ...
nsIAsyncStreamCopier
Note: At least one of the ...
...Note: At least one of the streams must be buffered. ...
...unsigned long aChunkSize, in boolean aCloseSource, in boolean aCloseSink ); Parameters aSource Contains the data to be copied. aSink Specifies the destination for the data. aTarget Specifies the thread on which the copy will occur. A null value is permitted and causes the copy to occur on an unspecified background thread. aSourceBuffered true if aSource implements nsIInputStream.readSegments
(). aSinkBuffered true if aSink implements nsIInputStream.writeSegments
() . aChunkSize Specifies how many bytes to read and write at a time. This controls the granularity of the copy operation. This value should match the segment size of any buffered streams involved in the operation. aCloseSource true if aSource should be closed after copying. aCloseSink true if aSink should be closed after copyi...
nsIAuthPrompt
ng text, in wstring passwordRealm, in PRUint32 savePassword, inout wstring user, inout wstring pwd); Constants Constant Value Description SAVE_PASSWORD_NEVER 0 Never saves the password. SAVE_PASSWORD_FOR_SESSION 1 Saves the password for the session. SAVE_PASSWORD_PERMANENTLY 2 Saves the password permanently. Methods prompt
() This method puts up a text input dialog with OK and Cancel buttons. boolean prompt( in wstring dialogTitle, in wstring text, in wstring passwordRealm, in PRUint32 savePassword, in wstring defaultText, out wstring result ); Parameters dialogTitle The title of the dialog. text The text of the prompt message dialog box. passwordRealm The password realm. For example, ldap://lo...
...f the dialog. text The text of the prompt message dialog box. passwordRealm The password realm. For example, ldap://localhost/dc=test. savePassword Saving password option. One of the SAVE_PASSWORD_* constants defaultText The default text for the text input dialog box. result The result of the dialog box, OK or Cancel buttons. Return value true for OK, false for Cancel. promptPassword
() This method puts up a password dialog with OK and Cancel buttons. Note: If a username is specified, the username should be escaped. boolean promptPassword( in wstring dialogTitle, in wstring text, in wstring passwordRealm, in PRUint32 savePassword, inout wstring pwd ); Parameters dialogTitle The title of the dialog. text The text of the prompt message dialog box. passwordRea...
...username is specified (http://user@site.com) it will be used when matching existing logins or saving new ones. If no username is specified, only password-only logins will be matched or saved. savePassword Saving password option. One of the SAVE_PASSWORD_* constants pwd The password entered by the user if OK was selected. Return value true for OK, false for Cancel. promptUsernameAndPassword
() This method puts up a username/password dialog with OK and Cancel buttons. boolean promptUsernameAndPassword( in wstring dialogTitle, in wstring text, in wstring passwordRealm, in PRUint32 savePassword, inout wstring user, inout wstring pwd ); Parameters dialogTitle The title of the dialog. text The text of the prompt message dialog box. passwordRealm The password realm. F...
nsIAutoCompleteSearch
toolkit/components/autocomplete/nsIAutoCompleteSearch.idlScriptable This interface is implemented by search providers to start and stop autocomplete. Inherits from: nsISupports Last changed in Gecko 1.7 Users call startSearch
() and pass in an nsIAutoCompleteObserver when the search starts. Results can be sent to the listener either synchronously or asynchronously, depending on the implementation. Method overview void startSearch(in AString searchString, in AString searchParam, in nsIAutoCompleteResult previousResult, in nsIAutoCompleteObserver listener); void stopSearch
(); Methods startSearch
() Search for a given string and notify a listener (either synchronously or asynchronously) of the result. void startSearch( in AString searchString, in AString searchParam, ...
... ...
..., in nsIAutoCompleteObserver listener ); Parameters searchString The string to search for. searchParam An extra parameter. Can be empty if not needed. previousResult The previous nsIAutoCompleteResult to use for faster searching. Can be null. listener An nsIAutoCompleteObserver listener to notify when the search is complete. stopSearch
() Stop all searches that are in progress. void stopSearch
(); Parameters None. ...
nsIBlocklistService
unsigned long getAddonBlocklistState( in jsval addon, in AString appVersion, Optional in AString toolkitVersion Optional ); Parameters addon The addon object whose blocklist state is to be determined. appVersion Optional The version of the application we are checking in the blocklist. If this parameter is null, the version of the...
... The version of the application we are checking in the blocklist. If this parameter is null, the version of the running application is used. toolkitVersion Optional The version of the toolkit we are checking in the blocklist. If this parameter is null, the version of the running toolkit is used. Return value The blocklist state of the add-on, one of the Constants. getPluginBlocklistState
() Determine the blocklist state of a plugin. unsigned long getPluginBlocklistState( in nsIPluginTag plugin, in AString appVersion, Optional in AString toolkitVersion Optional ); Parameters plugin The plugin to get the state for. appVersion Optional The version of the application we are checking in the blocklist. If this parameter is null, the version of the running applicati...
...al The version of the application we are checking in the blocklist. If this parameter is null, the version of the running application is used. toolkitVersion Optional The version of the toolkit we are checking in the blocklist. If this parameter is null, the version of the running toolkit is used. Return value The blocklist state of the plugin, one of the Constants. isAddonBlocklisted
() Determine if an item is blocklisted. boolean isAddonBlocklisted( in jsval addon, in AString appVersion, Optional from Gecko 1.9.1 in AString toolkitVersion Optional from Gecko 1.9.1 ); Parameters addon The addon object to be checked. appVersion Optional from Gecko 1.9.1 The version of the application we are checking in the blocklist. If this parameter is null, the version ...
nsICharsetResolver
ublic/nsICharsetResolver.idlScriptable Please add a summary to this article. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void notifyResolvedCharset(in ACString charset, in nsISupports closure); ACString requestCharset(in nsIWebNavigation aWebNavigation, in nsIChannel aChannel, out boolean aWantCharset, out nsISupports aClosure); Methods notifyResolvedCharset
() Some implementations may request that they be notified when the charset is actually detected. void notifyResolvedCharset( in ACString charset, in nsISupports closure ); Parameters charset The detected charset. closure The closure returned by requestCharset
(). requestCharset
() Called to resolve the charset that should be used for parsing the document being loaded from aChannel. If the cha...
...ACString requestCharset( in nsIWebNavigation aWebNavigation, in nsIChannel aChannel, out boolean aWantCharset, out nsISupports aClosure ); Parameters aWebNavigation The nsIWebNavigation the document is being loaded in. May be null. aChannel The channel the document is coming in from. ...
...d charset and the closure that requestCharset set. ACString requestCharset( in nsIWebNavigation aWebNavigation, in nsIChannel aChannel, out boolean aWantCharset, out nsISupports aClosure ); Parameters aWebNavigation The nsIWebNavigation the document is being loaded in. May be null. aChannel The channel the document is coming in from. aWantCharset Gets set to true if notifyResolvedCharset
() should be called with the given aClosure object. aClosure A resulting object which should be passed to notifyResolvedCharset
() if aWantCharset is set to true. Return value The resolved charset, or an empty string if no charset could be determined. ...
nsIClipboardDragDropHookList
tended for direct use by embedders; it is an implementation detail. You should access these capabilities indirectly by sending commands using the nsIClipboardDragDropHooks interface. Within Gecko, this interface is used by calling get_Interface on a docshell. Method overview void addClipboardDragDropHooks(in nsIClipboardDragDropHooks aHooks); nsISimpleEnumerator getHookEnumerator
(); void removeClipboardDragDropHooks(in nsIClipboardDragDropHooks aHooks); Methods addClipboardDragDropHooks
() This method adds a hook to the list. void addClipboardDragDropHooks( in nsIClipboardDragDropHooks aHooks ); Parameters aHooks Implementation of hooks. getHookEnumerator
() This method retrieves an enumerator for all hooks which have been added. nsISimpleEnumerato...
...Note: If this implementation is not present in the list then removal will be ignored. ...
...Note: If this implementation is not present in the list then removal will be ignored. ...
nsICookieManager
changed in Gecko 1.7 Inherits from: nsISupports This interface is intended to be used as a service. It is implemented by the @mozilla.org/cookiemanager;1 component, but should generally be accessed via Services.cookies Method overview void remove(in AUTF8String aHost, in ACString aName, in AUTF8String aPath, in boolean aBlocked, in jsval aOriginAttributes); void removeAll
(); Attributes Attribute Type Description enumerator nsISimpleEnumerator Called to enumerate through each cookie in the cookie list. The objects enumerated over are of type nsICookie. Read only. Methods remove
() This method is called to remove an individual cookie from the cookie list, specified by host, name, and path. If the cookie cannot be found, no...
...nd path. If the cookie cannot be found, no exception is thrown. Typically, the arguments to this method will be obtained directly from the desired nsICookie object. void remove( in AUTF8String aHost, in ACString aName, in AUTF8String aPath, in boolean aBlocked, in jsval aOriginAttributes ); Parameters aHost The host or domain for which the cookie was set. ...
...he cookie was set. See nsICookieManager2.add
() for a description of acceptable host strings. If the target cookie is a domain cookie, a leading dot must be present. aName The name specified in the cookie. aPath The path for which the cookie was set. aBlocked Indicates if cookies from this host should be permanently blocked. aOriginAttributes The originAttributes of this cookie. removeAll
() This method is called to remove all cookies from the cookie list. void removeAll
(); Parameters None. See also nsICookie nsICookie2 nsICookieManager2 nsICookiePermission ...
nsIDNSRecord
iptable This interface represents the result of a DNS lookup. Since a DNS query may return more than one resolved IP address, the record acts like an enumerator, allowing the caller to easily step through the list of IP addresses. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview PRNetAddr getNextAddr(in PRUint16 aPort); Native code only! ACString getNextAddrAsString
(); boolean hasMore
(); void rewind
(); Attributes Attribute Type Description canonicalName ACString for example, www.mozilla.org --> rheet.mozilla.org. Read only. Methods Native code only!getNextAddr This function copies the value of the next IP address into the given PRNetAddr struct and increments the internal address iterator. PRNetAddr getNextAddr( in PRUint16 aPort ); Parameter...
...w.mozilla.org --> rheet.mozilla.org. Read only. Methods Native code only!getNextAddr This function copies the value of the next IP address into the given PRNetAddr struct and increments the internal address iterator. PRNetAddr getNextAddr( in PRUint16 aPort ); Parameters aPort A port number to initialize the PRNetAddr with. Return value The value of the next IP address. getNextAddrAsString
() This function returns the value of the next IP address as a string and increments the internal address iterator. ACString getNextAddrAsString
(); Parameters None. Return value The value of the next IP address as a string. hasMore
() This method checks if there is another address in the record. boolean hasMore
(); Parameters None. Return value true if there is another address in the record. rewind(...
...ess iterator. ACString getNextAddrAsString
(); Parameters None. Return value The value of the next IP address as a string. hasMore
() This method checks if there is another address in the record. boolean hasMore
(); Parameters None. Return value true if there is another address in the record. rewind
() This function resets the internal address iterator to the first address in the record. void rewind
(); Parameters None. ...
nsIDOMGeoGeolocation
Callback, [optional] in nsIDOMGeoPositionErrorCallback errorCallback, [optional] in nsIDOMGeoPositionOptions options); Attributes Attribute Type Description lastPosition nsIDOMGeoPosition The most recently retrieved location as seen by the provider. May be null. Read only. Methods clearWatch
() When the clearWatch
() method is called, the watch
() process stops calling for new position identifiers and cease invoking callbacks. void clearWatch( in unsigned short watchId ); Parameters None. getCurrentPosition
() Acquires the user's current position via a new position object. If this fails, errorCallback is invoked with an nsIDOMGeoPositionError argument. void getCurrentPosition( in nsIDO...
...ons options ); Parameters successCallback An nsIDOMGeoPositionCallback to be called when the current position is available. errorCallback An nsIDOMGeoPositionErrorCallback that is called if an error occurs while retrieving the position; this parameter is optional. options An nsIDOMGeoPositionOptions object specifying options; this parameter is optional. watchPosition
() Similar to getCurrentPosition
(), except it continues to call the callback with updated position information periodically until clearWatch
() is called. unsigned short watchPosition( in nsIDOMGeoPositionCallback successCallback, [optional] in nsIDOMGeoPositionErrorCallback errorCallback, [optional] in nsIDOMGeoPositionOptions options ); Parameters successCallback An nsIDOMGeoPosition...
... ...
nsIDOMHTMLTimeRanges
dom/interfaces/html/nsIDOMHTMLTimeRanges.idlScriptable Please add a summary to this article. ...
... dom/interfaces/html/nsIDOMHTMLTimeRanges.idlScriptable Please add a summary to this article. ...
...lease add a summary to this article. Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Inherits from: nsISupports Method overview float start(in unsigned long index); float end(in unsigned long index); Attributes Attribute Type Description length unsigned long The number of ranges represented by the nsIDOMHTMLTimeRanges object. Read only. Methods end
() Returns the time offset to the end of the specified time range. float end( in unsigned long index ); Parameters index The index to the time range whose end time is to be returned. Return value The time at which the specified range ends, in seconds measured from the beginning of the timeline represented by the object. Exceptions thrown INDEX_SIZE_ERR The specified index is not valid. start(...
nsIDeviceMotion
erface was named nsIDeviceMotion prior to Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3). Method overview void addListener(in nsIDeviceMotionListener aListener); void addWindowListener(in nsIDOMWindow aWindow); Native code only! void removeListener(in nsIDeviceMotionListener aListener); void removeWindowListener(in nsIDOMWindow aWindow); Native code only! Methods addListener
() When called, the accelerometer support implementation must begin to notify the specified nsIDeviceMotionListener by calling its nsIDeviceMotionListener.onAccelerationChange
() method as appropriate to share updated acceleration data. void addListener( in nsIDeviceMotionListener aListener ); Parameters aListener The nsIDeviceMotionListener object whose nsIDeviceMotionListener.onAccelerationChan...
...hen called, the accelerometer support implementation must begin to notify the specified nsIDeviceMotionListener by calling its nsIDeviceMotionListener.onAccelerationChange
() method as appropriate to share updated acceleration data. void addListener( in nsIDeviceMotionListener aListener ); Parameters aListener The nsIDeviceMotionListener object whose nsIDeviceMotionListener.onAccelerationChange
() method should be called with updated acceleration data. Native code only!addWindowListener Sets the nsIAccelerometer as the source for MozOrientation events on the specified DOM window. ...
...void removeListener( in nsIDeviceMotionListener aListener ); Parameters aListener The nsIDeviceMotionListener object to which no further updates should be sent. ...
nsIDirectoryService
xpcom/io/nsIDirectoryService.idlScriptable This interface provides methods to initialize and configure a directory service instance. The XPCOM Directory Service implements this interface to provide support for a variety of well-known file and directory locations. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void init
(); void registerProvider(in nsIDirectoryServiceProvider prov); void unregisterProvider(in nsIDirectoryServiceProvider prov); init
() Initializes the nsIDirectoryService instance. This method must be called before an nsIDirectoryService instance can be used. In the case of the XPCOM Directory Service, this method is called as part of XPCOM initialization. Must not be called by external code; called internally by XPCOM initializatio...
...der prov); void unregisterProvider(in nsIDirectoryServiceProvider prov); init
() Initializes the nsIDirectoryService instance. This method must be called before an nsIDirectoryService instance can be used. In the case of the XPCOM Directory Service, this method is called as part of XPCOM initialization. Must not be called by external code; called internally by XPCOM initialization. void init
(); Parameters None. registerProvider
() Register a provider with the service. The directory service will keep a strong reference to the nsIDirectoryServiceProvider instances registered via registerProvider. The providers will be released when the service is destroyed at XPCOM shutdown. ...
...st not be called by external code; called internally by XPCOM initialization. void init
(); Parameters None. registerProvider
() Register a provider with the service. The directory service will keep a strong reference to the nsIDirectoryServiceProvider instances registered via registerProvider. The providers will be released when the service is destroyed at XPCOM shutdown. Call unregisterProvider
() to force the directory service to relinquish ownership of a particular provider instance. void registerProvider( in nsIDirectoryServiceProvider prov ); Parameters prov The nsIDirectoryServiceProvider to register with the service. unregisterProvider
() Unregister a provider that was previously registered with the directory service. void unregisterProvider( in nsIDirectoryServiceProvider prov...
nsIDroppedLinkHandler
boolean canDropLink( in nsIDOMDragEvent aEvent, in PRBool aAllowSameDocument ); Parameters aEvent A dragenter or dragover event. aAllowSameDocument If false, drops are only allowed if the document of the source of the drag is different from the destination. This check includes any parent, sibling and child frames in the same content...
...dragover event. aAllowSameDocument If false, drops are only allowed if the document of the source of the drag is different from the destination. This check includes any parent, sibling and child frames in the same content tree. If true, the source is not checked. Return value true if the link being dragged can be dropped. Exceptions thrown Missing Exception Missing Description dropLink
() Given a drop event, determines the link being dragged. If a uri is returned the caller can, for instance, load it. If null is returned, there is no valid link to be dropped. AString dropLink( in nsIDOMDragEvent aEvent, out AString aName, [optional] in boolean aDisallowInherit ); Parameters aEvent A drop event. aName The link title if it exists, or an empty string otherwise. Retu...
... valid link to be dropped. Exceptions thrown NS_ERROR_DOM_SECURITY_ERR Error will be thrown and the event canceled if the receiving target should not load the uri for security reasons. This will occur if the source of the drag initiated a link for dragging that it itself cannot access. This prevents a source document from tricking the user into a dragging a chrome url for example. dropLinks
() Given a drop event, determines the link being dragged. If non-empty links array is returned the caller can, for instance, load it. If empty links array is returned, there is no valid link to be dropped. void dropLinks( in nsIDOMDragEvent aEvent, [optional] in boolean aDisallowInherit, [optional] out unsigned long aCount, [retval, array, size_is(aCount)] out nsIDroppedLinkItem aLinks ); ...
nsIEnvironment
ports Last changed in Gecko 1.7 Implemented by: @mozilla.org/process/environment;1 as a service: var env = Components.classes["@mozilla.org/process/environment;1"]. getService(Components.interfaces.nsIEnvironment); Method overview void set(in AString aName, in AString aValue); AString get(in AString aName); boolean exists(in AString aName); Methods set
() Set the value of an environment variable. void set( in AString aName, in AString aValue ); Parameters aName The variable name to set. aValue The value to set. get
() Get the value of an environment variable. AString get( in AString aName ); Parameters aName the variable name to retrieve. Return value Returns the value of the env variable. An empty string wi...
... aName The variable name to set. aValue The value to set. get
() Get the value of an environment variable. AString get( in AString aName ); Parameters aName the variable name to retrieve. Return value Returns the value of the env variable. An empty string will be returned when the env variable does not exist or when the value itself is an empty string - please use exists
() to probe whether the env variable exists or not. exists
() Check the existence of an environment variable. This method checks whether an environment variable is present in the environment or not. Note: * For Unix/Linux platforms we follow the Unix definition: An environment variable exists when getenv
() returns a non-NULL value. An environment variable does not exist when getenv
() returns NULL. ...
... boolean exists( in AString aName ); Parameters aName The variable name to probe. Return value If the variable has been set, the value returned is PR_TRUE. If the variable was not defined in the environment PR_FALSE will be returned. ...
nsIEventListenerInfo
describes how an event listener was added to an event target; these are returned by nsIEventListenerService.getListenerInfoFor, which provides a list of all the listeners to a given event target. 1.0 66 Introduced Gecko 1.9.2 Inherits from: nsISupports Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Method overview nsISupports getDebugObject
(); AString toSource
(); Attributes Attribute Type Description allowsUntrusted boolean Indicates whether or not the event listener allows untrusted events. Read only. capturing boolean Indicates whether or not the event listener is in capture mode. Read only. inSystemEventGroup boolean Indicates whether or not the event listen...
...tener allows untrusted events. Read only. capturing boolean Indicates whether or not the event listener is in capture mode. Read only. inSystemEventGroup boolean Indicates whether or not the event listener is in the system event group. Read only. type AString The type of the event for which the listener was added. Read only. Methods getDebugObject
() Returns the debugger object if the debug service is active. nsISupports getDebugObject
(); Parameters None. Return value If jsdIDebuggerService is active and the listener is implemented in JS, this returns the listener as a jsdIValue. Otherwise null. This is the method you should use if you want to get access to the actual listener, but the debugger service must be already active, which significa...
...t access to the actual listener, but the debugger service must be already active, which significantly slows down script execution. Accordingly, this should probably only be used by real debuggers. This approach is necessary because event listeners added with addEventListener won't necessarily be nsIEventListeners; the DOM code will fix up ordinary JavaScript functions to act as listeners. toSource
() Tries to serialize the event listener to a string. AString toSource
(); Parameters None. Return value Returns a string describing the event listener, or null if serialization isn't possible (for example, if the listener was written in C++). Remarks nsIEventListenerInfo was introduced with bug 448602. See also nsIEventListenerService nsIEventTarget ...
nsIExternalHelperAppService
boolean applyDecodingForExtension( in AUTF8String aExtension, in ACString aEncodingType ); Parameters aExtension The filename extension to check. aEncodingType The encoding type to check. Return ...
...boolean applyDecodingForExtension( in AUTF8String aExtension, in ACString aEncodingType ); Parameters aExtension The filename extension to check. aEncodingType The encoding type to check. Return value true if data from URLs with the specified extension and encoding should be decoded prior to saving the file or delivering it to a helper application; otherwise false. doContent
() Binds an external helper application to a stream listener. The caller should pump data into the returned stream listener. When the OnStopRequest is issued, the stream listener implementation will launch the helper app with this data. nsIStreamListener doContent( in ACString aMimeContentType, in nsIRequest aRequest, in nsIInterfaceRequestor aWindowContext, in boolean aForceSave ); Paramet...
... will launch the helper app with this data. nsIStreamListener doContent( in ACString aMimeContentType, in nsIRequest aRequest, in nsIInterfaceRequestor aWindowContext, in boolean aForceSave ); Parameters aMimeContentType The content type of the incoming data. aRequest The request corresponding to the incoming data. aWindowContext Use nsIServiceManager.getInterface
() to retrieve properties like the DOM window or parent window; the service might need this in order to bring up dialogs. aForceSave true to always save this content to disk, regardless of nsIMIMEInfo and other such influences. Return value A nsIStreamListener which the caller should pump the data into. ...
nsIFeedContainer
categories nsIArray An array of the categories found in a feed or entry. Note: The returned array will contain nsIFeedCategory objects, except that interface has not been implemented yet. contributors nsIArray An array of nsIFe...
...Bag2 Provides access to all the fields found in the document. Common Atom and RSS fields are normalized, including some namespaced extensions such as "dc:subject" and "content:encoded". Consumers can avoid normalization by checking the feed type and accessing specific fields. Common namespaces are accessed using prefixes, such as get("dc:subject");. See nsIFeedResult.registerExtensionPrefix
() for more information about prefixes. id AString A string that identifies the feed or entry. Not all feeds have these, but all major feed formats have IDs for each entry. link nsIURI A URI containing the primary link for the feed or entry. links nsIArray An array of all links for a feed or entry. rights nsIFeedTextConstruct The feed o...
...or license text. title nsIFeedTextConstruct The feed or entry's title. Keep in mind that some feeds have no title, and some use markup in their titles, so be cautious when decoding this attribute. updated AString A string containing the date the feed or entry was last updated, in RFC822 form. This string is parsable by JavaScript and mail code. Methods normalize
() Synchronizes a container's fields with its convenience attributes. void normalize
(); Parameters None. See also nsIURI nsIFeedTextConstruct Interwiki link ...
nsIFrameMessageManager
ageListenerManager or nsIMessageSender instead. Method overview void addMessageListener(in AString aMessage, in nsIFrameMessageListener aListener, [optional] in boolean listenWhenClosed); void removeMessageListener(in AString aMessage, in nsIFrameMessageListener aListener); void sendAsyncMessage(in AString aMessage, in AString json); Methods addMessageListener
() Adds a message listener to the local frame. This listener will receive messages sent from the remote frame. void addMessageListener( in AString aMessage, in nsIFrameMessageListener aListener [optional in boolean listenWhenClosed ); Parameters aMessage The name of the message for which to add a listener. aListener An object implementing nsIFrameMessageListener whose receiveMessage ...
... want to receive messages during the short period after a frame has been removed from the DOM and before its frame script has finished unloading. This parameter only has an effect for frame message managers in the main process. An alternative method to listen for death of frame script is to use message-manager-disconnect observer: Observer Notifications :: Message Manager. ...
...ved from the DOM and before its frame script has finished unloading. This parameter only has an effect for frame message managers in the main process. An alternative method to listen for death of frame script is to use message-manager-disconnect observer: Observer Notifications :: Message Manager. removeMessageListener
() Removes a message listener previously added by calling addMessageListener
(). void removeMessageListener( in AString aMessage, in nsIFrameMessageListener aListener ); Parameters aMessage The name of the message for which to remove a listener. aListener An object implementing nsIFrameMessageListener to stop receiving messages. sendAsyncMessage
() Asynchronously sends a message to the listeners. void sendAsyncMessage( in AString aMessage, in AString json...
nsIGeolocationProvider
ptable Notify the geolocation service that a new geolocation has been discovered. 1.0 66 Introduced Gecko 1.9.1 Inherits from: nsISupports Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) This must be called on the main thread Interface provides location information to the nsGeolocator via the nsIDOMGeolocationCallback interface. After startup
() is called, any geo location change should call callback.update
(). The nsIGeolocationProvider interface provides information about the current users location to interested parties via nsIGeolocationUpdate. After the provider has been initialized, any changes to location should call callback.onRequest
(). You may find the WiFi access point monitoring service useful if you wish to implement support f...
...ies via nsIGeolocationUpdate. After the provider has been initialized, any changes to location should call callback.onRequest
(). You may find the WiFi access point monitoring service useful if you wish to implement support for WiFi-based location services. See dom/src/geolocation/NetworkGeolocationProvider.js for an example of how to write a geolocation provider. Method overview boolean isReady
(); Obsolete since Gecko 1.9.2 void shutdown
(); void startup
(); void watch(in nsIGeolocationUpdate callback); Methods isReady
() Obsolete since Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Reports whether or not the device is ready and has a position. boolean isReady
(); Parameters None. Return value true if the device is ready and has a position availab...
...tdown
(); void startup
(); void watch(in nsIGeolocationUpdate callback); Methods isReady
() Obsolete since Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Reports whether or not the device is ready and has a position. boolean isReady
(); Parameters None. Return value true if the device is ready and has a position available to return; otherwise false. shutdown
() Shuts down the location device. void shutdown
(); Parameters None. startup
() Start up the provider. This is called before any other method and may be called multiple times. void startup
(); Parameters None. watch
() Attaches a callback listener to be notified when a location change is observed. void watch( in nsIGeolocationUpdate callback ); Parameters callback An nsIGeolocationUpdate to be no...
nsIHTTPHeaderListener
modules/plugin/base/public/nsIHTTPHeaderListener.idlScriptable This interface allows plugin authors to access HTTP Response headers after issuing an nsIPluginHost.GetURL or nsIPluginHost.PostURL call. Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) Note: The plugin author must provide an instance to {GetURL,PostURL}
() that implements both nsIPluginStreamListener and nsIHTTPHeaderListener. ...
...s interface allows plugin authors to access HTTP Response headers after issuing an nsIPluginHost.GetURL or nsIPluginHost.PostURL call. Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) Note: The plugin author must provide an instance to {GetURL,PostURL}
() that implements both nsIPluginStreamListener and nsIHTTPHeaderListener. This instance is passed in through {GetURL,PostURL}
()'s streamListener parameter. The browser will then QI this streamListener to see if it implements nsIHTTPHeaderListener. Method overview void newResponseHeader(in string headerName, in string headerValue); void statusLine(in string line); Methods newResponseHeader
() Called for each HTTP Response header. Note: You must copy the values of the params. void newResponseHeader(...
.... Method overview void newResponseHeader(in string headerName, in string headerValue); void statusLine(in string line); Methods newResponseHeader
() Called for each HTTP Response header. Note: You must copy the values of the params. void newResponseHeader( in string headerName, in string headerValue ); Parameters headerName headerValue statusLine
() Called once for the HTTP Response status line. Value does not include a terminating newline. Note: You must copy this value. void statusLine( in string line ); Parameters line ...
nsIIdleService
); Attributes Attribute Type Description idleTime unsigned long The amount of time in milliseconds that has passed since the last user activity. Can be 0 if there is no valid idle time to report (this can happen if the user never interacted with the browser at all, and if we are unable to poll for idle time manually). Read only. Methods addIdleObserver
() Add an observer to be notified when the user idles for some period of time, and when they get back from that. The subject of the notification the observer will get is always the nsIIdleService itself. When the user goes idle, the observer topic is 'idle' and when they get back, the observer topic is 'back' in Gecko 15 and earlier or 'active' in Gecko 16 and later. The data parameter for the n...
...ut if the user remains idle for an extended period: 'idle-daily'. The data parameter for the notification contains the current user idle time. void addIdleObserver( in nsIObserver observer, in unsigned long time ); Parameters observer The nsIObserver to be notified. time The amount of time in seconds the user should be idle before the observer should be notified. removeIdleObserver
() Remove an observer registered with addIdleObserver
(). Note: Removing an observer will remove it once, for the idle time you specify. If you have added an observer multiple times, you will need to remove it just as many times. void removeIdleObserver( in nsIObserver observer, in unsigned long time ); Parameters observer The nsIObserver to be removed. time The amount of time they wer...
...emove it just as many times. void removeIdleObserver( in nsIObserver observer, in unsigned long time ); Parameters observer The nsIObserver to be removed. time The amount of time they were listening for. Example Example 1 var idleService = Components.classes["@mozilla.org/widget/idleservice;1"] .getService(Components.interfaces.nsIIdleService) setTimeout(function
() { alert(idleService.idleTime) }, 1000) // if you don't use the mouse or the keyboard after running this snippet, // you'll see a number around 1000 alerted. Example 2 var idleService = Components.classes["@mozilla.org/widget/idleservice;1"] .getService(Components.interfaces.nsIIdleService) var idleObserver = { observe: function(subject, topic, data) { alert("topic: " + ...
nsIInProcessContentFrameMessageManager
Return value The nsIContent object representing the owner's content. See also Content process event handling nsIContentFrameMessageManager ...
...Return value The nsIContent object representing the owner's content. See also Content process event handling nsIContentFrameMessageManager ...
...Return value The nsIContent object representing the owner's content. See also Content process event handling nsIContentFrameMessageManager ...
nsIInputStreamCallback
xpcom/io/nsIAsyncInputStream.idlScriptable This is a companion interface for nsIAsyncInputStream.asyncWait
(). Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void onInputStreamReady(in nsIAsyncInputStream aStream); Methods onInputStreamReady
() Called to indicate that the stream is either readable or closed. ...
...cWait
(). Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void onInputStreamReady(in nsIAsyncInputStream aStream); Methods onInputStreamReady
() Called to indicate that the stream is either readable or closed. void onInputStreamReady( in nsIAsyncInputStream aStream ); Parameters aStream The stream whose nsIAsyncInputStream.asyncWait
() method was called. ...
... Method overview void onInputStreamReady(in nsIAsyncInputStream aStream); Methods onInputStreamReady
() Called to indicate that the stream is either readable or closed. ...
nsIJSID
ox 3) The following methods return objects that implement this interface: Components.interfaces.name Components.classes[contract] Components.interfacesById[uuid] Components.classesById[cid] The first two cases create a named JSID while the last two cases create an unnamed JSID. An unnamed JSID also results when you implement a function that is passed an nsIIDRef parameter, such as QueryInterface
(). Note that for these cases of JSID the specified class or interface must exist and be scriptable. Method overview boolean equals(in nsIJSID other); const nsID* getID
(); Violates the XPCOM interface guidelines void initialize(in string idString); string toString
(); Attributes Attribute Type Description id nsIDPtr Read only. Native code only! Obsolete since Gecko 1.9 The internal ...
...in string idString); string toString
(); Attributes Attribute Type Description id nsIDPtr Read only. Native code only! Obsolete since Gecko 1.9 The internal nsID. name string Read only. The name of the JSID, if it was set. number string Read only. The string representation of the internal nsID. valid boolean Read only. Returns true if the JSID has been initialised. Methods equals
() This method determines if this nsIJSID has the same nsID as another nsIJSID. boolean equals( in nsIJSID other ); Parameters other The other nsIJSID to compare to. Return value true if the nsIJSID's are valid and have the same nsID, otherwise false. Violates the XPCOM interface guidelines getID
() const nsID* getID
(); Parameters None. Return value A pointer to the internal nsID structu...
...etermines if this nsIJSID has the same nsID as another nsIJSID. boolean equals( in nsIJSID other ); Parameters other The other nsIJSID to compare to. Return value true if the nsIJSID's are valid and have the same nsID, otherwise false. Violates the XPCOM interface guidelines getID
() const nsID* getID
(); Parameters None. Return value A pointer to the internal nsID structure. initialize
() Initializes the JSID. void initialize( in string idString ); Parameters idString The number to initialize the JSID, in string format, e.g. {00000000-0000-0000-c000-000000000046}. A JSID can only be initialized once. toString
() This methods returns a string representation of the object. string toString
(); Parameters None. Return value The name of the JSID if it has one, otherwise the string ...
nsIMacDockSupport
Attributes Attribute Type Description badgeText AString Text to display in a badge on the application's dock icon. This can be used, for example, to display the number of unread messages in an email client. dockMenu nsIStandaloneMenu The menu to display when the user right-clicks on the application's icon in the dock. Methods activateApplication
() Activates the application, making it the frontmost application. The application should call this to activate itself when one of its dock menu items are selected, since doing so does not automatically activate the application. void activateApplication( in boolean aIgnoreOtherApplications ); Parameters aIgnoreOtherApplications If true, the application is activated regardless of the stat...
...p://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menupopup'); macMenu.setAttribute('id', 'myMacMenu'); var macMenuItem = win.document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menuitem'); macMenuItem.setAttribute('label', 'Show Most Recent Window'); macMenuItem.setAttribute('id', 'myMacMenuItem'); macMenuItem.addEventListener('command', function
(){ var dockSupport = Cc['@mozilla.org/widget/macdocksupport;1'].getService(Ci.nsIMacDockSupport); dockSupport.activateApplication(true); Services.wm.getMostRecentWindow(null).focus
() }) macMenu.appendChild(macMenuItem); var mainPopupSet = win.document.getElementById('mainPopupSet'); mainPopupSet.appendChild(macMenu); let dockMenuElement = macMenu; //document.getElementById("menu_mac_dockmenu...
...ommended way to add to the native menu, just maniuplate the default menu DOM element. var macMenuItem = Services.appShell.hiddenDOMWindow.document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menuitem'); macMenuItem.setAttribute('label', 'Show Most Recent Window'); macMenuItem.setAttribute('id', 'myMacMenuItem'); macMenuItem.addEventListener('command', function
(){ var dockSupport = Cc['@mozilla.org/widget/macdocksupport;1'].getService(Ci.nsIMacDockSupport); dockSupport.activateApplication(true); Services.wm.getMostRecentWindow(null).focus
() }) Services.appShell.hiddenDOMWindow.document.getElementById('menu_mac_dockmenu').appendChild(macMenuItem) This adds the "Show Most Recent Window" menuitem from the previous example as a third item. Two types of ...
nsIMicrosummarySet
Introduced Gecko 1.8 Obsolete Gecko 6.0 Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Warning: Microsummary support was removed in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) Method overview void addObserver(in nsIMicrosummaryObserver observer); nsISimpleEnumerator Enumerate
(); void removeObserver(in nsIMicrosummaryObserver observer); Methods addObserver
() Add a microsummary observer to this microsummary set. Adding an observer to a set is the equivalent of adding it to each constituent microsummary. void addObserver( in nsIMicrosummaryObserver observer ); Parameters observer The microsummary observer to add. Enumerate
() Retr...
...void removeObserver( in nsIMicrosummaryObserver observer ); Parameters observer The microsummary observer to remove. ...
...r to a set is the equivalent of adding it to each constituent microsummary. void addObserver( in nsIMicrosummaryObserver observer ); Parameters observer The microsummary observer to add. Enumerate
() Retrieve an nsISimpleEnumerator of microsummaries in the set. nsISimpleEnumerator Enumerate
(); Parameters None. Return value An enumerator of nsIMicrosummary objects. removeObserver
() Remove a microsummary observer from this microsummary. void removeObserver( in nsIMicrosummaryObserver observer ); Parameters observer The microsummary observer to remove. See also nsIMicrosummaryService Microsummary topics Creating a Microsummary ...
nsIMsgFilter
action is not label attribute nsMsgLabelValue label; junkScore attribute long junkScore; strValue attribute AUTF8String strValue; customId // action id if type is Custom attribute ACString customId; customAction // custom action associated with customId // (which must be set prior to reading this attribute) readonly attribute nsIMsgFilterCustomAction customAction; Methods AddTerm
() void nsIMsgFilter::AddTerm ( in nsMsgSearchAttribValue attrib, in nsMsgSearchOpValue op, in nsIMsgSearchValue value, in boolean BooleanAND, in ACString arbitraryHeader ) GetTerm
() void nsIMsgFilter::GetTerm ( in long termIndex, in nsMsgSearchAttribValue attrib, in nsMsgSearchOpValue o...
...in boolean BooleanAND, in ACString arbitraryHeader ) GetTerm
() void nsIMsgFilter::GetTerm ( in long termIndex, in nsMsgSearchAttribValue attrib, in nsMsgSearchOpValue op, in nsIMsgSearchValue value, out boolean BooleanAND, out ACString arbitraryHeader ) appendTerm
() void nsIMsgFilter::appendTerm (in nsIMsgSearchTerm term) createTerm
() nsIMsgSearchTerm nsIMsgFilter::createTerm ( ) MatchHdr
() void nsIMsgFilter::MatchHdr ( in nsIMsgDBHdr msgHdr, in nsIMsgFolder folder, in nsIMsgDatabase db, in string headers, in unsigned long headerSize, out boolean result ) logRuleHit
() void nsIMsgFilter::logRuleHit ( in...
...chTerm nsIMsgFilter::createTerm ( ) MatchHdr
() void nsIMsgFilter::MatchHdr ( in nsIMsgDBHdr msgHdr, in nsIMsgFolder folder, in nsIMsgDatabase db, in string headers, in unsigned long headerSize, out boolean result ) logRuleHit
() void nsIMsgFilter::logRuleHit ( in nsIMsgRuleAction aFilterAction, in nsIMsgDBHdr aHeader ) createAction
() nsIMsgRuleAction nsIMsgFilter::createAction ( ) getActionAt
() nsIMsgRuleAction nsIMsgFilter::getActionAt (in long aIndex) appendAction
() void nsIMsgFilter::appendAction (in nsIMsgRuleAction action ) clearActionList
() void nsIMsgFilter::clearActionList
() getSortedActionList
() void nsIMsgFilter::getSortedActionList (in nsISupportsArray actionList) ...
nsIMsgWindowCommands
ow.idlScriptable This interface defines methods used by the back end to update the user interface in a mail or news message list. Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) The JavaScript implementation of this used by Thunderbird is given here. ...
...erface defines methods used by the back end to update the user interface in a mail or news message list. Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) The JavaScript implementation of this used by Thunderbird is given here. Method overview void selectFolder(in ACString folderUri); void selectMessage(in ACString messageUri); void clearMsgPane
(); Methods selectFolder
() This method is called by the backend to change the folder displayed in the message window. This could be as a result of clicking on a new mail alert, or by clicking a link to a newsgroup. void selectFolder( in ACString folderUri ); Parameters folderUri The URI of the folder to select. selectMessage
() This method is called by the backend to change the displayed message. For instance, when del...
...ewsgroup. void selectFolder( in ACString folderUri ); Parameters folderUri The URI of the folder to select. selectMessage
() This method is called by the backend to change the displayed message. For instance, when deleting attachments, this causes the message to be redisplayed. void selectMessage( in ACString messageUri ); Parameters messageUri The URI of the message to open. clearMsgPane
() This method is called by the backend when it wants to clear the message pane, for instance if you select the group header . void clearMsgPane
(); Paramters None. ...
nsINavHistoryBatchCallback
toolkit/components/places/public/nsINavHistoryService.idlScriptable Please add a summary to this article. ...
...ublic/nsINavHistoryService.idlScriptable Please add a summary to this article. ...
... Please add a summary to this article. ...
nsINavHistoryResult
f the puzzle; they define how the data looks and how the data is interacted with. More specifically, the nsINavHistoryResultViewer interface provides the View component of the pattern, and nsINavHistoryResultViewObserver is the Controller. The result indicates to the view when something changes by using the nsINavHistoryResultViewer interface. Viewers register themselves through the registerViewer
() method. The viewer then tells the actual view object what to do. You can use nsINavHistoryResultTreeViewer as the viewer; this provides a prepackaged interaction with a nsiTreeBoxObject. If you need a different view, you'll need to create your own viewer interface. The viewer provides notifications to the controller when view events occur; this is done using the nsINavHistoryResultViewObserver in...
...s are suppressed. This is used to prevent rapid flickering of changes when performing batch or temporary operations on the result structure. viewer nsINavHistoryResultViewer The viewer for this result. The viewer is responsible for actually updating the view object itself, as well as for handling events on the view. Obsolete since Gecko 2.0 Methods addObserver
() Adds an observer for changes that occur on the result. void addObserver( in nsINavHistoryResultObserver aObserver, in boolean aOwnsWeak ); Parameters aObserver An object that implements the nsINavHistoryResultObserver interface, which will receive notifications of changes on the result. aOwnsWeak If false, the result will keep an owning reference to the observer,...
...result. void addObserver( in nsINavHistoryResultObserver aObserver, in boolean aOwnsWeak ); Parameters aObserver An object that implements the nsINavHistoryResultObserver interface, which will receive notifications of changes on the result. aOwnsWeak If false, the result will keep an owning reference to the observer, which must be removed by calling removeObserver
(). If true, the result will keep a weak reference to the observer, which must implement the nsISupportsWeakReference interface. removeObserver
() Removes an observer that was added by a previous call to addObserver
(). void removeObserver( in nsINavHistoryResultObserver aObserver ); Parameters aObserver The observer to remove. See also nsINavHistoryResultObserver nsINavHistor...
nsIObserverService
See nsIObserver for a JavaScript example. void addObserver( in nsIObserver anObserver, in string aTopic, in boolean ownsWeak ); Parameters anObserver The nsIObserver object which will receive notifications. aTopic The notification topic or subject. ownsWeak If set to false, the nsIObserverService will ...
...e nsIObserver object which will receive notifications. aTopic The notification topic or subject. ownsWeak If set to false, the nsIObserverService will hold a strong reference to anObserver. If set to true and anObserver supports the nsISupportsWeakReference interface, a weak reference will be held. Otherwise an error will be returned. (In most cases, you should use false.) enumerateObservers
() Called to enumerate all observers registered for a particular topic. nsISimpleEnumerator enumerateObservers( in string aTopic ); Parameters aTopic The notification topic or subject. Return value Returns an enumeration of all registered listeners. See nsISimpleEnumerator. notifyObservers
() This method is called to notify all observers for a particular topic. See Example. void notif...
...responds to the source of the notification, but could be defined differently depending on the notification topic and may even be null. aTopic The notification topic. This string-valued key uniquely identifies the notification. This parameter must not be null. someData A notification specific string value. The meaning of this parameter is dependent on the topic. It may be null. removeObserver
() This method is called to unregister an observer for a particular topic. void removeObserver( in nsIObserver anObserver, in string aTopic ); Parameters anObserver The nsIObserver instance to remove. aTopic The notification topic or subject. This string-valued key uniquely identifies the notification. This parameter must not be null. Example This notifies all nsIObservers watching ...
nsIParserUtils
rms (1 << 4) Flag for sanitizer: Drops forms and form controls (excluding <fieldset> and <legend>. SanitizerDropMedia (1 << 5) Flag for sanitizer: Drops <img>, <video>, <audio>, and <source>, and flattens out SVG. SanitizerLogRemovals (1 << 6) Flag for sanitizer: Log messages to the console for everything that gets sanitized. Methods convertToPlainText
() Converts HTML to plain text. AString convertToPlainText( in AString src, in unsigned long flags, in unsigned long wrapCol ); Parameters src The HTML source to parse (C++ callers are allowed but not required to use the same string for the return value.) flags Conversion option flags defined in nsIDocumentEncoder. wrapCol Number of characters per line; 0 for no auto-wrapping. Re...
... unsigned long flags, in unsigned long wrapCol ); Parameters src The HTML source to parse (C++ callers are allowed but not required to use the same string for the return value.) flags Conversion option flags defined in nsIDocumentEncoder. wrapCol Number of characters per line; 0 for no auto-wrapping. Return value The plain text conversion of the HTML specified in src. parseFragment
() Parses markup into a sanitized document fragment. nsIDOMDocumentFragment parseFragment( in AString fragment, in unsigned long flags, in boolean isXML, in nsIURI baseURI, in nsIDOMElement element ); Parameters fragment The input markup. flags Sanitization option flags defined above. isXML true if |fragment| is XML and false if HTML. baseURI The base URL for this fragment. ...
...IURI baseURI, in nsIDOMElement element ); Parameters fragment The input markup. flags Sanitization option flags defined above. isXML true if |fragment| is XML and false if HTML. baseURI The base URL for this fragment. element The context node for the fragment parsing algorithm. Return value An nsIDOMDocumentFragment object for the resulting sanitized document fragment. sanitize
() Parses a string into an HTML document, sanitizes the document, and returns the result serialized to a string. The sanitizer is designed to protect against XSS when sanitized content is inserted into a different-origin context without an iframe-equivalent sandboxing mechanism. By default, the sanitizer doesn't try to avoid leaking information that the content was viewed to third parties. That i...
nsIProperties
void get( in string prop, in nsIIDRef iid, [iid_is(iid),retval] out nsQIResult result ); Parameters prop The property name. iid The desired interface. result The resulting object instance. Exceptions thrown NS_ERROR_FAILURE If the property does not exist. NS_ERROR_NO_INTERFACE If the property exists, but does not support the reque...
...ssociated with a particular name. void get( in string prop, in nsIIDRef iid, [iid_is(iid),retval] out nsQIResult result ); Parameters prop The property name. iid The desired interface. result The resulting object instance. Exceptions thrown NS_ERROR_FAILURE If the property does not exist. NS_ERROR_NO_INTERFACE If the property exists, but does not support the requested interface. getKeys
() Returns an array of property names. nsMemory.h defines the macro NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY, which can be used to free aKeys when it is no longer needed. void getKeys( out PRUint32 count, [array, size_is(count), retval] out string keys ); Parameters count The length of the result array. keys The resulting array of keys. has
() Tests if a property exists. boolean has( in string ...
...e aKeys when it is no longer needed. void getKeys( out PRUint32 count, [array, size_is(count), retval] out string keys ); Parameters count The length of the result array. keys The resulting array of keys. has
() Tests if a property exists. boolean has( in string prop ); Parameters prop The property name. Return value true if the property exists, false if the property does not exist. set
() Sets the XPCOM object associated with a particular name. void set( in string prop, in nsISupports value ); Parameters prop The property name. value The XPCOM object value to associate with prop. undefine
() Undefines a property. void undefine( in string prop ); Parameters prop The property name. Remarks This interface was frozen for Gecko 1.2. See bug 162114 for details. From Gecko 2.0...
nsIRequestObserver
terface is used by various streams (such as nsIChannel ) to indicate the start and end of a request. ...
...Note: An exception thrown from onStopRequest is generally ignored. void onStopRequest( in nsIRequest aRequest, in nsISupports aContext, in nsresult aStatusCode ); Parameters aRequest Request being observed. ...
...Note: An exception thrown from onStopRequest is generally ignored. ...
nsIScriptableUnescapeHTML
nsIDOMDocumentFragment parseFragment( in AString fragment, in PRBool isXML, in nsIURI baseURI, in nsIDOMElement element ); Parameters ...
...ragment parseFragment(in AString fragment, in PRBool isXML, in nsIURI baseURI, in nsIDOMElement element); AString unescape(in AString src); Methods parseFragment
() Parses a string of HTML or XML source into a sanitized DocumentFragment. This is equivalent to calling nsIParserUtils::parseFragment(fragment, 0, isXML, baseURI, element). You should call nsIParserUtils::parseFragment
() instead of calling this method. nsIDOMDocumentFragment parseFragment( in AString fragment, in PRBool isXML, in nsIURI baseURI, in nsIDOMElement element ); Parameters fragment A string of HTML or XML source to parse as a fragment. isXML Set this to true if the fragment is an XML string; otherwise set it to false. baseURI Pointer to the base URI against which to resolve any URIs ...
...se URI against which to resolve any URIs included in the fragment. This parameter is ignored if isXML is false. element The nsIDOMElement to be used as the context node for the purposes of the fragment parsing algorithm. Return value An nsIDOMDocumentFragment of the element with the new text appended. Exceptions thrown NS_ERROR_FAILURE Unable to append the text to the element. unescape
() Convents HTML source into plain text. This is equivalent to calling nsIParserUtils::convertToPlainText(src, nsIDocumentEncoder::OutputSelectionOnly | nsIDocumentEncoder::OutputAbsoluteLinks, 0). You should call nsIParserUtils::convertToPlainText
() instead of calling this method. AString unescape( in AString src ); Parameters src The HTML string to convert into plain text. Return valu...
nsISearchEngine
lue Description TYPE_MOZSEARCH 1 TYPE_SHERLOCK 2 TYPE_OPENSEARCH 3 Search engine data type constants Constant Value Description DATA_XML 1 Data type is XML DATA_TEXT 2 Data type is Text. Methods addParam
() Adds a parameter to the search engine's submission data. This should only be called on engines created via nsIBrowserSearchService.addEngineWithDetails
(). void addParam( in AString name, in AString value, in AString responseType ); Parameters name The name of the parameter to add. value The value to pass. If value is "{searchTerms}", it will be substituted with...
...bmission. Must not be null. responseType Since an engine can have several different request URLs, differentiated by response types, this parameter selects a request to add parameters to. If null, will default to "text/html" Exceptions thrown NS_ERROR_INVALID_ARG If name or value are null. NS_ERROR_FAILURE If the search engine is read-only. getSubmission
() Gets a nsISearchSubmission object that contains information about what to send to the search engine, including the URI and postData, if applicable. nsISearchSubmission getSubmission( in AString data, [optional] in AString responseType, [optional] in AString purpose ); Parameters data Data to add to the submission object. That is the search terms. responseType [...
...ssion. If null, will default to "text/html". purpose [optional] A string meant to indicate the context of the search request. This allows the search service to provide a different nsISearchSubmission depending on e.g. where the search is triggered in the UI. Possible values depend on the application's installed search engines. Return value An nsISearchSubmission supportsResponseType
() Determines whether the engine can return responses in the given MIME type. boolean supportsResponseType( in AString responseType ); Parameters responseType The MIME type to check for. Return value Returns true if the engine spec has a URL with the given responseType, false otherwise. See also nsISearchSubmission nsIBrowserSearchService ...
nsIServerSocketListener
netwerk/base/public/nsIServerSocket.idlScriptable This interface is notified whenever a server socket accepts a new connection. The transport is in the connected state, and read/write streams can be opened using the normal nsITransport API. ...
... netwerk/base/public/nsIServerSocket.idlScriptable This interface is notified whenever a server socket accepts a new connection. The transport is in the connected state, and read/write streams can be opened using the normal nsITransport API. ...
....GetHost
(), which returns a string representation of the client's IP address, which may be either an IPv4 or an IPv6 address. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void onSocketAccepted(in nsIServerSocket aServ, in nsISocketTransport aTransport); void onStopListening(in nsIServerSocket aServ, in nsresult aStatus); Methods onSocketAccepted
() This method is called when a client connection is accepted. void onSocketAccepted( in nsIServerSocket aServ, in nsISocketTransport aTransport ); Parameters aServ The server socket. aTransport The connected socket transport. onStopListening
() This method is called when the listening socket stops for some reason. The server socket is effectively dead after this notification. ...
nsISmsService
ervice;1"] .createInstance(Components.interfaces.nsISmsService); Method overview [implicit_jscontext] nsIDOMMozSmsMessage createSmsMessage(in long id, in DOMString delivery, in DOMString sender, in DOMString receiver, in DOMString body, in jsval timestamp, in bool read ); unsigned short getNumberOfMessagesForText(in DOMString text); boolean hasSupport
(); void send(in DOMString number, in DOMString message, in long requestId, [optional] in unsigned long long processId); Methods createSmsMessage
() [implicit_jscontext] nsIDOMMozSmsMessage createSmsMessage( in long id, in DOMString delivery, in DOMString sender, in DOMString receiver, in DOMString body, in jsval timestamp, in bool read ); Parameters id A number ...
...t" and is representing the way the SMS was delivered. sender A DOMString with the name of the sender. receiver A DOMString with the name of the receiver. body A DOMString with the text of the message. timestamp A Date object with the timestamp of the message. read A Boolean indicating whether a message is marked as read or unread. ...
...ect with the timestamp of the message. read A Boolean indicating whether a message is marked as read or unread. Return value A SmsMessage getNumberOfMessagesForText
() unsigned short getNumberOfMessagesForText( in DOMString text ); Parameters text A DOMString text to check. Return value The number of multi-part SMS needed for a given text (160 characters for one SMS). hasSupport
() Checks if the current platform has SMS support. boolean hasSupport
(); Return value Boolean. send
() void send( in DOMString number, in DOMString message, in long requestId, in unsigned long long processId Optional ); Parameters number A DOMString with a telephone number to send to. message A DOMString with the text message. requestId Missing Description processId Optional...
nsIStringEnumerator
xpcom/ds/nsIStringEnumerator.idlScriptable Please add a summary to this article. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview AString getNext
(); boolean hasMore
(); Methods getNext
() Called to retrieve the next string in the enumerator. The "next" element is the first string upon the first call. Must be preceded by a call to hasMoreElements
() which returns PR_TRUE. This method is generally called within a loop to iterate over the strings in the enumerator. AString getNext
(); Parameters None. Return value The next string in the enumerator. Throws an exception if there are no more strings. hasMore
() Called to determine whether or not the enumerator has any strings that can be returned via getNext
(). This method is generally used to determine whet...
...Return value True if there are remaining strings in the enumerator. False if there are no more strings in the enumerator. ...
...Return value True if there are remaining strings in the enumerator. ...
nsIStyleSheetService
A user sheet loaded via this API will come before userContent.css and userChrome.css in the cascade (so the rules in it will have lower precedence than rules in those sheets). An agent sheet loaded via this API will come after ua.css in the cascade (so the rules in it will have higher precedence...
...lative ordering of two user or two agent sheets loaded via this API is undefined. Sheets added via this API take effect on all documents, including already-loaded ones, immediately. void loadAndRegisterSheet( in nsIURI sheetURI, in unsigned long type ); Parameters sheetURI URI of the stylesheet to load and register. type One of the type constants. ...
...The removal takes effect immediately, even for already-loaded documents. void unregisterSheet( in nsIURI sheetURI, in unsigned long type ); Parameters sheetURI URI of the stylesheet to unregister. type One of the type constants. ...
nsISyncJPAKE
This will compute the key and expand the key to two keys, an AES256 encryption key and a 256 bit HMAC key. It returns a key confirmation value (SHA256d of the key) and the encryption and HMAC keys. void final( in ACString aB, in ACString aGVB, in ACString aRB, in ACString aHkdfInfo, out ACString aAES256Key, out ACString aHMAC256Key ); Par...
...String aHMAC256Key ); Parameters aB Schnorr signature value B, in hex representation. aGVB Schnorr signature value g^vb (vb is a random value), in hex representation. aRB Schnorr signature value rb = vb - xb * h, in hex representation. aHkdfInfo Missing Description aAES256Key The AES 256 encryption key, in base64 representation. aHMAC256Key The 256 bit HMAC key, in base64 representation. round1
() Perform first round of the JPAKE exchange. void round1( in ACString aSignerID, out ACString aGX1, out ACString aGV1, out ACString aR1, out ACString aGX2, out ACString aGV2, out ACString aR2 ); Parameters aSignerID String identifying the signer. aGX1 Schnorr signature value g^x1, in hex representation. aGV1 Schnorr signature value g^v1 (v1 is a random value), in hex representation.
...value g^x1, in hex representation. aGV1 Schnorr signature value g^v1 (v1 is a random value), in hex representation. aR1 Schnorr signature value r1 = v1 - x1 * h, in hex representation. aGX2 Schnorr signature value g^x2, in hex representation. aGV2 Schnorr signature value g^v2 (v2 is a random value), in hex representation. aR2 Schnorr signature value r2 = v2 - x2 * h, in hex representation. round2
() Perform second round of the JPAKE exchange. void round2( in ACString aPeerID, in ACString aPIN, in ACString aGX3, in ACString aGV3, in ACString aR3, in ACString aGX4, in ACString aGV4, in ACString aR4, out ACString aA, out ACString aGVA, out ACString aRA ); Parameters aPeerID String identifying the peer. aPIN String containing the weak secret (PIN). aGX3 Schnorr signature ...
nsISyncMessageSender
ageManager.idl Inherits from: nsIMessageListenerManager Message "senders" have a single "other side" to which messages are sent. For example, a child-process message manager will send messages that are only delivered to its one parent-process message manager. See Message Manager interfaces for more details on the distinction between message senders and message broadcasters. Both sendSyncMessage
() and sendRpcMessage
() will block until a reply is received, but they may be temporarily interrupted to process an urgent incoming message (such as a CPOW request). Methods jsval sendSyncMessage([optional] in AString messageName, [optional] in jsval obj, [optional] in jsval objects, [optional] in nsIPrincipal pri...
...ptional] in jsval obj, [optional] in jsval objects, [optional] in nsIPrincipal principal); jsval sendRpcMessage([optional] in AString messageName, [optional] in jsval obj, [optional] in jsval objects, [optional] in nsIPrincipal principal); sendSyncMessage
() Like sendAsyncMessage
(), except blocks the sender until all listeners of the message have been invoked. Returns an array containing return values from each listener invoked. Send messageName and obj to the "other side" of this message manager. This invokes listeners who registered for messageName using a nsIMessageListenerManager. See nsIMessageListener::receiveMessage
() for the format of the...
...es the objects property of the received message, with each original object replaced with a cross process object wrapper for it. principal nsIPrincipal Returns Array: an array of structured clones of the objects returned by all the listeners to this message, one element for each listener. If there was only one listener, it is an array with a single element. sendRpcMessage
() Like sendSyncMessage
(), except re-entrant. New RPC messages may be issued even if, earlier on the call stack, we are waiting for a reply to an earlier sendRpcMessage
() call. Parameters Name Type Description messageName String The name of the message. Optional. This becomes the name property of the received message. obj JSONable object. ...
nsITextInputProcessorCallback
IME from Gecko. This interface has a "function" attribute. Therefore, JS-IME can implement this as a function. ...
...ment this as a function. ...
...zilla.org/text-input-processor;1"]. createInstance(Components.interfaces.nsITextInputProcessor); } if (!this._TIP.beginInputTransaction(window, this._callback)) { return false; } ... }, } Method overview boolean onNotify(in nsITextInputProcessor aTextInputProcessor, in nsITextInputProcessorNotification aNotification); Methods onNotify
() This is called when Gecko requests or notifies something to IME. boolean onNotify(in nsITextInputProcessor aTextInputProcessor, in nsITextInputProcessorNotification aNotification); Parameters aTextInputProcessor The instance which receives the notification. If the handler needs to do something with composition, you can use this. aNotification A notification or request. ...
nsITransport
ants Open flags. Constant Value Description OPEN_BLOCKING 1<<0 Open flags. OPEN_UNBUFFERED 1<<1 Generic nsITransportEventSink status codes. nsITransport implementations may override these status codes with their own more specific status codes (for example, see nsISocketTransport). Constant Value Description STATUS_READING 0x804b0008 STATUS_WRITING 0x804b0009 Methods close
() Close the transport and any open streams. void close( in nsresult aReason ); Parameters aReason The reason for closing the stream. openInputStream
() Open an input stream on this transport. nsIInputStream openInputStream( in unsigned long aFlags, in unsigned long aSegmentSize, in unsigned long aSegmentCount ); Parameters aFlags Optional transport specific flags. Flags have the followi...
...ts. ReadSegments is only guaranteed to be implemented when this flag is NOT specified. aSegmentSize If OPEN_UNBUFFERED is not set, then this parameter specifies the size of each buffer segment (pass 0 to use default value). aSegmentCount If OPEN_UNBUFFERED is not set, then this parameter specifies the maximum number of buffer segments (pass 0 to use default value). Return value openOutputStream
() Open an output stream on this transport. nsIOutputStream openOutputStream( in unsigned long aFlags, in unsigned long aSegmentSize, in unsigned long aSegmentCount ); Parameters aFlags Optional transport specific flags. Flags have the following meaning: OPEN_BLOCKING If specified, then the resulting stream will have blocking stream semantics. This means that if the stream is full and is not...
...ments and WriteFrom are only guaranteed to be implemented when this flag is NOT specified. aSegmentSize If OPEN_UNBUFFERED is not set, then this parameter specifies the size of each buffer segment (pass 0 to use default value). aSegmentCount If OPEN_UNBUFFERED is not set, then this parameter specifies the maximum number of buffer segments (pass 0 to use default value). Return value setEventSink
() Set the transport event sink. void setEventSink( in nsITransportEventSink aSink, in nsIEventTarget aEventTarget ); Parameters aSink Receives transport layer notifications. aEventTarget Indicates the event target to which the notifications should be delivered. If null, then the notifications may occur on any thread. ...
nsIURL
ectory/fileBaseName.fileExtension;param \ \ / \ ----------------------- \ | / \ fileName / ---------------------------- | filePath You can get a nsIURL from an nsIURI, using the QueryInterface
() method: var myURI = Components.classes["@mozilla.org/network/io-service;1"] .getService(Components.interfaces.nsIIOService) .newURI("http://developer.mozilla.org", null, null); try { var myURL = myURI.QueryInterface(Components.interfaces.nsIURL); } catch(e) { // the URI is not an URL } Or using instanceof: if (myURI instanceof Components.interfaces...
...not have been specially handled. query AUTF8String Query portion (the part after the "?") of the URL. If there isn't one, an empty string is returned. Some characters may be escaped. ref AUTF8String Reference portion (the part after the "#") of the URL. If there isn't one, an empty string is returned. Some characters may be escaped. Methods getCommonBaseSpec
() This method takes a uri and compares the two. The common uri portion is returned as a string. The minimum common uri portion is the protocol, and any of these if present: login, password, host and port If no commonality is found, "" is returned. If they are identical, the whole path with file/ref/etc. is returned. For file uris, it is expected that the common spec would be at least "file:///" sin...
...If no commonality is found, the entire uri spec is returned. If they are identical, "" is returned. Filename, query, and so forth are always returned except when uris are identical. AUTF8String getRelativeSpec( in nsIURI aURIToCompare ); Parameters aURIToCompare A URI to compare wi...
nsIUTF8StringEnumerator
xpcom/ds/nsIStringEnumerator.idlScriptable An object can implement this interface to allow a client to iterate over a set of strings provided by the object. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview AUTF8String getNext
(); boolean hasMore
(); Methods getNext
() Returns the next string in the enumerator. The "next" element is the first string upon the first call. Must be preceded by a call to hasMore
(), which returns PR_TRUE. ...
...Supports Last changed in Gecko 1.7 Method overview AUTF8String getNext
(); boolean hasMore
(); Methods getNext
() Returns the next string in the enumerator. The "next" element is the first string upon the first call. Must be preceded by a call to hasMore
(), which returns PR_TRUE. This method is generally called within a loop to iterate over the strings in the enumerator. AUTF8String getNext
(); Parameters None. Return value The next string in the enumerator. Throws an exception if there are no more strings. hasMore
() Reports whether or not the enumerator has any strings that can be returned via getNext
(). This method is generally used to determine whether or not to initiate or continue iteration over the enumerator, athough it can be called without subsequent getNext
() calls. Calling ...
...ception if there are no more strings. hasMore
() Reports whether or not the enumerator has any strings that can be returned via getNext
(). This method is generally used to determine whether or not to initiate or continue iteration over the enumerator, athough it can be called without subsequent getNext
() calls. Calling this method doesn't affect the internal state of the enumerator. boolean hasMore
(); Parameters None. Return value true if there are remaining strings in the enumerator, otherwise false. ...
nsIUpdateCheckListener
void onCheckComplete( in nsIXMLHttpRequest request, [array, size_is(updateCount)] in nsIUpdate updates, in unsigned long updateCount ); Parameters request The nsIXMLHttpRequest object handling the update check. updates An array of nsIUpdate objects describing the available updates. updateCount The number of updates in the updates array. onError(...
...) Called when the update check is completed. void onCheckComplete( in nsIXMLHttpRequest request, [array, size_is(updateCount)] in nsIUpdate updates, in unsigned long updateCount ); Parameters request The nsIXMLHttpRequest object handling the update check. updates An array of nsIUpdate objects describing the available updates. updateCount The number of updates in the updates array. ...
...void onProgress( in nsIXMLHttpRequest request, in unsigned long position, in unsigned long totalSize ); Parameters request The nsIXMLHttpRequest object handling the update check. position The number of bytes downloaded so far. ...
nsIUpdateChecker
ware updates. ...
...x 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method overview void checkForUpdates(in nsIUpdateCheckListener listener, in boolean force); void stopChecking(in unsigned short duration); Constants Constant Value Description CURRENT_CHECK 1 Constant for the stopChecking
() method indicating that only the current update check should be stopped. CURRENT_SESSION 2 Constant for the stopChecking
() method indicating that all update checks during the current session should be stopped. ANY_CHECKS 3 Constant for the stopChecking
() method indicating that all update checking should be stopped. This disables the update checking preferences. Methods checkForUpdates
() Checks for available updates, notifying a listener of the results. void checkForUpdates( in nsIUpdateCheckListener listener, ...
...kListener to be notified of the results of an update check. force If true, the update checker checks for updates, regardless of the current value of the user's update settings. This is used by any user interface that offers the user the opportunity to check for updates immediately. The force option doesn't work if the system administrator has locked the app.update.enabled preference. stopChecking
() Ends any pending update check. void stopChecking( in unsigned short duration ); Parameters duration One of the constants indicating the set of updates to stop. See also nsIUpdatePatch nsIUpdate nsIUpdateCheckListener nsIApplicationUpdateService nsIUpdateManager nsIUpdatePrompt nsIUpdateTimerManager ...
nsIUpdateTimerManager
, or even months). These timers are used to schedule update checks in the future, for example. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method overview void registerTimer(in AString id, in nsITimerCallback callback, in unsigned long interval); Methods registerTimer
() Presents a user interface that checks for and displays the available updates. void registerTimer( in AString id, in nsITimerCallback callback, in unsigned long interval ); Parameters id An ID used to identify the timer interval; used for persistence. callback An nsITimerCallback object that is notified when the interval expires. interval The lengt...
...tify the timer interval; used for persistence. callback An nsITimerCallback object that is notified when the interval expires. interval The length of time, in seconds, until the timer should fire. Remarks Note that the timer is not precise, and that the default minimum interval is 2 minutes. ...
...nent; instead, the component is instantiated when the timer is triggered. The values are: contractID The component's contract ID. method The method used to instantiate the interface; this should be either getService or createInstance, depending on your component. id The ID that identifies the interval; this is the same ID you would pass into registerTimer
(). preference The preference for the timer interval; this allows a preference to override the default interval. This can be an empty string if the default interval should not be overridden. interval The same interval that would be passed into registerTimer
(). See also nsIUpdate nsIUpdateCheckListener nsIUpdateChecker nsIUpdatePatch nsIApplicationUpdateService...
nsIWebBrowser
indow interface. The chrome object must also implement nsIEmbeddingSiteWindow. The chrome may optionally implement nsIInterfaceRequestor, nsIWebBrowserChromeFocus, nsIContextMenuListener and nsITooltipListener to receive additional notifications from the browser object. The chrome object may optionally implement nsIWebProgressListener instead of explicitly calling addWebBrowserListener
() and removeWebBrowserListener
() to register a progress listener object. If the implementation does this, it must also implement nsIWeakReference. Note: The implementation should not refcount the supplied chrome object; it should assume that a non nsnull value is always valid. The embedder must explicitly set this value back to nsnull if the chrome object is destroyed before the browser object.
...ements nsISupportsWeakReference, the implementation should get the nsIWeakReference and hold that. Otherwise, the implementation should not refcount this interface; it should assume that a non null value is always valid. In that case, the embedder should explicitly set this value back to null if the parent content listener is destroyed before the browser object. Methods addWebBrowserListener
() Registers a listener of the type specified by the iid to receive callbacks. The browser stores a weak reference to the listener to avoid any circular dependencies. Typically this method will be called to register an object to receive nsIWebProgressListener or nsISHistoryListener notifications in which case the the IID is that of the interface. void addWebBrowserListener( in nsIWeakReference aLi...
...ce aListener, in nsIIDRef aIID ); Parameters aListener The listener to be added. aIID The IID of the interface that will be called on the listener as appropriate. Return value NS_OK Listener was successfully added. NS_ERROR_INVALID_ARG One of the arguments was invalid or the object did not implement the interface specified by the IID. removeWebBrowserListener
() Removes a previously registered listener. void removeWebBrowserListener( in nsIWeakReference aListener, in nsIIDRef aIID ); Parameters aListener The listener to be removed. aIID The IID of the interface on the listener that will no longer be called. Return value NS_OK Listener was successfully added. NS_ERROR_INVALID_ARG One of the arguments was invalid or ...
nsIWebNavigationInfo
avigationInfo = Components.classes["@mozilla.org/webnavigation-info;1"] .getService(Components.interfaces.nsIWebNavigationInfo); Method overview unsigned long isTypeSupported(in ACString aType, in nsIWebNavigation aWebNav); Constants Support type constants Constant Value Description UNSUPPORTED 0 Returned by isTypeSupported
() to indicate lack of support for a type. Note: This is guaranteed not to change, so that boolean tests can be done on the return value if isTypeSupported to detect whether a type is supported at all. IMAGE 1 Returned by isTypeSupported
() to indicate that a type is supported as an image. PLUGIN 2 Returned by isTypeSupported
() to indicate that a type is supported vi...
...This lets you determine whether a MIME type can be displayed as-is inside a browser, or if the browser will instead forward handling of the data to a plug-in or an external helper application. ...
...This lets you determine whether a MIME type can be displayed as-is inside a browser, or if the browser will instead forward handling of the data to a plug-in or an external helper application. ...
nsIWebSocketChannel
h no close frame being sent) when a status code is expected. 1007-1999 Reserved for future use by the WebSocket standard. 2000-2999 Reserved for use by WebSocket extensions. 3000-3999 Available for use by libraries and frameworks. May not be used by applications. 4000-4999 Available for use by applications. Methods asyncOpen
() Asynchronously opens the WebSocket connection. Received messages are fed to the socket listener as they arrive. The socket listener's methods are called on the thread that calls asyncOpen
() and are not called until after asyncOpen
() returns. If asyncOpen
() returns successfully, the protocol implementation promises to call at least onStart and onStop of the listener. Note: Implementations should t...
...d. void asyncOpen( in nsIURI aURI, in ACString aOrigin, in nsIWebSocketListener aListener, in nsISupports aContext ); Parameters aURI The uri of the websocket protocol; this may be redirected. aOrigin The URI of the originating resource. aListener The nsIWebSocketListener implementation. aContext An opaque parameter forwarded to aListener's methods. close
() void close( in unsigned short aCode, in AUTF8String aReason ); Parameters aCode The status of the connection when closed; see Status codes for possible values. aReason A human-readable string describing the reason the connection closed. sendBinaryMsg
() Sends a binary message to the WebSocket peer. void sendBinaryMsg( in ACString aMsg ); Parameters aMsg The data ...
... unsigned short aCode, in AUTF8String aReason ); Parameters aCode The status of the connection when closed; see Status codes for possible values. aReason A human-readable string describing the reason the connection closed. sendBinaryMsg
() Sends a binary message to the WebSocket peer. void sendBinaryMsg( in ACString aMsg ); Parameters aMsg The data to send. sendMsg
() Sends a text message to the WebSocket peer. void sendMsg( in AUTF8String aMsg ); Parameters aMsg The UTF-8 string to send. See also WebSockets WebSocket ...
nsIXPCException
ception objects are the preferred types of exceptions when implementing xpcom interfaces in JavaScript. ...
...Return value Native code only!stowJSVal void stowJSVal( in xpcexJSContextPtr cx, in xpcexJSV...
...Return value Native code only!stowJSVal void stowJSVal( in xpcexJSContextPtr cx, in xpcexJSVal val ); Parameters cx val Remarks Components.Exception is a JavaScript constructor to create nsIXPCException objects. ...
nsIXULBrowserWindow
available to C++ code. See the documentation for XULBrowserWindow for details. Method overview AString onBeforeLinkTraversal(in AString originalTarget, in nsIURI linkURI, in nsIDOMNode linkNode, in PRBool isAppTab); void setJSDefaultStatus(in AString status); void setJSStatus(in AString status); void setOverLink(in AString link, in nsIDOMElement element); Methods onBeforeLinkTraversal
() Called before traversing a link to determine the appropriate target into which to load the link. This may be used, for example, to redirect links into new tabs or windows when it's not desirable to replace the content in the current tab (such as when the link is clicked in an app tab). AString onBeforeLinkTraversal( in AString originalTarget, in nsIURI linkURI, in nsIDOMNode linkNode, in ...
...in nsIDOMNode linkNode, in PRBool isAppTab ); Parameters originalTarget The specified target for the link. linkURI The URI of the link that is about to be traversed. linkNode The nsIDOMNode representing the DOM node in which the link is located. isAppTab Whether or not the link being clicked is in an app tab. Return value A string indicating the revised target for the link. ...
...nsIDOMNode representing the DOM node in which the link is located. isAppTab Whether or not the link being clicked is in an app tab. Return value A string indicating the revised target for the link. setJSDefaultStatus
() Sets the default status according to JavaScript's version of the default status. void setJSDefaultStatus( in AString status ); Parameters status The status string. setJSStatus
() Sets the status according to JavaScript's version of the status. void setJSStatus( in AString status ); Parameters status The status string. setOverLink
() Tells the object implementing this function what link we are currently over. void setOverLink( in AString link, in nsIDOMElement element ); Parameters link The link string. element The currently targeted link element. ...
nsIZipReaderCache
If the zip reader for the given fil...
...Otherwise the previously created nsIZipReader is returned. ...
...zip. nsIZipReader getInnerZip( in nsIFile zipFile, in AUTF8String zipEntry ); Parameters zipFile The zip file. zipEntry The zip entry. Return value The nsIZipReader for the given zip file. getZip
() Returns a (possibly shared) cached nsIZipReader for a zip file. If the zip reader for the given file is not in the cache, a new nsIZipReader is opened (see nsIZipReader.open
()). Otherwise the previously created nsIZipReader is returned. Note: If nsIZipReader.close has been called on the shared nsIZipReader, this method will return the closed nsIZipReader nsIZipReader getZip( in nsIFile zipFile ); Parameters zipFile The zip file. Return value The nsIZipReader for the given zip file. init
() Initializes a new zip reader cache. void init( in unsigned long ca...
nsPIPromptService
embedding/components/windowwatcher/public/nsPIPromptService.idlScriptable This interface is for the dialog implementers, not for other developers. Inherits from: nsISupports Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Implemented by: The contract ID isn't defined. This interface defines the meaning of each indexes of GetInt
(), SetInt
(), GetString
() and SetString
() of the nsIDialogParamBlock interface but they are defined on in C++. The indexes for GetString
() and SetString
() are: eMsg The value is 0. This is the message text of the dialog. eCheckboxMsg The value is 1. This is the label text of a checkbox on the dialog. eIconClass The value is 2. This is the class attribute value of the icon image. eTitleMessage The value is 3. This is the heading...
...eButton2Text The value is 10. This is the label of the third button on the dialog. eButton3Text The value is 11. This is the label of the forth button on the dialog. eDialogTitle The value is 12. This is the title of the dialog. eOpeningSound Obsolete since Gecko 1.9.2 The value is 13. This is the system sound name which should be played when the dialog is shown. See also nsISound.playSystemSound
(). This is obsolete on Gecko 1.9.2 and later. You should use eSoundEventId instead. The indexes for GetInt
() and SetInt
() are: eButtonPressed The value is 0. This is used for the result of the dialog. The pressed button number will be returned. eCheckboxState The value is 1. This is the default checkbox state and the result of it. eNumberButtons The value is 2. This is the number of the visible b...
...ssword field. eDefaultButton The value is 5. This is the button number which should be the default button on the dialog. eDelayButtonEnable The value is 6. If this is not 0, the all buttons are disabled when the dialog is shown. And they will be enabled later. eSoundEventId The value is 7. This is the sound event ID which should be played when the dialog is shown. See also nsISound.playEventSound
(). Method overview void doDialog(in nsIDOMWindow aParent, in nsIDialogParamBlock aParamBlock, in string aChromeURL); Methods doDialog
() Opens a dialog. void doDialog( in nsIDOMWindow aParent, in nsIDialogParamBlock aParamBlock, in string aChromeURL ); Parameters aParent The parent window of the dialog. aParamBlock Various parameters for the dialog. aChromeURL The URL of the dialog im...
Frequently Asked Questions
ives from a given interface, when you forgetting to also specify the interface name in the NS_IMPL_ISUPPORTS / NS_IMPL_THREADSAFE_ISUPPORTS macro. For example, the assertion occurs when you convert the pointer to the object to a raw pointer to that interface, then assign the raw pointer to another nsCOMPtr for that interface. NS_PRECONDITION "You can't dereference a NULL nsCOMPtr with operator->
()" NS_PRECONDITION "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 befor...
...| 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->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...
...eter? call a getter that fills in an nsIFoo*& parameter? call a getter that doesn't AddRef its result? Any XPCOM function that returns an interface pointer, i.e., a `getter', must have already AddRefed that pointer. If it didn't, you should probably report it as a bug. No matter which code pattern you use to solve this problem, you should comment it, e.g., // Warning: this getter doesn't AddRef
() its result. If the getter returns the new pointer as its function result, no worries, General Does nsCOMPtr bloat the code? Are nsCOMPtrs fast? Can I use them in tight loops? Bibliography Web Resources nsCOMPtr.h, and nsCOMPtr.cpp are the source to nsCOMPtr. You can examine the source to nsCOMPtr online using (the wonderful) LXR. Exploring this code is not an adventure for the faint of he...
Using the clipboard
in // a browser window where it's already loaded. Components.utils.import('resource://gre/modules/Services.jsm'); // Create a constructor for the built-in supports-string class. ...
... if (source instanceof Ci.nsIDOMWindow) // Note: in Gecko versions >16, you can import the PrivateBrowsingUtils.jsm module // and use PrivateBrowsingUtils.privacyContextFromWindow(sourceWindow) instead source = source.QueryInterface(Ci.nsIInterfaceRe...
...s object will not be placed on the clipboard. Otherwise, use a one from a logical source window instead (see the description above). Tell the transferring object about the flavor of data you want to get. Retrieve the data from the clipboard and put it in the transferable. Get the data from the transferring object. The first steps are similar to that used for copying: var trans = Transferable
(); trans.addDataFlavor("text/unicode"); Recall that Transferable
() is a function from the boilerplate in the previous section. Instead, you can create a Ci.nsITransferable instance. The boilerplate may be a better method, but this method works as well. var trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable); trans.init(null) trans.addDataFlavor("text/unicode"); ...
XPCOM
acy add-ons--like extensions and themes--that were created prior to Firefox 1.5. Add-ons can (and should) be identified with IDs of the form extensionname@organization.tld since Firefox 1.5.Generic factoryMost XPCOM factories can be very simple. Rick Potts wrote a templated-based generic factory (nsFactory<t>) that simplifies the factory creation process that just requires writing a CreateInstance
() method. The new nsIGenericFactory interface takes this a step further, by providing a single interface that can be reused anytime a simple implementation of nsIFactory is needed. Here is the interface, and a description of its use.</t>How to build a binary XPCOM component using Visual StudioThis is a simple tutorial for building XPCOM objects in C++ using Visual Studio. XPCOM is Mozilla's cross p...
... another experienced nsCOMPtr user, or find the answer by experimentation.Using nsIClassInfoIf you use a C++ class which implements nsIClassInfo from JavaScript, then you don't have to explicitly call QueryInterface on the JavaScript object to access the object's interfaces.Using nsIDirectoryServicensDirectoryService implements the nsIProperties interface. This implementation will allow you to Get
(), Set
(), Define
(), and Undefine
() nsIFile.Using nsIPasswordManagerTechnical review completed.Using nsISimpleEnumeratorUsing the clipboardThis section provides information about cutting, copying, and pasting to and from the clipboard.Using the Gecko SDKWeak referenceIn XPCOM, a weak reference is a special object that contains a pointer to an XPCOM object, but doesnot keep that object alive. If the ...
...ed to XPCOM development in general, and specifically the needs of Mozilla. Like the standard libraries, XPCOM must be a fairly self-contained library, so as not to encumber clients with any unnecessary external dependencies.XPCOM Thread SynchronizationXPCOM thread synchronization primitives have the same semantics as those in NSPR, and each method of these synchronization objects (e.g. Mutex::Lock
()) has a matching function in NSPR (PR_Lock
()). This is no accident, as mozilla:: primitives are merely bare-minimum wrappers around NSPR's.xptcall FAQxptcall is a small low level XPCOM method call library. It is implemented using platform specific C/C++ and assembly language code. It is used to facilitate cross language and cross thread method calls. Porting this code is required in order to make ...
Gloda examples
n Thunderbird 3 This page provides some examples for using gloda. See Creating a gloda message query for more examples. ...
...of all tags defined in TB let query = Gloda.newQuery(Gloda.NOUN_MESSAGE); let tagArray = MailServices.tags.getAllTags({}); query.tags(...tagArray); let collection = query.getCollection(myListener); Search messages by dateRange Searches for all messages within a date range id_q=Gloda.newQuery(Gloda.NOUN_MESSAGE); // Define a date range form yesterday to now id_q.dateRange([new Date
() - 86400000, new Date
()]); var myListener = { /* called when new items are returned by the database query or freshly indexed */ onItemsAdded: function _onItemsAdded(aItems, aCollection) { }, /* called when items that are already in our collection get re-indexed */ onItemsModified: function _onItemsModified(aItems, aCollection) { }, /* called when items that are in our c...
...he system */ onItemsRemoved: function _onItemsRemoved(aItems, aCollection) { }, /* called when our database query completes */ onQueryCompleted: function _onQueryCompleted(msg_coll) { try { while(msg = msg_coll.items.pop
()) { //do something with the messages here alert(msg.subject); } } catch (e) {} } }); } }); ...
Mail composition back end
rogress and completion of the copy operation. nsIMsgSendListener The following describes the methods of the nsIMsgSendListener interface: OnStartSending The OnStartSending interface is called when the sending operation has begun. This is called after messages creation has completed. If message creation fails, the nsIMsgSend operation will return an NS_FAILED
() return code. NS_IMETHOD OnStartSending(const char *aMsgID, - the message ID for the message being sent PRUint32 aMsgSize) = 0; - the total message size for the message being sent OnProgress The OnProgress interface is called with progress notification on the send operation. NS_IMETHOD OnProgress(const char *aMsgID, - the message ID for the m...
...y Operations There are various copy operations that can result as a part of message creation and delivery. These are all controlled by the caller in various way. The following details the specific copy operations that can occur in a message send call. Copy to Sent Folder Copying to the "Sent" folder is controlled by a setting in the nsIMsgCompFields interface. The SetFcc
() and GetFcc
() methods are used by the caller to control if a message should be copied to the defined "Sent" folder if the sending operation was successful. Currently, this pref is a "char *" which is the specific name of the folder, but this will more than likely change to a PRBool (boolean) preference. The determiniation of which folder is the "Sent" folder for the user is done by a call to GetFo...
... methods are used by the caller to control if a message should be copied to the defined "Sent" folder if the sending operation was successful. Currently, this pref is a "char *" which is the specific name of the folder, but this will more than likely change to a PRBool (boolean) preference. The determiniation of which folder is the "Sent" folder for the user is done by a call to GetFoldersWithFlag
() and the message store will control this user defined preference. If the setting for GetFcc
() is set to true, the copy operation is automatically performed after a successful send operation. Drafts Saving a message as a draft is controlled by the "nsMsgDeliverMode mode" argument of the CreateAndSendMessage and SendMessageFile methods. If the caller passes in nsMsgSaveAsDraft, ...
Access Window
the window object, such as accessing the height or width of the window/tab or setting its title, registering timer events and much more. The Window API will give you the complete details. Since window is a global variable you can use it directly from your JavaScript file. ...
...sing the height or width of the window/tab or setting its title, registering timer events and much more. The Window API will give you the complete details. Since window is a global variable you can use it directly from your JavaScript file. ...
... Check if the window is a tab or the root window window.addEventListener("load", function(e) { alert("Is root?: " + isRoot
()); }, false); function isRoot
() { if(window != window.top) return "false"; else return "true"; } The example above tells you if the window object is a reference of the application window or of one of it is a tabs. Register a timer window.setInterval( function
() { alert('foobar'); }, 60000); //execute the function once very minute If you periodically need to perform a certain action then you can use the setInterval function, it will then call this function every x milliseconds, in this case every 60000ms or one minute. ...
Memory Management
free that memory with the correct allocator. It is usually best to expose a freeing function from the binary. Keeping objects alive The following js-ctypes objects will hold references to objects, keeping them alive. This is not an exhaustive list, but will help you to understand memory management and how it affects your use of js-ctypes: A function or static data declared using the declare
() method will hold that library alive. A CType will hold referent CType objects alive. A CData will hold referent CData objects alive, under specific circumstances. For example, a CData object produced by accessing a field of a structure or the internals of an array will hold the referent objects alive. What won't keep objects alive It's important to note that getting direct access to the cont...
.... A CType will hold referent CType objects alive. A CData will hold referent CData objects alive, under specific circumstances. For example, a CData object produced by accessing a field of a structure or the internals of an array will hold the referent objects alive. What won't keep objects alive It's important to note that getting direct access to the contents of a CData object using address
(), addressOfElement
(), or contents, will result in a CData object that does not hold its referent alive. Be sure to hold an explicit reference so that the referent object doesn't get into garbage collection, before you're done using it. Closures You also need to be sure to retain references to any JavaScript code that native code may call back into. This should be obvious, but is important enough...
...ta object that does not hold its referent alive. Be sure to hold an explicit reference so that the referent object doesn't get into garbage collection, before you're done using it. Closures You also need to be sure to retain references to any JavaScript code that native code may call back into. This should be obvious, but is important enough to be worth stating explicitly. When in doubt, malloc
() When you need to keep data around, you can use malloc
() to allocate it directly. This bypasses JavaScript's memory management and lets you handle memory management yourself. ...
ctypes.open
int add(int a, int b) { return a + b; } To make this a shared library, a native file which can be loaded and used from js-ctypes, compile it with these commands: gcc -fPIC -c myCFuntionsForUnix.c gcc -shared -o myCFuntionsForUnix.so myCFuntionsForUnix.o A file named myCFuntionsForUnix.so is successfully created. ...
... int add(int a, int b) { return a + b; } To make this a shared library, a native file which can be loaded and used from js-ctypes, compile it with these commands: gcc -fPIC -c myCFuntionsForUnix.c gcc -shared -o myCFuntionsForUnix.so myCFuntionsForUnix.o A file named myCFuntionsForUnix.so is successfully created. ...
...o'); var jarPath_myLib = jarPath_folder + 'mySubFolder/myCFunctionsForUnix.so'; } This can then be opened and the C functions within can be used from js-ctypes. ...
ArrayType
If you don't specify this parameter, the array's length is unspecified. Return value A CType represents the newly declared array type. ...
...ns a CType representing the data type "pointer to this type". This is the result of calling ctypes.PointerType(the_type). Read only. size Number The size of the type, in bytes. This is the same value as the C sizeof. Read only. Note: ctypes.void_t.size is undefined. Method overview Methods inherited from CType CType array([n]) String toSource
() String toString
() ArrayType CData Syntax CData sized_arraytype
(); CData unsized_arraytype(length); sized_arraytype and unsized_arraytype are ArrayType CType. Parameters length The number of entries the array type should be able to contain. Only for unsized ArrayType. Return value A CData representing the newly allocated array. Exceptions thrown TypeError length is ...
...s a CType. Read only. Note: This is never ctypes.void_t or an array type with an unspecified length. value object The JavaScript equivalent of the CData object's value. This will throw a TypeError exception if the value can't be converted. ArrayType CData Method_overview CData addressOfElement(idx) Methods inherited from CData CData address
() String toSource
() String toString
() ArrayType CData Methods addressOfElement
() Returns a new CData object of the appropriate pointer type, whose value points to the specified array element on which the method was called. CData addressOfElement( idx ); Parameters idx A numeric value indicating the offset into the array of the element just to return a pointer. If...
StructType
cture (that is, one created in C using #pragma pack). CType StructType( name[, fields] ); Parameters name The name of the structure. Must be a string. fields Optional An array of field descriptors, describing all the entries in the structure. If this isn't specified, the structure is considered opaque and you can't access its contents directly. You can call the resulting type's define
() method to assign it a non-opaque type later. See Opaque structures for further explanation and an example. Return value A CType object describing the newly created struct data type. Exceptions thrown TypeError The name is not a string, or one or more of the fields does not have a defined size. RangeError The size of the structure, in bytes, cannot be represented both as a size_t and as ...
...a type "pointer to this type". This is the result of calling ctypes.PointerType(the_type). Read only. size Number The size of the type, in bytes. This is the same value as the C sizeof. Read only. Note: ctypes.void_t.size is undefined. Method overview define(fields) Methods inherited from CType CType array([n]) String toSource
() String toString
() Methods define
() Defines a previously declared opaque type's fields. This lets you convert an opaque structure type into a defined structure type. define( fields ); Parameters fields A field specification, as described above. StructType CData Syntax CData structtype
(); structtype is StructType CType. Return value A CData representing the newly a...
...s a CType. Read only. Note: This is never ctypes.void_t or an array type with an unspecified length. value object The JavaScript equivalent of the CData object's value. This will throw a TypeError exception if the value can't be converted. StructType CData Method_overview CData addressOfField(name) Methods inherited from CData CData address
() String toSource
() String toString
() StructType CData Methods addressOfField
() Returns a new CData object of the appropriate pointer type, whose value points to the specified field of the structure on which the method was called. See Working with strings for more information on how to convert strings. CData addressOfField( name ); Parameters name The name of the...
ctypes
o an indeterminate type of data. Large integer types Because JavaScript doesn't support large (64-bit) integers, js-ctypes provides two data types allowing access to 64-bit integer data. Type Description Int64 A JavaScript object representing a 64-bit signed integer. UInt64 A JavaScript object representing a 64-bit unsigned integer. Methods cast
() Casts the specified CData object to a new type, returning a new CData object representing the value in the new type. See Type casting for details. CData cast( data, type ); Parameters data The CData object to type cast. type The type to which to cast the value. This can be one of the Predefined data types, or any user-defined types. Return value A new CData object representing the...
...urning a new CData object representing the value in the new type. See Type casting for details. CData cast( data, type ); Parameters data The CData object to type cast. type The type to which to cast the value. This can be one of the Predefined data types, or any user-defined types. Return value A new CData object representing the same data, but with the specified type. libraryName
() Returns the correct platform-specific filename for a given library name (e.g. libnss3.dylib for nss3 on OS X.) String libraryName( name ); Parameters name The name of the library. Return value String containing the platform-specific filename of the library. open
() Opens a library, specified by a pathname. The library is loaded from the specified full path, or, if a partial path is ...
... full path, or, if a partial path is specified, from the appropriate library directory based on the platform on which the application is running. See Library search paths for more details. Library open( libSpec ); Parameters libSpec The native library to open, specified as a pathname string. Return value A Library object representing the opened library. Examples Example of StructType
() on Windows Let's say we need TB_BUTTON, this type needs to be created. So we look up on MSDN what the TB_BUTTON structures is (MSDN :: TB_BUTTON Structure) and it says it is: typedef struct { int iBitmap; int idCommand; BYTE fsState; BYTE fsStyle; #ifdef _WIN64 BYTE bReserved[6]; #else #if defined(_WIN32) BYTE bReserved[2]; #endif #endif DWORD_PTR d...
js-ctypes reference
obtained by by loading the ctypes module: Components.utils.import("resource://gre/modules/ctypes.jsm"); You can use the ctypes object to load libraries, construct types, and perform miscellaneous tasks such as type casting. The ctypes object also provides numerous predefined types that correspond to primitives and common typedefs in C. Working with libraries To load a Library, use ctypes.open
(). The Library object is used mostly to declare native functions provided by the library so that js-ctypes knows how to call them. See Library.declare
() for instructions on how to declare these functions. Once you have finished working with a Library, call Library.close
(). Calling conventions See ABI. Types and data To use js-ctypes effectively, it is important to understand the different kin...
...o understand the different kinds of objects that the module provides. There are three major categories: Types These represent a type in C, and are thus represented by CType objects. These objects have two main purposes. First, they provide a concrete representation of different data types, allowing the programmer to describe the arguments and return type of a native function (see Library.declare
()). Second, they serve as constructors to create concrete instances of the given type, i.e. CData objects. Out of the box, js-ctypes supports a number of predefined types. Type constructors These are functions that define new types, and thus return a CType object. These include ctypes.PointerType(type) and the .ptr property, which creates a new type describing a pointer to an existing type. ...
... concrete instances of the given type, i.e. CData objects. Out of the box, js-ctypes supports a number of predefined types. Type constructors These are functions that define new types, and thus return a CType object. These include ctypes.PointerType(type) and the .ptr property, which creates a new type describing a pointer to an existing type. ctypes.ArrayType(type, [length]) and the .array
() method, which creates a new type describing an array of objects of an existing type. ctypes.StructType
(), which creates a new type describing a C struct. ctypes.FunctionType(abi, returnType, argType1 [, argType2 ...]), which creates a new type describing a C function. Data These are instances of types, represented by CData objects and instantiated by calling CType objects as functions. The...
Plug-in Development Overview - Plugins
to the plug-in instance in a new stream. The NPN_PostURLNotify function operates like NPN_PostURL, except that it notifies the plug-in of the result when the operation completes. For information about using these methods, see URLs. Starting in Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7), you can get the origin of the document in a secure, convenient way by calling NPN_GetValue
() to retrieve the value of the variable NPNVdocumentOrigin. The returned value is the Unicode serialization of the document's origin converted to NFKC-encoded (that is, normalized) UTF-8. Your plug-in must free the returned string's memory by calling NPN_MemFree
() when you're done with it. Getting Version and UI Information The Netscape group of Plug-in API methods provides some basic services to...
...tus line. For information about using this method, see Version, UI, and Status Information. Making Plug-ins Scriptable Scriptable plug-ins are plug-ins that have been extended to provide methods that can be called from JavaScript and the DOM when accessed through the object or embed element. ...
...See the Wikipedia article for historical information. ...
Scripting plugins - Plugins
that wishes to access objects in the browser window that loaded the plugin can do this by getting the NPObject for the browser's window object, or the DOM element that loaded the plugin. This is done by using an extension to NPN_GetValue. The extensions are two additions to the NPNVariables enumeration; the new enumerations are NPNVWindowNPObject and NPNVPluginElementNPObject. Calling NPN_GetValue
() with either of those new enumerations will return an NPObject representing the browser object, and from there, the functions in this API can be used to get and set properties, and to call methods on those browser objects. And as always when working with reference counted NPObjects, the caller is responsible for calling NPN_ReleaseObject on the NPObject to drop the reference. The new NPNVariable...
..., the caller is responsible for calling NPN_ReleaseObject on the NPObject to drop the reference. ...
...drop the reference. ...
Index - Firefox Developer Tools
hen an exception occurs, the line where it occurs is highlighted in the source pane, with a squiggly red line under the problematic code. A tooltip describes the exception. Starting in Firefox 80, a disclosure triangle within the tooltip reveals a stack trace. 120 Debug eval sources You can debug JavaScript code that is evaluated dynamically, either as a string passed to eval
() or as a string passed to the Function constructor. 121 Disable breakpoints To disable a single breakpoint, uncheck the checkbox next to it in the breakpoints list. 122 Examine, modify, and watch variables When the code has stopped at a breakpoint, you can examine its state in the variables pane of the debugger: 123 Highlight and inspect DOM n...
... debugging sessions when you are forced to step through its stack frames in order to reach your own code. However, you can tell the debugger to ignore the details of selected sources. 125 Open the debugger There are three ways to open the debugger: 126 Pretty-print a minified file JavaScript To prettify a minified file, click the Pretty print source icon
() at the bottom of the source pane. The debugger formats the source and displays it as a new file with a name like: "{ } [original-name]". 127 Search To search for a particular file, press Control + P (or Command + P on a Mac) and type the search term. The source pane will display a list of all matching files as you type. You can use the up and down arrows to move through the...
...be provided by watchpoints. By setting a watchpoint on the property, rather than a breakpoint at a particular line, you can discover where that access occurs. 134 Set a logpoint Debugger, Debugging, Dev Tools, JavaScript debugging, Tools, breakpoint, logpoint Sometimes you want to view a value in your code but you don't want to pause execution. Rather than sprinkle console.log
() statements throughout your code, you can use a special type of breakpoint, the logpoint. Logpoints print a message to the Console panel instead of pausing code execution. 135 Set an XHR breakpoint Debugger, Debugging, JavaScript, XHR Breakpoint An XHR (XMLHttpRequest) breakpoint breaks code execution when an XHR request is dispatched so that you can examine the current state ...
AbortSignal: abort event - Web APIs
The abort event of the Fetch API is fired when a fetch request is aborted, i.e. using AbortController.abort
(). Bubbles No Cancelable No Interface Event Event handler onabort Examples In the following snippets, we create a new AbortController object, and get its AbortSignal (available in the signal property). Later on we check whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console. ...
...ent handler onabort Examples In the following snippets, we create a new AbortController object, and get its AbortSignal (available in the signal property). Later on we check whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console. ...
... new AbortController object, and get its AbortSignal (available in the signal property). Later on we check whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console. You can use the abort event in an addEventListener method: var controller = new AbortController
(); var signal = controller.signal; signal.addEventListener('abort', function
() { console.log('Request aborted'); }; Or use the onabort event handler property: var controller = new AbortController
(); var signal = controller.signal; signal.onabort = function
() { console.log('Request aborted'); }; Specifications Specification Status DOMThe definition of 'abort' in that specification. Living Standard ...
AbsoluteOrientationSensor - Web APIs
to the 'accelerometer', 'gyroscope', and 'magnetometer' device sensors 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 AbsoluteOrientationSensor.AbsoluteOrientationSensor
() Creates a new AbsoluteOrientationSensor object. Properties No specific properties; inherits methods from its ancestors OrientationSensor and Sensor. Event handlers No specific event handlers; inherits methods from its ancestor, Sensor. Methods No specific methods; inherits methods from its ancestors OrientationSensor and Sensor. Examples Basic Example The following example, which is lo...
...lowing example, which is loosely based on Intel's Orientation Phone demo, instantiates an AbsoluteOrientationSensor with a frequency of 60 times a second. On each reading it uses OrientationSensor.quaternion to rotate a visual model of a phone. const options = { frequency: 60, referenceFrame: 'device' }; const sensor = new AbsoluteOrientationSensor(options); sensor.addEventListener('reading',
() => { // model is a Three.js object instantiated elsewhere. model.quaternion.fromArray(sensor.quaternion).inverse
(); }); sensor.addEventListener('error', error => { if (event.error.name == 'NotReadableError') { console.log("Sensor is not available."); } }); sensor.start
(); Permissions Example Using orientation sensors requires requesting permissions for multiple device sensors. Becau...
...ventListener('error', error => { if (event.error.name == 'NotReadableError') { console.log("Sensor is not available."); } }); sensor.start
(); Permissions Example Using orientation sensors requires requesting permissions for multiple device sensors. Because the Permissions uses promises, a good way to request permissions is to use Promise.all. const sensor = new AbsoluteOrientationSensor
(); Promise.all([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...
AesGcmParams - Web APIs
For details of how to supply appropriate values for this parameter, see the specification for AES-GCM: NIST SP800-38D, in particular section 5.2.1.1 on Input Data. Properties name A DOMString. This should be set to AES-GCM. iv A BufferSource -- the initialization vector. This must be unique for every encryption operation carried out with a given key. ...
... that the IV does not have to be secret, just unique: so it is OK, for example, to transmit it in the clear alongside the encrypted message. additionalData Optional A BufferSource. This contains additional data that will not be encrypted but will be authenticated along with the encrypted data. If additionalData is given here then the same data must be given in the corresponding call to decrypt
(): if the data given to the decrypt
() call does not match the original data, the decryption will throw an exception. This gives you a way to authenticate associated data without having to encrypt it. The bit length of additionalData must be <= 264-1. The additionalData property is optional and may be omitted without compromising the security of the encryption operation. tagLength Optional ...
...e one of the following values: 32, 64, 96, 104, 112, 120, or 128. The AES-GCM specification recommends that it should be 96, 104, 112, 120 or 128, although 32 or 64 bits may be acceptable in some applications: Appendix C of the specification provides additional guidance here. tagLength is optional and defaults to 128 if it is not specified. Examples See the examples for SubtleCrypto.encrypt
() and SubtleCrypto.decrypt
(). Specifications Specification Status Comment Web Cryptography APIThe definition of 'SubtleCrypto.AesGcmParams' in that specification. Recommendation ...
AnalyserNode.smoothingTimeConstant - Web APIs
asic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). If you are curious about the effect the smoothingTimeConstant
() has, try cloning the above example and setting analyser.smoothingTimeConstant = 0; instead. You'll notice that the value changes are much more jarring. var audioCtx = new (window.AudioContext || window.webkitAudioContext)
(); var analyser = audioCtx.createAnalyser
(); analyser.minDecibels = -90; analyser.maxDecibels = -10; analyser.smoothingTimeConstant = 0.85; ... analyser.fftSize = 256; var ...
...(window.AudioContext || window.webkitAudioContext)
(); var analyser = audioCtx.createAnalyser
(); analyser.minDecibels = -90; analyser.maxDecibels = -10; analyser.smoothingTimeConstant = 0.85; ... ...
... Working Draft ...
Animation.replaceState - Web APIs
The read-only Animation.replaceState property of the Web Animations API returns the replace state of the animation. This will be active if the animation has been removed, or persisted if Animation.persist
() has been invoked on it. Syntax let myReplaceState = Animation.replaceState; Value A string that represents the replace state of the anmation. The value can be one of: active: The initial value of the animation's replace state; when the animation has been removed by the browser's Automatically removing filling animations behavior. persisted: The animation has been explicitly persisted by invoking Animation.persist
() on it. removed: The animation has been explicitly removed. Examples In our simple replace indefinite animations demo, you can see the following code: const div...
... animation has been explicitly removed. Examples In our simple replace indefinite animations demo, you can see the following code: const divElem = document.querySelector('div'); document.body.addEventListener('mousemove', evt => { let anim = divElem.animate( { transform: `translate(${ evt.clientX}px, ${evt.clientY}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitStyles
(); //anim.persist
() anim.onremove = function
() { console.log('Animation removed'); } console.log(anim.replaceState); }); Here we have a <div> element, and an event listener that fires the event handler code whenever the mouse moves. The event handler sets up an animation that animates the <div> element to the position of the mouse pointer. This could result in a huge animations list...
...imates the <div> element to the position of the mouse pointer. This could result in a huge animations list, which could create a memory leak. For this reason, modern browsers automatically remove overriding forward filling animations. You can see the replaceState of the animation being logged at the end of the handler. This will be active for each animation by default, or persisted if the persist
() call is uncommented. Specifications Specification Status Comment Web AnimationsThe definition of 'Animation.replaceState' in that specification. Working Draft ...
AudioBuffer.duration - Web APIs
tax var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate); myArrayBuffer.duration; Value A double. ...
... Working Draft ...
... Working Draft ...
AudioBuffer.length - Web APIs
tax var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate); myArrayBuffer.length; Value An integer. ...
... Working Draft ...
... Working Draft ...
AudioBuffer.numberOfChannels - Web APIs
yArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate); myArrayBuffer.numberOfChannels; Value An integer. ...
... Working Draft ...
... Working Draft ...
AudioBuffer.sampleRate - Web APIs
fer.sampleRate; Value A floating-point value indicating the current sample rate of the buffers data, in samples per second. ...
... Working Draft ...
... Working Draft ...
AudioBufferSourceNode.buffer - Web APIs
hannel containing silence (that is, every sample is 0). Syntax AudioBufferSourceNode.buffer = soundBuffer; Value An AudioBuffer which contains the data representing the sound which the node will play. Example For a full working example, see this code running live, or view the source. ...
...fer(2, frameCount, audioCtx.sampleRate); button.onclick = function
() { // Fill the buffer with white noise; //just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // This gives us the actual ArrayBuffer that contains the data var nowBuffering = myArrayBuffer.getChannelData(channel); for (var i = 0; i < frameCount; i++) { // Math.random
() is in [0; 1.0] // audio needs to be in [-1.0; 1.0] nowBuffering[i] = Math.random
() * 2 - 1; } } // Get an AudioBufferSourceNode. ...
...ntains the data var nowBuffering = myArrayBuffer.getChannelData(channel); for (var i = 0; i < frameCount; i++) { // Math.random
() is in [0; 1.0] // audio needs to be in [-1.0; 1.0] nowBuffering[i] = Math.random
() * 2 - 1; } } // Get an AudioBufferSourceNode. // This is the AudioNode to use when we want to play an AudioBuffer var source = audioCtx.createBufferSource
(); // set the buffer in the AudioBufferSourceNode source.buffer = myArrayBuffer; Specifications Specification Status Comment Web Audio APIThe definition of 'buffer' in that specification. Working Draft Initial definition ...
AudioBufferSourceNode.detune - Web APIs
The detune property of the AudioBufferSourceNode interface is a k-rate AudioParam representing detuning of oscillation in cents. For example, values of +100 and -100 detune the source up or down by one semitone, while +1200 and -1200 detune it up or down by one octave. Syntax var source = audioCtx.createBufferSource
(); source.detune.value = 100; // value in cents Note: Though the AudioParam returned is read-only, the value it represents is not. ...
...p or down by one semitone, while +1200 and -1200 detune it up or down by one octave. Syntax var source = audioCtx.createBufferSource
(); source.detune.value = 100; // value in cents Note: Though the AudioParam returned is read-only, the value it represents is not. Value A k-rate AudioParam whose value indicates the detuning of oscillation in cents. ...
...oCtx = new AudioContext
(); const channelCount = 2; const frameCount = audioCtx.sampleRate * 2.0; // 2 seconds const myArrayBuffer = audioCtx.createBuffer(channelCount, frameCount, audioCtx.sampleRate); for (let channel = 0; channel < channelCount; channel++) { const nowBuffering = myArrayBuffer.getChannelData(channel); for (let i = 0; i < frameCount; i++) { nowBuffering[i] = Math.random
() * 2 - 1; } } const source = audioCtx.createBufferSource
(); source.buffer = myArrayBuffer; source.connect(audioCtx.destination); source.detune.value = 100; // value in cents source.start
(); Specifications Specification Status Comment Web Audio APIThe definition of 'detune' in that specification. Working Draft ...
AudioNode - Web APIs
. For a list of all audio nodes, see the Web Audio API homepage. Creating an AudioNode There are two ways to create an AudioNode: via the constuctor and via the factory method. // constructor const analyserNode = new AnalyserNode(audioCtx, { fftSize: 2048, maxDecibels: -25, minDecibels: -60, smoothingTimeConstant: 0.5, }); // factory method const analyserNode = audioCtx.createAnalyser
(); analyserNode.fftSize = 2048; analyserNode.maxDecibels = -25; analyserNode.minDecibels = -60; analyserNode.smoothingTimeConstant = 0.5; You are free to use either constructors or factory methods, or mix both, however there are advantages to using the constructors: All parameters can be set during construction time and don't need to be set individually. You can sub-class an audio node. While ...
...ing the way channels must be matched between the node's inputs and outputs. AudioNode.channelInterpretation Represents an enumerated value describing the meaning of the channels. This interpretation will define how audio up-mixing and down-mixing will happen. The possible values are "speakers" or "discrete". Methods Also implements methods from the interface EventTarget. AudioNode.connect
() Allows us to connect the output of this node to be input into another node, either as audio data or as the value of an AudioParam. AudioNode.disconnect
() Allows us to disconnect the current node from another one it is already connected to. Example This simple snippet of code shows the creation of some audio nodes, and how the AudioNode properties and methods can be used. You can find exampl...
...ect
() Allows us to disconnect the current node from another one it is already connected to. Example This simple snippet of code shows the creation of some audio nodes, and how the AudioNode properties and methods can be used. You can find examples of such usage on any of the examples linked to on the Web Audio API landing page (for example Violent Theremin.) const audioCtx = new AudioContext
(); const oscillator = new OscillatorNode(audioCtx); const gainNode = new GainNode(audioCtx); oscillator.connect(gainNode).connect(audioCtx.destination); oscillator.context; oscillator.numberOfInputs; oscillator.numberOfOutputs; oscillator.channelCount; Specifications Specification Status Comment Web Audio APIThe definition of 'AudioNode' in that specification. Workin...
AudioParamDescriptor - Web APIs
Processor, and register it. Note that this should be done in a separate file. We expand the processor by adding a static parameterDescriptors getter. It will be used internally by the AudioWorkletNode constructor to populate its parameters with instantiated AudioParam objects. ...
... } }) return true } }...
...e used for all 128 samples // if no automation is scheduled for the moment. } }) return true } } registerProcessor('white-noise-processor', WhiteNoiseProcessor) Next, in our main scripts file we'll load the processor, create an instance of AudioWorkletNode passing it the name of the processor, and connect the node to an audio graph. ...
AudioScheduledSourceNode - Web APIs
The AudioScheduledSourceNode interface--part of the Web Audio API--is a parent interface for several types of audio source node interfaces which share the ability to be started and stopped, optionally at specified times. Specifically, this interface defines the start
() and stop
() methods, as well as the onended event handler. You can't create an AudioScheduledSourceNode object directly. Instead, use the interface which extends it, such as AudioBufferSourceNode, OscillatorNode, and ConstantSourceNode. Unless stated otherwise, nodes based upon AudioScheduledSourceNode output silence when not playing (that is, before start
() is called and after stop
() is called). Silence is represented, as always, by a stream of samples with the value zero (0). Properties Inherits properties from its par...
...e, nodes based upon AudioScheduledSourceNode output silence when not playing (that is, before start
() is called and after stop
() is called). Silence is represented, as always, by a stream of samples with the value zero (0). Properties Inherits properties from its parent interface, AudioNode. Methods Inherits methods from its parent interface, AudioNode, and adds the following methods: start
() Schedules the node to begin playing the constant sound at the specified time. If no time is specified, the node begins playing immediately. stop
() Schedules the node to stop playing at the specified time. If no time is specified, the node stops playing at once. ...
...rom its parent interface, AudioNode, and adds the following methods: start
() Schedules the node to begin playing the constant sound at the specified time. If no time is specified, the node begins playing immediately. stop
() Schedules the node to stop playing at the specified time. If no time is specified, the node stops playing at once. Events Listen to these events using addEventListener
() or by assigning an event listener to the oneventname property of this interface: ended Fired when the source node has stopped playing, either because it's reached a predetermined stop time, the full duration of the audio has been performed, or because the entire buffer has been played. Also available using the onended event handler property. Specification Specification Status ...
AudioTrack.enabled - Web APIs
lse; Value The enabled property is a Boolean whose value is true if the track is enabled; enabled tracks produce audio while the media is playing. Setting enabled to false effectively mutes the audio track, preventing it from contributing to the media's audio performance. Example This example switches between the main and commentary audio tracks of a media element. ...
...These represent the primary audio track and the commentary track. Note: This example assumes that there is only one of each kind of track in the video, but this is not necessarily the case. The element's audio tracks are then scanned through using th...
...s within the audio tracks of the <video> element "main-video" the audio tracks whose kind values are "main" and "commentary". These represent the primary audio track and the commentary track. Note: This example assumes that there is only one of each kind of track in the video, but this is not necessarily the case. The element's audio tracks are then scanned through using the JavaScript forEach
() method (although the audioTracks property of a media element isn't actually a JavaScript array, it can be accessed like one for the most part). The scan looks for the tracks whose kind values are "main" and "commentary" and remembers those AudioTrack objects. Once those have been found, the values of the two tracks' enabled properties are exchanged, which results in swapping which of the two tra...
AudioTrackList: change event - Web APIs
The change event is fired when an audio track is enabled or disabled, for example by changing the track's enabled property. ...
...hange Examples Using addEventListener
(): const videoElement = document.querySelector('video'); videoElement.audioTracks.addEventListener('change', (event) => { console.log(`'${event.type}' event fired`); }); // changing the value of `enabled` will trigger the `change` event const toggleTrackButton = document.querySelector('.toggle-track'); toggleTrackButton.addEventListener('click',
() => { const track = videoElement.audioTracks[0]; track.enabled = !track.enabled; }); Using the onchange event handler property: const videoElement = document.querySelector('video'); videoElement.audioTracks.onchange = (event) => { console.log(`'${event.type}' event fired`); }; // changing the value of `enabled` will trigger the `change` event const toggleTrackButton = document.querySel...
... Living Standard ...
AudioWorkletNode.parameters - Web APIs
Processor, and register it. Note that this should be done in a separate file. We expand the processor by adding a static parameterDescriptors getter. It will be used internally by the AudioWorkletNode constructor to populate its parameters with instantiated AudioParam objects. ...
... } }) return true } }...
...e used for all 128 samples // if no automation is scheduled for the moment. } }) return true } } registerProcessor('white-noise-processor', WhiteNoiseProcessor) Next, in our main scripts file we'll load the processor, create an instance of AudioWorkletNode passing it the name of the processor, and connect the node to an audio graph. ...
AudioWorkletNode - Web APIs
not, thus custom AudioWorkletProcessors cannot be defined outside them. The AudioWorkletNode interface of the Web Audio API represents a base class for a user-defined AudioNode, which can be connected to an audio routing graph along with other nodes. It has an associated AudioWorkletProcessor, which does the actual audio processing in a Web Audio rendering thread. Constructor AudioWorkletNode
() Creates a new instance of an AudioWorkletNode object. Properties Also Inherits properties from its parent, AudioNode. AudioWorkletNode.port Read only Returns a MessagePort used for bidirectional communication between the node and its associated AudioWorkletProcessor. The other end is available under the port property of the processor. AudioWorkletNode.parameters Read only Returns an A...
...custom AudioWorkletProcessor, which will output white noise, and register it. Note that this should be done in a separate file. ...
...or (let i = 0; i < channel.length; i++) { channel[i] = Math.random
() * 2 - 1 } }) return true } } registerProcessor('white-noise-processor', WhiteNoiseProcessor) Next, in our main script file we'll load the processor, create an instance of AudioWorkletNode passing it the name of the processor, and connect the node to an audio graph. const audioContext = new AudioContext
() await audioContext.audioWorklet.addModule('white-noise-processor.js') const whiteNoiseNode = new AudioWorkletNode(audioContext, 'white-noise-processor') whiteNoiseNode.connect(audioContext.destination) Specifications Specification Status Comment Web Audio APIThe definition of 'AudioWorkletNode' in that specification. Working Draft ...
AudioWorkletProcessor.parameterDescriptors (static getter) - Web APIs
Processor, and register it. Note that this should be done in a separate file. We expand the processor by adding a static parameterDescriptors getter. It will be used internally by the AudioWorkletNode constructor to populate its parameters with instantiated AudioParam objects. ...
... } }) return true } }...
...e used for all 128 samples // if no automation is scheduled for the moment. } }) return true } } registerProcessor('white-noise-processor', WhiteNoiseProcessor) Next, in our main scripts file we'll load the processor, create an instance of AudioWorkletNode passing it the name of the processor, and connect the node to an audio graph. ...
AuthenticatorResponse.clientDataJSON - Web APIs
This property is only accessed on one of the child objects of AuthenticatorResponse, specifically AuthenticatorAttestationResponse or AuthenticatorAssertionResponse. Syntax var arrayBuffer = AuthenticatorAttestationResponse.clientDataJSON; var arrayBuffer = AuthenticatorAssertionResponse.clientDataJSON; Value An ArrayBuffer. ...
...d already id: A DOMString which is the base64url encoding of the token binding ID which was used for the communication. Should this property be absent, it would indicate that the client does not support token binding. ...
... id: A DOMString which is the base64url encoding of the token binding ID which was used for the communication. Should this property be absent, it would indicate that the client does not support token binding. ...
BaseAudioContext.state - Web APIs
The state read-only property of the BaseAudioContext interface returns the current state of the AudioContext. Syntax baseAudioContext.state; Value A DOMString. Possible values are: suspended: The audio context has been suspended (with the AudioContext.suspend
() method.) running: The audio context is running normally. ...
... The state read-only property of the BaseAudioContext interface returns the current state of the AudioContext. Syntax baseAudioContext.state; Value A DOMString. Possible values are: suspended: The audio context has been suspended (with the AudioContext.suspend
() method.) running: The audio context is running normally. ...
...ontext.suspend
() method.) running: The audio context is running normally. closed: The audio context has been closed (with the AudioContext.close
() method.) Example The following snippet is taken from our AudioContext states demo (see it running live.) The AudioContext.onstatechange hander is used to log the current state to the console every time it changes. audioCtx.onstatechange = function
() { console.log(audioCtx.state); } Specifications Specification Status Comment Web Audio APIThe definition of 'state' in that specification. Working Draft ...
BasicCardResponse.billingAddress - Web APIs
The billingAddress property of the BasicCardResponse dictionary contains the billing address of the card used to make the payment. Syntax "billingAddress" : PaymentAddress Value A PaymentAddress object representing the billing address of the card. ...
...Response dictionary contains the billing address of the card used to make the payment. Syntax "billingAddress" : PaymentAddress Value A PaymentAddress object representing the billing address of the card. Example Let's look at a sample payment request: var request = new PaymentRequest(supportedInstruments, details, options); // Call show
() to trigger the browser's payment flow. ...
... Example Let's look at a sample payment request: var request = new PaymentRequest(supportedInstruments, details, options); // Call show
() to trigger the browser's payment flow. request.show
().then(function(instrumentResponse) { // Do something with the response from the UI. console.log(instrumentResponse.details); }) .catch(function(err) { // Do something with the error from request.show
(). }); Once the payment flow has been triggered using PaymentRequest.show
() and the promise resolves successfully, the PaymentResponse object available inside the fulfilled promise (instrumentResponse above) will have a PaymentResponse.details property that will contain response details. This has to conform to the structure defined by the BasicCardResponse dictionary, and may look something like t...
BasicCardResponse.cardNumber - Web APIs
The cardNumber property of the BasicCardResponse dictionary contains the number of the card used to make the payment. Syntax "cardNumber" : "number" Value A DOMString representing the credit card number. Example Let's look at a sample payment request: var request = new PaymentRequest(supportedInstruments, details, options); // Call show
() to trigger the browser's payment flow. ...
...The cardNumber property of the BasicCardResponse dictionary contains the number of the card used to make the payment. Syntax "cardNumber" : "number" Value A DOMString representing the credit card number. Example Let's look at a sample payment request: var request = new PaymentRequest(supportedInstruments, details, options); // Call show
() to trigger the browser's payment flow. ...
... Example Let's look at a sample payment request: var request = new PaymentRequest(supportedInstruments, details, options); // Call show
() to trigger the browser's payment flow. request.show
().then(function(instrumentResponse) { // Do something with the response from the UI. console.log(instrumentResponse.details); }) .catch(function(err) { // Do something with the error from request.show
(). }); Once the payment flow has been triggered using PaymentRequest.show
() and the promise resolves successfully, the PaymentResponse object available inside the fulfilled promise (instrumentResponse above) will have a PaymentResponse.details property that will contain response details. This has to conform to the structure defined by the BasicCardResponse dictionary, and may look something like t...
BasicCardResponse.cardSecurityCode - Web APIs
The cardSecurityCode property of the BasicCardResponse dictionary contains the security code of the card used to make the payment. Syntax "cardSecurityCode" : "number" Value A DOMString representing the card security code. Example Let's look at a sample payment request: var request = new PaymentRequest(supportedInstruments, details, options); // Call show
() to trigger the browser's payment flow. ...
...e property of the BasicCardResponse dictionary contains the security code of the card used to make the payment. Syntax "cardSecurityCode" : "number" Value A DOMString representing the card security code. Example Let's look at a sample payment request: var request = new PaymentRequest(supportedInstruments, details, options); // Call show
() to trigger the browser's payment flow. ...
... Example Let's look at a sample payment request: var request = new PaymentRequest(supportedInstruments, details, options); // Call show
() to trigger the browser's payment flow. request.show
().then(function(instrumentResponse) { // Do something with the response from the UI. console.log(instrumentResponse.details); }) .catch(function(err) { // Do something with the error from request.show
(). }); Once the payment flow has been triggered using PaymentRequest.show
() and the promise resolves successfully, the PaymentResponse object available inside the fulfilled promise (instrumentResponse above) will have a PaymentResponse.details property that will contain response details. This has to conform to the structure defined by the BasicCardResponse dictionary, and may look something like t...
BasicCardResponse.cardholderName - Web APIs
The cardNumber property of the BasicCardResponse dictionary contains the cardholder name of the card used to make the payment. Syntax name = basicCardResponse.cardholderName; Value A DOMString indicating the name of the cardholder. Example Let's look at a sample payment request: var request = new PaymentRequest(supportedInstruments, details, options); // Call show
() to trigger the browser's payment flow. ...
...e BasicCardResponse dictionary contains the cardholder name of the card used to make the payment. Syntax name = basicCardResponse.cardholderName; Value A DOMString indicating the name of the cardholder. Example Let's look at a sample payment request: var request = new PaymentRequest(supportedInstruments, details, options); // Call show
() to trigger the browser's payment flow. ...
... Example Let's look at a sample payment request: var request = new PaymentRequest(supportedInstruments, details, options); // Call show
() to trigger the browser's payment flow. request.show
().then(function(instrumentResponse) { // Do something with the response from the UI. console.log(instrumentResponse.details); }) .catch(function(err) { // Do something with the error from request.show
(). }); Once the payment flow has been triggered using PaymentRequest.show
() and the promise resolves successfully, the PaymentResponse object available inside the fulfilled promise (instrumentResponse above) will have a PaymentResponse.details property that will contain response details. This has to conform to the structure defined by the BasicCardResponse dictionary, and may look something like t...
BasicCardResponse.expiryMonth - Web APIs
The expiryMonth property of the BasicCardResponse dictionary contains the expiry month of the card used to make the payment. Syntax "expiryMonth" : "number" Value A DOMString representing the card expiry month as a two-digit number in the range 01 to 12. ...
...ictionary contains the expiry month of the card used to make the payment. Syntax "expiryMonth" : "number" Value A DOMString representing the card expiry month as a two-digit number in the range 01 to 12. Example Let's look at a sample payment request: var request = new PaymentRequest(supportedInstruments, details, options); // Call show
() to trigger the browser's payment flow. ...
... Example Let's look at a sample payment request: var request = new PaymentRequest(supportedInstruments, details, options); // Call show
() to trigger the browser's payment flow. request.show
().then(function(instrumentResponse) { // Do something with the response from the UI. console.log(instrumentResponse.details); }) .catch(function(err) { // Do something with the error from request.show
(). }); Once the payment flow has been triggered using PaymentRequest.show
() and the promise resolves successfully, the PaymentResponse object available inside the fulfilled promise (instrumentResponse above) will have a PaymentResponse.details property that will contain response details. This has to conform to the structure defined by the BasicCardResponse dictionary, and may look something like t...
BasicCardResponse.expiryYear - Web APIs
The expiryYear property of the BasicCardResponse dictionary contains the expiry year of the card used to make the payment. Syntax "expiryYear" : "number" Value A DOMString representing the card expiry year as a four-digit number in the range 0000 to 9999. ...
...tionary contains the expiry year of the card used to make the payment. Syntax "expiryYear" : "number" Value A DOMString representing the card expiry year as a four-digit number in the range 0000 to 9999. Example Let's look at a sample payment request: var request = new PaymentRequest(supportedInstruments, details, options); // Call show
() to trigger the browser's payment flow. ...
... Example Let's look at a sample payment request: var request = new PaymentRequest(supportedInstruments, details, options); // Call show
() to trigger the browser's payment flow. request.show
().then(function(instrumentResponse) { // Do something with the response from the UI. console.log(instrumentResponse.details); }) .catch(function(err) { // Do something with the error from request.show
(). }); Once the payment flow has been triggered using PaymentRequest.show
() and the promise resolves successfully, the PaymentResponse object available inside the fulfilled promise (instrumentResponse above) will have a PaymentResponse.details property that will contain response details. This has to conform to the structure defined by the BasicCardResponse dictionary, and may look something like t...
BatteryManager.onchargingchange - Web APIs
events. These events occur when the battery charging state is updated. Syntax battery.onchargingchange = funcRef Where battery is a BatteryManager object, and funcRef is a function to be called when the chargingchange event occurs. ...
...yntax battery.onchargingchange = funcRef Where battery is a BatteryManager object, and funcRef is a function to be called when the chargingchange event occurs. ...
... = funcRef Where battery is a BatteryManager object, and funcRef is a function to be called when the chargingchange event occurs. ...
BatteryManager.onchargingtimechange - Web APIs
. These events occur when the battery chargingTime is updated. Syntax battery.onchargingtimechange = funcRef Where battery is a BatteryManager object, and funcRef is a function to be called when the chargingtimechange event occurs. ...
...chargingtimechange = funcRef Where battery is a BatteryManager object, and funcRef is a function to be called when the chargingtimechange event occurs. ...
...battery is a BatteryManager object, and funcRef is a function to be called when the chargingtimechange event occurs. ...
Bluetooth - Web APIs
The Bluetooth interface of the Web Bluetooth API returns a Promise to a BluetoothDevice object with the specified options. Interface interface Bluetooth : EventTarget { Promise<boolean> getAvailability
(); attribute EventHandler onavailabilitychanged; [SameObject] readonly attribute BluetoothDevice? referringDevice; Promise<sequence<BluetoothDevice>> getDevices
(); Promise<BluetoothDevice> requestDevice(optional RequestDeviceOptions options = {}); }; Bluetooth includes BluetoothDeviceEventHandlers; Bluetooth includes CharacteristicEventHandlers; Bluetooth includes ServiceEventHandlers; Properties Inherits properties from its parent EventTarget. Bluetooth.referringDevice Read only Returns a reference to the device, if any, from which the user opened the current page. F...
...ser opened the current page. For example, an Eddystone beacon might advertise a URL, which the user agent allows the user to open. A BluetoothDevice representing the beacon would be available through navigator.bluetooth.referringDevice. Events Bluetooth.onavailabilitychanged An event handler that runs when an event of type availabilitychanged has fired. ...
... runs when an event of type availabilitychanged has fired. Methods Bluetooth.getAvailability
() Returns a Promise that resolved to a Boolean indicating whether the user-agent has the ability to support Bluetooth. Some user-agents let the user configure an option that affects what is returned by this value. If this option is set, that is the value returned by this method. Bluetooth.getDevices
() Returns a Promise that resolved to an array of BluetoothDevices which the origin already obtained permission for via a call to Bluetooth.requestDevice
(). Bluetooth.requestDevice
() Returns a Promise to a BluetoothDevice object with the specified options. Specifications Specification Status Comment Web BluetoothThe definition of 'Bluetooth' in that specification. Dr...
BluetoothRemoteGATTService - Web APIs
TTService.deviceRead only Returns information about a Bluetooth device through an instance of BluetoothDevice. BluetoothRemoteGATTService.isPrimaryRead only Returns a Boolean Indicating whether this is a primary or secondary service. BluetoothRemoteGATTService.uuidRead only Returns a DOMString representing the UUID of this service. ...
...turns a Boolean Indicating whether this is a primary or secondary service. BluetoothRemoteGATTService.uuidRead only Returns a DOMString representing the UUID of this service. Methods BluetoothRemoteGATTService.getCharacteristic
() Returns a Promise to an instance of BluetoothGATTCharacteristic for a given universally unique identifier (UUID). BluetoothRemoteGATTService.getCharacteristics
() Returns a Promise to an Array of BluetoothGATTCharacteristic instances for an optional universally unique identifier (UUID). ...
...ce. Methods BluetoothRemoteGATTService.getCharacteristic
() Returns a Promise to an instance of BluetoothGATTCharacteristic for a given universally unique identifier (UUID). BluetoothRemoteGATTService.getCharacteristics
() Returns a Promise to an Array of BluetoothGATTCharacteristic instances for an optional universally unique identifier (UUID). BluetoothRemoteGATTService.getIncludedService
() Returns a Promise to an instance of BluetoothRemoteGATTService for a given universally unique identifier (UUID). BluetoothRemoteGATTService.getIncludedServices
() Returns a Promise to an Array of BluetoothRemoteGATTService instances for an optional universally unique identifier (UUID). Specifications Specification Status Comment Web BluetoothThe definition of 'Bluetoo...
ByteLengthQueuingStrategy - Web APIs
Examples const queueingStrategy = new ByteLengthQueuingStrategy({ highWaterMark: 1 }); const readableStream = new ReadableStream({ start(controller) { ... }, pull(controller) { ... ...
... Examples const queueingStrategy = new ByteLengthQueuingStrategy({ highWaterMark: 1 }); const readableStream = new ReadableStream({ start(controller) { ... }, pull(controller) { ... ...
....enabled preference (needs to be set to true) and the javascript.options.streams preference (needs to be set to true). ...
CSSImageValue - Web APIs
The CSSImageValue interface of the CSS Typed Object Model API represents values for properties that take an image, for example background-image, list-style-image, or border-image-source. The CSSImageValue object represents an <image> that involves an URL, such as url
() or image
(), but not linear-gradient
() or element
() . Properties None. Methods None. ...
...lement
() . Properties None. Methods None. Examples We create an element <button>Magic Wand</button> We add some CSS, including a background image requesting a binary file: button { display: inline-block; min-height: 100px; min-width: 100px; background: no-repeat 5% center url(https://mdn.mozillademos.org/files/16793/magicwand.png) aqua; } We get the element's style map. ...
...on { display: inline-block; min-height: 100px; min-width: 100px; background: no-repeat 5% center url(https://mdn.mozillademos.org/files/16793/magicwand.png) aqua; } We get the element's style map. We then get
() the background-image from the stylemap and stringify it: // get the element const button = document.querySelector( 'button' ); // Retrieve all computed styles with computedStyleMap
() const allComputedStyles = button.computedStyleMap
(); // Return the CSSImageValue Example console.log( allComputedStyles.get('background-image') ); console.log( allComputedStyles.get('background-image').toString
() ); Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'CSSImageValue' in that specification. Working Draft Initial defi...
CSSMathValue - Web APIs
values. Interfaces based on CSSMathValue Below is a list of interfaces based on the CSSMathValue interface. CSSMathInvert CSSMathMax CSSMathMin CSSMathNegate CSSMathProduct CSSMathSum Properties CSSMathValue.operator Indicates the operator that the current subtype represents. Event handlers No Methods None. ...
...CSSMathValue Below is a list of interfaces based on the CSSMathValue interface. CSSMathInvert CSSMathMax CSSMathMin CSSMathNegate CSSMathProduct CSSMathSum Properties CSSMathValue.operator Indicates the operator that the current subtype represents. Event handlers No Methods None. Examples We create an element with a width determined using a calc
() function, then console.log
() the operator. ...
...tor Indicates the operator that the current subtype represents. Event handlers No Methods None. Examples We create an element with a width determined using a calc
() function, then console.log
() the operator. <div>has width</div> We assign a width with a calculation div { width: calc(30% - 20px); } We add the JavaScript const styleMap = document.querySelector('div').computedStyleMap
(); console.log( styleMap.get('width') ); // CSSMathSum {values: CSSNumericArray, operator: "sum"} console.log( styleMap.get('width').operator ); // 'sum' console.log( styleMap.get('width').values[1].value ); // -20 The CSSMathValue.operator returns 'sum' because styleMap.get('width').values[1].value ); is -20: adding a negative number. Specifications Spec...
CanvasGradient - Web APIs
If the offset is not between 0 and 1, inclusive, an INDEX_SIZE_ERR is raised; if the color can't be parsed as a CSS <color>, a SYNTAX_ERR is raised. ...
...If the offset is not between 0 and 1, inclusive, an INDEX_SIZE_ERR is raised; if the color can't be parsed as a CSS <color>, a SYNTAX_ERR is raised. ...
...If the offset is not between 0 and 1, inclusive, an INDEX_SIZE_ERR is raised; if the color can't be parsed as a CSS <color>, a SYNTAX_ERR is raised. ...
CanvasRenderingContext2D.lineJoin - Web APIs
the Canvas 2D API determines the shape used to join two line segments where they meet. This property has no effect wherever two connected segments have the same direction, because no joining area will be added in this case. Degenerate segments with a length of zero (i.e., with all endpoints and control points at the exact same position) are also ignored. Note: Lines can be drawn with the stroke
(), strokeRect
(), and strokeText
() methods. Syntax ctx.lineJoin = "bevel" || "round" || "miter"; Options There are three possible values for this property: "round", "bevel", and "miter". The default is "miter". "round" Rounds off the corners of a shape by filling an additional sector of disc centered at the common endpoint of connected segments. The radius for these rounded corners is eq...
...filling an additional lozenge-shaped area. This setting is affected by the miterLimit property. Default value. Examples Changing the joins in a path This example applies rounded line joins to a path. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.lineWidth = 20; ctx.lineJoin = 'round'; ctx.beginPath
(); ctx.moveTo(20, 20); ctx.lineTo(190, 100); ctx.lineTo(280, 20); ctx.lineTo(280, 150); ctx.stroke
(); Result Comparison of line joins The example below draws three different paths, demonstrating each of the three lineJoin options. <canvas id="canvas" width="150" height="150"></canvas> var ctx = document.getElementById('canvas').getContext('2d'); var lineJoin = ['round', 'bevel', 'miter'];...
... Comparison of line joins The example below draws three different paths, demonstrating each of the three lineJoin options. <canvas id="canvas" width="150" height="150"></canvas> var ctx = document.getElementById('canvas').getContext('2d'); var lineJoin = ['round', 'bevel', 'miter']; ctx.lineWidth = 10; for (let i = 0; i < lineJoin.length; i++) { ctx.lineJoin = lineJoin[i]; ctx.beginPath
(); ctx.moveTo(-5, 5 + i * 40); ctx.lineTo(35, 45 + i * 40); ctx.lineTo(75, 5 + i * 40); ctx.lineTo(115, 45 + i * 40); ctx.lineTo(155, 5 + i * 40); ctx.stroke
(); } ScreenshotLive sample Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.lineJoin' in that specification. Living Standard ...
CanvasRenderingContext2D.miterLimit - Web APIs
e miterLimit property See the chapter Applying styles and color in the Canvas tutorial for more information. ...
...anvas tutorial for more information. ...
...code" class="playable-code"> ctx.beginPath
(); ctx.moveTo(0,0); ctx.lineWidth = 15; ctx.lineTo(100, 100); ctx.stroke
();</textarea> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var textarea = document.getElementById("code"); var reset = document.getElementById("reset"); var edit = document.getElementById("edit"); var code = textarea.value; function drawCanvas
() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addEventListener("click", function
() { textarea.value = code; drawCanvas
(); }); edit.addEventListener("click", function
() { textarea.focus
(); }) textarea.addEventListener("input", drawCanvas); window.addEventListener("load", drawCanvas); ScreenshotLive sample Specifications Specification ...
CanvasRenderingContext2D.textAlign - Web APIs
For example, if textAlign is "center", then the text's left edge will be at x - (textWidth / 2). Syntax ctx.textAlign = "left" || "right" || "center" || "start" || "end"; Options Possible values: "left" The text is left-aligned. "right" The text is right-aligned. "center" The text is centered. ...
...ht-to-left locales). The default value is "start". Examples General text alignment This example demonstrates the three "physical" values of the textAlign property: "left", "center", and "right". ...
... General text alignment This example demonstrates the three "physical" values of the textAlign property: "left", "center", and "right". HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); canvas.width = 350; const ctx = canvas.getContext('2d'); const x = canvas.width / 2; ctx.beginPath
(); ctx.moveTo(x, 0); ctx.lineTo(x, canvas.height); ctx.stroke
(); ctx.font = '30px serif'; ctx.textAlign = 'left'; ctx.fillText('left-aligned', x, 40); ctx.textAlign = 'center'; ctx.fillText('center-aligned', x, 85); ctx.textAlign = 'right'; ctx.fillText('right-aligned', x, 130); Result Direction-dependent text alignment This example demonstrates the two direction-dependent values of the textAlign property: "start" and "end". Note that the direction ...
Optimizing canvas - Web APIs
ntext('2d').drawImage(myCanvas.offScreenCanvas, 0, 0); Avoid floating-point coordinates and use integers instead Sub-pixel rendering occurs when you render objects on a canvas without whole values. ctx.drawImage(myImage, 0.3, 0.5); This forces the browser to do extra calculations to create the anti-aliasing effect. To avoid this, make sure to round all co-ordinates used in calls to drawImage
() using Math.floor
(), for example. Don't scale images in drawImage Cache various sizes of your images on an offscreen canvas when loading as opposed to constantly scaling them in drawImage
(). Use multiple layered canvases for complex scenes In your application, you may find that some objects need to move or change frequently, while others remain relatively static. A possible optimization in thi...
...ght; var scaleToFit = Math.min(scaleX, scaleY); var scaleToCover = Math.max(scaleX, scaleY); stage.style.transformOrigin = '0 0'; //scale from top left stage.style.transform = 'scale(' + scaleToFit + ')'; Turn off transparency If your application uses canvas and doesn't need a transparent backdrop, set the alpha option to false when creating a drawing context with HTMLCanvasElement.getContext
(). This information can be used internally by the browser to optimize rendering. var ctx = canvas.getContext('2d', { alpha: false }); More tips Batch canvas calls together. For example, draw a polyline instead of multiple separate lines. Avoid unnecessary canvas state changes. Render screen differences only, not the whole new state. Avoid the shadowBlur property whenever possible. Avoid te...
...ar ctx = canvas.getContext('2d', { alpha: false }); More tips Batch canvas calls together. For example, draw a polyline instead of multiple separate lines. Avoid unnecessary canvas state changes. Render screen differences only, not the whole new state. Avoid the shadowBlur property whenever possible. Avoid text rendering whenever possible. Try different ways to clear the canvas (clearRect
() vs. fillRect
() vs. resizing the canvas). With animations, use window.requestAnimationFrame
() instead of window.setInterval
() . Be careful with heavy physics libraries. ...
Using channel messaging - Web APIs
ages to be sent to an <iframe>. We also have a paragraph which we will use later on to display confirmation messages that we will receive back from the <iframe>. ...
...t we will receive back from the <iframe>. ...
...frame.addEventListener("load", onLoad); function onLoad
() { // Listen for button clicks button.addEventListener('click', onClick); // Listen for messages on port1 port1.onmessage = onMessage; // Transfer port2 to the iframe iframe.contentWindow.postMessage('init', '*', [channel.port2]); } // Post a message on port1 when the button is clicked function onClick(e) { e.preventDefault
(); port1.postMessage(input.value); } // Handle messages received on port1 function onMessage(e) { output.innerHTML = e.data; input.value = ''; } We start off by creating a new message channel by using the MessageChannel
() constructor. When the IFrame has loaded, we register an onclick handler for our button and an onmessage handler for MessageChannel.port1. Finally we transfer MessageChann...
ChildNode - Web APIs
The ChildNode mixin contains methods and properties that are common to all types of Node objects that can have a parent. It's implemented by Element, DocumentType, and CharacterData objects. Properties There are neither inherited, nor specific properties. Methods There are no inherited methods. ChildNode.remove
() Removes this ChildNode from the children list of its parent. ChildNode.before
() Inserts a set of Node or DOMString objects in the children list of this ChildNode's parent, just before this ChildNode. DOMString objects are inserted as equivalent Text nodes. ChildNode.after
() Inserts a set of Node or DOMString objects in the children list of this ChildNode's parent, just after this ChildNode. DOMString objects are inserted as equivalent Text nodes. ChildNode.replac...
...DOMString objects are inserted as equivalent Text nodes. ...
...uivalent Text nodes. Specifications Specification Status Comment DOMThe definition of 'ChildNode' in that specification. Living Standard Split the ElementTraversal interface in ParentNode and ChildNode. previousElementSibling and nextElementSibling are now defined on the latter. The CharacterData and DocumentType implemented the new interfaces. Added the remove
(), before
(), after
() and replaceWith
() methods. Element Traversal SpecificationThe definition of 'ElementTraversal' in that specification. Obsolete Added the initial definition of its properties to the ElementTraversal pure interface and use it on Element. Polyfill External on GitHub: childNode.js ...
Client - Web APIs
Properties Client.id Read only The universally unique identifier of the client as a string. Client.type Read only The client's type as a string. It can be "window", "worker", or "sharedworker". ...
... Properties Client.id Read only The universally unique identifier of the client as a string. Client.type Read only The client's type as a string. It can be "window", "worker", or "sharedworker". ...
... Properties Client.id Read only The universally unique identifier of the client as a string. Client.type Read only The client's type as a string. It can be "window", "worker", or "sharedworker". ...
ClipboardItem.types - Web APIs
The read-only types property of the ClipboardItem interface returns an Array of MIME types available within the ClipboardItem Syntax var types = clipboardItem.types; Value An Array of available MIME types. Examples In the below example, we're returning all items on the clipboard via the clipboard.read
() method. Then checking the types property for available types before utilizing the ClipboardItem.getType
() method to return the Blob object. ...
... Value An Array of available MIME types. Examples In the below example, we're returning all items on the clipboard via the clipboard.read
() method. Then checking the types property for available types before utilizing the ClipboardItem.getType
() method to return the Blob object. If no clipboards contents is found for the specified type, an error is returned. ...
...ple, we're returning all items on the clipboard via the clipboard.read
() method. Then checking the types property for available types before utilizing the ClipboardItem.getType
() method to return the Blob object. If no clipboards contents is found for the specified type, an error is returned. ...
CredentialsContainer - Web APIs
The CredentialsContainer interface of the the Credential Management API 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 Navigator.credentials. Properties None. Event handlers None. ...
...in or sign out happen. This interface is accessible from Navigator.credentials. Properties None. Event handlers None. Methods CredentialsContainer.create
()Secure context Returns a Promise that resolves with a new Credential instance based on the provided options, or null if no Credential object can be created. In exceptional circumstances, the Promise may reject. CredentialsContainer.get
()Secure context Returns a Promise that resolves with the Credential instance that matches the provided parameters. CredentialsContainer.preventSilentAccess
()Secure context Sets a flag that specifies whether automatic log in is allowed for future visits to the current origin, then returns an empty Promise. For example, you might call this, after a user signs out of a website to ensure that he/she...
...ialsContainer.preventSilentAccess
()Secure context Sets a flag that specifies whether automatic log in is allowed for future visits to the current origin, then returns an empty Promise. For example, you might call this, after a user signs out of a website to ensure that he/she isn't automatically signed in on the next site visit. Earlier versions of the spec called this method requireUserMediation
(). See Browser compatibility for support details. CredentialsContainer.store
()Secure context Stores a set of credentials for a user, inside a provided Credential instance and returns that instance in a Promise. Examples // TBD Specifications Specification Status Comment Credential Management Level 1 Working Draft Initial definition. Web Authentication: ...
CryptoKey - Web APIs
The CryptoKey interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods generateKey
(), deriveKey
(), importKey
(), or unwrapKey
(). For security reasons, the CryptoKey interface can only be used in a secure context. Properties CryptoKey.type String which may take one of the following values: "secret": This key is a secret key for use with a symmetric algorithm. "private": This key is the private half of an asymmetric algorithm's CryptoKeyPair. "public": This key is the public half of an asymmetric algorithm's CryptoKeyPair. CryptoKey.extractable Boolean indicating whether or not the key may be extracted using SubtleCrypto.exportKey
() or SubtleCrypto.wrapKey
(). true: The key may be extracted. false The ...
... "private": This key is the private half of an asymmetric algorithm's CryptoKeyPair. "public": This key is the public half of an asymmetric algorithm's CryptoKeyPair. CryptoKey.extractable Boolean indicating whether or not the key may be extracted using SubtleCrypto.exportKey
() or SubtleCrypto.wrapKey
(). true: The key may be extracted. false The key may not be extracted. exportKey
() or wrapKey
() will throw an exception if used to extract this key. CryptoKey.algorithm An object describing the algorithm for which this key can be used and any associated extra parameters. AesKeyGenParams if the algorithm is any of the AES variants. RsaHashedKeyGenParams if the algorithm is any of the RSA variants. EcKeyGenParams if the algorithm is any of the EC variants. Hmac...
... messages. "verify": The key may be used to verify signatures. "deriveKey": The key may be used in deriving a new key. "deriveBits": The key may be used in deriving bits. "wrapKey": The key may be used to wrap a key. "unwrapKey": The key may be used to unwrap a key. Examples The examples for SubtleCrypto methods often use CryptoKey objects. For example: SubtleCrypto.generateKey
() SubtleCrypto.deriveKey
() SubtleCrypto.importKey
() SubtleCrypto.exportKey
() SubtleCrypto.wrapKey
() SubtleCrypto.unwrapKey
() SubtleCrypto.encrypt
() SubtleCrypto.decrypt
() SubtleCrypto.sign
() SubtleCrypto.verify
() Specifications Specification Status Comment Web Cryptography APIThe definition of 'CryptoKey' in that specification. Recommendation Initial defini...
DOMImplementation - Web APIs
The DOMImplementation interface represents an object providing methods which are not dependent on any particular document. Such an object is returned by the Document.implementation property. Property This interface has no specific property and doesn't inherit any. Methods No inherited method. DOMImplementation.createDocument
() Creates and returns an XMLDocument. DOMImplementation.createDocumentType
() Creates and returns a DocumentType. DOMImplementation.createHTMLDocument
() Creates and returns an HTML Document. DOMImplementation.hasFeature
() Returns a Boolean indicating if a given feature is supported or not. This function is unreliable and kept for compatibility purpose alone: except for SVG-related queries, it always returns true. Old browsers are very inconsistent in their ...
... if a given feature is supported or not. This function is unreliable and kept for compatibility purpose alone: except for SVG-related queries, it always returns true. Old browsers are very inconsistent in their behavior. Specifications Specification Status Comment DOMThe definition of 'DOMImplementation' in that specification. Living Standard Removed the getFeature
() method. Added the createHTMLDocument
() method. Modified the return type of createDocument
() from Document to XMLDocument. Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'DOMImplementation' in that specification. Obsolete Added the getFeature
() method (never implemented by any user agent). Document Object Model (DOM) Level 2 Core Specificati...
...rom Document to XMLDocument. Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'DOMImplementation' in that specification. Obsolete Added the getFeature
() method (never implemented by any user agent). Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'DOMImplementation' in that specification. Obsolete Added the createDocument
() and createDocumentType
() methods. Document Object Model (DOM) Level 1 SpecificationThe definition of 'DOMImplementation' in that specification. Obsolete Initial definition. ...
DOMPoint - Web APIs
ee dimensions, as well as an optional perspective value. DOMPoint is based on DOMPointReadOnly but allows its properties' values to be changed. In general, a positive x component represents a position to the right of the origin, a positive y component is downward from the origin, and a positive z component extends outward from the screen (in other words, toward the user). Constructor DOMPoint
() Creates and returns a new DOMPoint object given the values of zero or more of its coordinate components and optionally the w perspective value. You can also use an existing DOMPoint or DOMPointReadOnly or a DOMPointInit dictionary to create a new point by calling the DOMPoint.fromPoint
() static method. Methods DOMPoint inherits methods from its parent, DOMPointReadOnly. Static methods ...
...ns a new DOMPoint object given the values of zero or more of its coordinate components and optionally the w perspective value. You can also use an existing DOMPoint or DOMPointReadOnly or a DOMPointInit dictionary to create a new point by calling the DOMPoint.fromPoint
() static method. Methods DOMPoint inherits methods from its parent, DOMPointReadOnly. Static methods DOMPoint.fromPoint
() Creates a new mutable DOMPoint object given an existing point (or a DOMPointInit dictionary) which provides the values for its properties. Properties DOMPoint inherits properties from its parent, DOMPointReadOnly. DOMPoint.x The x coordinate of the DOMPoint. DOMPoint.y The y coordinate of the DOMPoint. DOMPoint.z The z coordinate of the DOMPoint. DOMPoint.w The perspective value of ...
...y coordinate of the DOMPoint. DOMPoint.z The z coordinate of the DOMPoint. DOMPoint.w The perspective value of the DOMPoint. Examples In the WebXR Device API, DOMPointReadOnly values are used to represent positions and orientations. In the following snippet, the pose of the XR device (such as a VR headset or phone with AR capabilities) can be retrieved by calling using XRFrame.getViewerPose
() during an XRSession animation frame, then accessing the resulting XRPose's transform property, which contains two DOMPointReadOnly attributes: position as a vector and orientation as a quaternion. function onXRFrame(time, xrFrame) { let viewerPose = xrFrame.getViewerPose(xrReferenceSpace); if (viewerPose) { let position = viewerPose.transform.position; let orientation = viewerPose.t...
DOMPointInit - Web APIs
Properties DOMPointInit.x An unrestricted floating-point value indicating the x-coordinate of the point in space. This is generally the horizontal coordinate, with positive values being to the right and negative values to the left. ...
... Properties DOMPointInit.x An unrestricted floating-point value indicating the x-coordinate of the point in space. This is generally the horizontal coordinate, with positive values being to the right and negative values to the left. ...
...r to the user. This same code will work to create a DOMPointReadOnly object; just change the interface name in the code. const pointDesc = { x: window.screenX, y: window.screenY, z: 5.0 }; const windTopLeft = DOMPoint.fromPoint(pointDesc) Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'DOMPointReadOnly.fromPoint
()' in that specification. Candidate Recommendation Initial definition ...
DataTransferItem - Web APIs
eration, each drag event has a dataTransfer property which contains a list of drag data items. Each item in the list is a DataTransferItem object. This interface has no constructor. Properties DataTransferItem.kind Read only The kind of drag data item, string or file. DataTransferItem.type Read only The drag data item's type, typically a MIME type. Methods DataTransferItem.getAsFile
() Returns the File object associated with the drag data item (or null if the drag item is not a file). DataTransferItem.getAsString
() Invokes the specified callback with the drag data item string as its argument. DataTransferItem.webkitGetAsEntry
() Returns an object based on FileSystemEntry representing the selected file's entry in its file system. This will generally be either a FileSystemF...
... ...
...L Living StandardThe definition of 'DataTransferItem' in that specification. Living Standard Initial definition. HTML 5.1The definition of 'DataTransferItem' in that specification. Recommendation W3C snapshot of WHATWG File and Directory Entries APIThe definition of 'DataTransferItem.webkitGetAsEntry
()' in that specification. Draft Definition of webkitGetAsEntry
() as part of the File and Directory Entries API. ...
DataTransferItemList.length - Web APIs
drag payload so the drop handler will // know which element to add to its tree var dataList = ev.dataTransfer.items; dataList.add(ev.target.id, "text/plain"); // Add some other items to the drag payload dataList.add("<p>... ...
... data[i].getAsString(function (s){ console.log("... Drop: HTML = " + s); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI data[i].getAsString(function (s){ console.log("... ...
...i].getAsString(function (s){ console.log("... ...
DedicatedWorkerGlobalScope: message event - Web APIs
The message event is fired on a DedicatedWorkerGlobalScope object when the worker receives a message from its parent (i.e. when the parent sends a message using Worker.postMessage
()). ...
...ge event is fired on a DedicatedWorkerGlobalScope object when the worker receives a message from its parent (i.e. when the parent sends a message using Worker.postMessage
()). ...
...rface MessageEvent Event handler property onmessage Examples This code creates a new worker and sends it a message using Worker.postMessage
(): const worker = new Worker("static/scripts/worker.js"); worker.addEventListener('message', (event) => { console.log(`Received message from worker: ${event.data}`) }); The worker can listen for this message using addEventListener
(): // inside static/scripts/worker.js self.addEventListener('message', (event) => { console.log(`Received message from parent: ${event.data}`); }); Alternatively, it could listen using the onmessage event handler property: // static/scripts/worker.js self.onmessage = (event) => { console.log(`Received message from parent: ${event.data}`); }; Specifications Specification ...
DisplayMediaStreamConstraints.video - Web APIs
This value may simply be a Boolean, where true specifies that a default selection of input source be made (typically the entire display area of the device in use, spanning every screen in a multiple screen configuration). Since a video track must always be included, a value of false results in a TypeError exception being thrown. ...
... Syntax displayMediaStreamConstraints.video = allowVideoFlag; displayMediaStreamConstraints.video = mediaTrackConstraints; displayMediaStreamConstraints = { video: allowVideoFlag | mediaTrackConstraints; } Value The value may be either a Boolean or a MediaTrackConstraints object. If a Boolean is specified, a value of true (the default) indicates that the stream returned by getDisplayMedia
() should be in whatever format the user agent feels is best. A value of false is not permitted and will throw a TypeError. If a MediaTrackConstraints object is given instead, the video track will be processed to match the settings given in the constraints object. Constraints specific to screen sharing These constraints apply to MediaTrackConstraints objects specified as part of the DisplayMediaS...
... of false is not permitted and will throw a TypeError. If a MediaTrackConstraints object is given instead, the video track will be processed to match the settings given in the constraints object. Constraints specific to screen sharing These constraints apply to MediaTrackConstraints objects specified as part of the DisplayMediaStreamConstraints object's video property when using getDisplayMedia
() to obtain a stream for screen sharing. cursor A ConstrainDOMString which specifies whether or not to include the mouse cursor in the generated track, and if so, whether or not to hide it while not moving. The value may be a single one of the following strings, or an array of them to allow the browser flexibility in deciding what to do about the cursor. always The mouse is always visi...
Document: DOMContentLoaded event - Web APIs
'DOM fully loaded and parsed'); }); for( let i = 0; i < 1000000000; i++) {} // This synchronous script is going to delay parsing of the DOM, // so the DOMContentLoaded event is going to launch later. </script> Checking whether loading is already complete DOMContentLoaded may fire before your script has a chance to run, so it is wise to check before adding a listener. ...
...oading is already complete DOMContentLoaded may fire before your script has a chance to run, so it is wise to check before adding a listener. ...
...; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } JS const log = document.querySelector('.event-log-contents'); const reload = document.querySelector('#reload'); reload.addEventListener('click',
() => { log.textContent =''; window.setTimeout(
() => { window.location.reload(true); }, 200); }); window.addEventListener('load', (event) => { log.textContent = log.textContent + 'load\n'; }); document.addEventListener('readystatechange', (event) => { log.textContent = log.textContent + `readystate: ${document.readyState}\n`; }); document.addEventListener('DOMContentLoaded', (...
Document: gotpointercapture event - Web APIs
The gotpointercapture event is fired when an element captures a pointer using setPointerCapture
(). Bubbles No Cancelable No Interface PointerEvent Event handler property ongotpointercapture Examples This example gets a <p> element and listens for the gotpointercapture event. It then calls setPointerCapture
() on the element on a pointerdown event, which will trigger gotpointercapture. ...
...celable No Interface PointerEvent Event handler property ongotpointercapture Examples This example gets a <p> element and listens for the gotpointercapture event. It then calls setPointerCapture
() on the element on a pointerdown event, which will trigger gotpointercapture. ...
...tercapture. ...
Document.lastModified - Web APIs
tring, lastModified cannot easily be used for comparing the modification dates of documents. ...
...(See: Bug 4363 - document.lastModified returns date in UTC time, but should return it in local time) If you want to know whether an exte...
... if (isFinite(nLastVisit)) { alert("This page has been changed!"); } } Note: WebKit returns the time string in UTC; Gecko and Internet Explorer return a time in the local timezone. (See: Bug 4363 - document.lastModified returns date in UTC time, but should return it in local time) If you want to know whether an external page has changed, please read this paragraph about the XMLHttpRequest
() API. Specifications Specification Status Comment HTML Living StandardThe definition of 'document.lastModified' in that specification. Living Standard ...
Document.onfullscreenerror - Web APIs
The Document.onfullscreenerror property is an event handler for the fullscreenerror event that is sent to the document when it fails to transition into full-screen mode after a prior call to Element.requestFullscreen
(). Syntax targetDocument.onfullscreenerror = fullscreenErrorHandler; Value An event handler for the fullscreenerror event. Example This example attempts to call requestFullscreen
() outside of an event handler. ...
...r for the fullscreenerror event that is sent to the document when it fails to transition into full-screen mode after a prior call to Element.requestFullscreen
(). Syntax targetDocument.onfullscreenerror = fullscreenErrorHandler; Value An event handler for the fullscreenerror event. Example This example attempts to call requestFullscreen
() outside of an event handler. Since requestFullscreen
() can only be called in response to user action, for security reasons, this will fail, causing the fullscreenerror to be sent to the document. ...
... attempts to call requestFullscreen
() outside of an event handler. Since requestFullscreen
() can only be called in response to user action, for security reasons, this will fail, causing the fullscreenerror to be sent to the document. document.onfullscreenerror = function ( event ) { displayWarning("Unable to switch into full-screen mode."); }; //.... document.documentElement.requestFullscreen
(); Specifications Specification Status Comment Fullscreen APIThe definition of 'onfullscreenerror' in that specification. Living Standard Initial definition. ...
Document.readyState - Web APIs
"span"); span.textContent = "A <span> element."; document.body.appendChild(span); break; case "complete": // The page is fully loaded. ...
...appendChild(span); break; case "complete": // The page is fully loaded. ...
...ment.styleSheets[0].cssRules[0].cssText); break; } readystatechange as an alternative to DOMContentLoaded event // Alternative to DOMContentLoaded event document.onreadystatechange = function
() { if (document.readyState === 'interactive') { initApplication
(); } } readystatechange as an alternative to load event // Alternative to load event document.onreadystatechange = function
() { if (document.readyState === 'complete') { initApplication
(); } } readystatechange as event listener to insert or modify the DOM before DOMContentLoaded document.addEventListener('readystatechange', event => { if (event.target.readyState === 'interactive') { initLoader
(); } else if (event.target.readyState === 'complete') { initApp
(); } }); Specifications S...
DocumentOrShadowRoot - Web APIs
rns the element set as the target for mouse events while the pointer is locked. It returns null if lock is pending, the pointer is unlocked, or if the target is in another document. DocumentOrShadowRoot.styleSheetsRead only Returns a StyleSheetList of CSSStyleSheet objects for stylesheets explicitly linked into, or embedded in a document. ...
...other document. DocumentOrShadowRoot.styleSheetsRead only Returns a StyleSheetList of CSSStyleSheet objects for stylesheets explicitly linked into, or embedded in a document. Methods DocumentOrShadowRoot.caretPositionFromPoint
() Returns a CaretPosition object containing the DOM node containing the caret, and caret's character offset within that node. DocumentOrShadowRoot.elementFromPoint
() Returns the topmost element at the specified coordinates. DocumentOrShadowRoot.elementsFromPoint
() Returns an array of all elements at the specified coordinates. ...
...hadowRoot.caretPositionFromPoint
() Returns a CaretPosition object containing the DOM node containing the caret, and caret's character offset within that node. DocumentOrShadowRoot.elementFromPoint
() Returns the topmost element at the specified coordinates. DocumentOrShadowRoot.elementsFromPoint
() Returns an array of all elements at the specified coordinates. DocumentOrShadowRoot.getSelection
() Returns a Selection object representing the range of text selected by the user, or the current position of the caret. DocumentOrShadowRoot.nodeFromPoint
() Returns the topmost node at the specified coordinates. DocumentOrShadowRoot.nodesFromPoint
() Returns an array of all nodes at the specified coordinates. Specifications Specification Status Comment Shadow ...
DynamicsCompressorNode.attack - Web APIs
The attack property of the DynamicsCompressorNode interface is a k-rate AudioParam representing the amount of time, in seconds, required to reduce the gain by 10 dB. It defines how quickly the signal is adapted when its volume is increased. The attack property's default value is 0.003 and it can be set between 0 and 1. Syntax var audioCtx = new AudioContext
(); var compressor = audioCtx.createDynamicsCompressor
(); compressor.attack.value = 0; Value An AudioParam. Note: Though the AudioParam returned is read-only, the value it represents is not. Example The below code demonstrates a simple usage of createDynamicsCompressor
() to add compression to an audio track. For a more complete example, have a look at our basic Compressor example (view the source code). // Create a MediaElem...
...rates a simple usage of createDynamicsCompressor
() to add compression to an audio track. For a more complete example, have a look at our basic Compressor example (view the source code). ...
...ValueAtTime(-50, audioCtx.currentTime); compressor.knee.setValueAtTime(40, audioCtx.currentTime); compressor.ratio.setValueAtTime(12, audioCtx.currentTime); compressor.attack.setValueAtTime(0, audioCtx.currentTime); compressor.release.setValueAtTime(0.25, audioCtx.currentTime); // connect the AudioBufferSourceNode to the destination source.connect(audioCtx.destination); button.onclick = function
() { var active = button.getAttribute('data-active'); if(active == 'false') { button.setAttribute('data-active', 'true'); button.innerHTML = 'Remove compression'; source.disconnect(audioCtx.destination); source.connect(compressor); compressor.connect(audioCtx.destination); } else if(active == 'true') { button.setAttribute('data-active', 'false'); button.innerHTML =...
DynamicsCompressorNode.knee - Web APIs
The knee property of the DynamicsCompressorNode interface is a k-rate AudioParam containing a decibel value representing the range above the threshold where the curve smoothly transitions to the compressed portion. The knee property's default value is 30 and it can be set between 0 and 40. Syntax var audioCtx = new AudioContext
(); var compressor = audioCtx.createDynamicsCompressor
(); compressor.knee.value = 40; Value An AudioParam. Note: Though the AudioParam returned is read-only, the value it represents is not. Example The below code demonstrates a simple usage of createDynamicsCompressor
() to add compression to an audio track. For a more complete example, have a look at our basic Compressor example (view the source code). // Create a MediaElementAudioSourceNode // Feed th...
...rates a simple usage of createDynamicsCompressor
() to add compression to an audio track. For a more complete example, have a look at our basic Compressor example (view the source code). ...
...ValueAtTime(-50, audioCtx.currentTime); compressor.knee.setValueAtTime(40, audioCtx.currentTime); compressor.ratio.setValueAtTime(12, audioCtx.currentTime); compressor.attack.setValueAtTime(0, audioCtx.currentTime); compressor.release.setValueAtTime(0.25, audioCtx.currentTime); // connect the AudioBufferSourceNode to the destination source.connect(audioCtx.destination); button.onclick = function
() { var active = button.getAttribute('data-active'); if(active == 'false') { button.setAttribute('data-active', 'true'); button.innerHTML = 'Remove compression'; source.disconnect(audioCtx.destination); source.connect(compressor); compressor.connect(audioCtx.destination); } else if(active == 'true') { button.setAttribute('data-active', 'false'); button.innerHTML =...
DynamicsCompressorNode.ratio - Web APIs
The ratio property of the DynamicsCompressorNode interface Is a k-rate AudioParam representing the amount of change, in dB, needed in the input for a 1 dB change in the output. The ratio property's default value is 12 and it can be set between 1 and 20. Syntax var audioCtx = new AudioContext
(); var compressor = audioCtx.createDynamicsCompressor
(); compressor.ratio.value = 12; Value An AudioParam. Note: Though the AudioParam returned is read-only, the value it represents is not. Example The below code demonstrates a simple usage of createDynamicsCompressor
() to add compression to an audio track. For a more complete example, have a look at our basic Compressor example (view the source code). // Create a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it var sourc...
...rates a simple usage of createDynamicsCompressor
() to add compression to an audio track. For a more complete example, have a look at our basic Compressor example (view the source code). ...
...ValueAtTime(-50, audioCtx.currentTime); compressor.knee.setValueAtTime(40, audioCtx.currentTime); compressor.ratio.setValueAtTime(12, audioCtx.currentTime); compressor.attack.setValueAtTime(0, audioCtx.currentTime); compressor.release.setValueAtTime(0.25, audioCtx.currentTime); // connect the AudioBufferSourceNode to the destination source.connect(audioCtx.destination); button.onclick = function
() { var active = button.getAttribute('data-active'); if(active == 'false') { button.setAttribute('data-active', 'true'); button.innerHTML = 'Remove compression'; source.disconnect(audioCtx.destination); source.connect(compressor); compressor.connect(audioCtx.destination); } else if(active == 'true') { button.setAttribute('data-active', 'false'); button.innerHTML =...
DynamicsCompressorNode.release - Web APIs
The release property of the DynamicsCompressorNode interface Is a k-rate AudioParam representing the amount of time, in seconds, required to increase the gain by 10 dB. It defines how quick the signal is adapted when its volume is reduced. The release property's default value is 0.25 and it can be set between 0 and 1. Syntax var audioCtx = new AudioContext
(); var compressor = audioCtx.createDynamicsCompressor
(); compressor.release.value = 0.25; Value An AudioParam. Note: Though the AudioParam returned is read-only, the value it represents is not. Example The below code demonstrates a simple usage of createDynamicsCompressor
() to add compression to an audio track. For a more complete example, have a look at our basic Compressor example (view the source code). // Create a MediaE...
...rates a simple usage of createDynamicsCompressor
() to add compression to an audio track. For a more complete example, have a look at our basic Compressor example (view the source code). ...
...ValueAtTime(-50, audioCtx.currentTime); compressor.knee.setValueAtTime(40, audioCtx.currentTime); compressor.ratio.setValueAtTime(12, audioCtx.currentTime); compressor.attack.setValueAtTime(0, audioCtx.currentTime); compressor.release.setValueAtTime(0.25, audioCtx.currentTime); // connect the AudioBufferSourceNode to the destination source.connect(audioCtx.destination); button.onclick = function
() { var active = button.getAttribute('data-active'); if(active == 'false') { button.setAttribute('data-active', 'true'); button.innerHTML = 'Remove compression'; source.disconnect(audioCtx.destination); source.connect(compressor); compressor.connect(audioCtx.destination); } else if(active == 'true') { button.setAttribute('data-active', 'false'); button.innerHTML =...
DynamicsCompressorNode.threshold - Web APIs
The threshold property of the DynamicsCompressorNode interface is a k-rate AudioParam representing the decibel value above which the compression will start taking effect. The threshold property's default value is -24 and it can be set between -100 and 0. Syntax var audioCtx = new AudioContext
(); var compressor = audioCtx.createDynamicsCompressor
(); compressor.threshold.value = -50; Value An AudioParam. Note: Though the AudioParam returned is read-only, the value it represents is not. Example The below code demonstrates a simple usage of createDynamicsCompressor
() to add compression to an audio track. For a more complete example, have a look at our basic Compressor example (view the source code). // Create a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it var...
...rates a simple usage of createDynamicsCompressor
() to add compression to an audio track. For a more complete example, have a look at our basic Compressor example (view the source code). ...
...ValueAtTime(-50, audioCtx.currentTime); compressor.knee.setValueAtTime(40, audioCtx.currentTime); compressor.ratio.setValueAtTime(12, audioCtx.currentTime); compressor.attack.setValueAtTime(0, audioCtx.currentTime); compressor.release.setValueAtTime(0.25, audioCtx.currentTime); // connect the AudioBufferSourceNode to the destination source.connect(audioCtx.destination); button.onclick = function
() { var active = button.getAttribute('data-active'); if(active == 'false') { button.setAttribute('data-active', 'true'); button.innerHTML = 'Remove compression'; source.disconnect(audioCtx.destination); source.connect(compressor); compressor.connect(audioCtx.destination); } else if(active == 'true') { button.setAttribute('data-active', 'false'); button.innerHTML =...
EXT_blend_minmax - Web APIs
The EXT_blend_minmax extension is part of the WebGL API and extends blending capabilities by adding two new blend equations: the minimum or maximum color components of the source and destination colors. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is only available to WebGL1 contexts. ...
... ext.MAX_EXT Produces the maximum color components of the source and destination colors. ...
...tensions in the WebGL tutorial. Availability: This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default. The constants in WebGL2 are gl.MIN and gl.MAX. Constants This extension adds two new constants, which can be used in WebGLRenderingContext.blendEquation
() and WebGLRenderingContext.blendEquationSeparate
(): ext.MIN_EXT Produces the minimum color components of the source and destination colors. ext.MAX_EXT Produces the maximum color components of the source and destination colors. Examples var ext = gl.getExtension('EXT_blend_minmax'); gl.blendEquation(ext.MIN_EXT); gl.blendEquation(ext.MAX_EXT); gl.blendEquationSeparate(ext.MIN_EXT, ext.MAX_EXT); Specifications Specification ...
EXT_float_blend - Web APIs
The WebGL API's EXT_float_blend extension allows blending and draw buffers with 32-bit floating-point components. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is available to both, WebGL1 and WebGL2 contexts. However, to use it, you need to enable the use of 32-bit floating-point draw buffers by enabling the extension WEBGL_color_buffer_float (for WebGL1) or EXT_color_buffer_float (for WebGL2). Doing so automatically enables EXT_float_blend as well. With this extension enabled, calling drawArrays
() or drawElements
() with blending enabled and a draw buffer with 32-bit floating-point components will no longer result in an INVALID_OPERATION error. ...
... any one or more of EXT_color_buffer_float, OES_texture_float, or WEBGL_color_buffer_float are enabled. This ensures that content written before EXT_float_blend was exposed by WebGL will function as expected. ...
... will function as expected. ...
EXT_texture_filter_anisotropic - Web APIs
The EXT_texture_filter_anisotropic extension is part of the WebGL API and exposes two constants for anisotropic filtering (AF). AF improves the quality of mipmapped texture access when viewing a textured primitive at an oblique angle. Using just mipmapping, these lookups have a tendency to average to grey. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. ...
...ipmapping, these lookups have a tendency to average to grey. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is available to both, WebGL1 and WebGL2 contexts. Constants ext.MAX_TEXTURE_MAX_ANISOTROPY_EXT This is the pname argument to the gl.getParameter
() call, and it returns the maximum available anisotropy. ext.TEXTURE_MAX_ANISOTROPY_EXT This is the pname argument to the gl.getTexParameter
() and gl.texParameterf
() / gl.texParameteri
() calls and sets the desired maximum anisotropy for a texture. ...
...texts. Constants ext.MAX_TEXTURE_MAX_ANISOTROPY_EXT This is the pname argument to the gl.getParameter
() call, and it returns the maximum available anisotropy. ext.TEXTURE_MAX_ANISOTROPY_EXT This is the pname argument to the gl.getTexParameter
() and gl.texParameterf
() / gl.texParameteri
() calls and sets the desired maximum anisotropy for a texture. ...
EffectTiming.direction - Web APIs
The value of direction corresponds directly to AnimationEffectTimingReadOnly.direction in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
...The value of direction corresponds directly to AnimationEffectTimingReadOnly.direction in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
...The value of direction corresponds directly to AnimationEffectTimingReadOnly.direction in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
EffectTiming.iterationStart - Web APIs
The value of iterationStart corresponds directly to AnimationEffectTimingReadOnly.iterationStart in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
...The value of iterationStart corresponds directly to AnimationEffectTimingReadOnly.iterationStart in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
...The value of iterationStart corresponds directly to AnimationEffectTimingReadOnly.iterationStart in timing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. ...
Element.attributes - Web APIs
.attributes; Enumerating elements attributes Numerical indexing is useful for going through all of an element's attributes. The following example runs through the attribute nodes for the element in the document with id "paragraph", and prints each attribute's value. ...
...h id "paragraph", and prints each attribute's value. ...
... Living Standard From Document Object Model (DOM) Level 3 Core Specification, moved from Node to Element Document Object Model (DOM) Level 3 Core SpecificationThe def...
Element.scrollWidth - Web APIs
udes the element's padding, but not its border, margin or vertical scrollbar (if present). It can also include the width of pseudo-elements such as ::before or ::after. If the element's content can fit without a need for horizontal scrollbar, its scrollWidth is equal to clientWidth This property will round the value to an integer. If you need a fractional value, use element.getBoundingClientRect
(). Syntax var xScrollWidth = element.scrollWidth; xScrollWidth is the width of the content of element in pixels. Example <!DOCTYPE html> <html> <head> <title>Example</title> <style> div { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } #aDiv { width: 100px; } but...
... Working Draft Initial definition ...
... Working Draft Initial definition ...
Event.cancelable - Web APIs
e read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. If the event is not cancelable, then its cancelable property will be false and the event listener cannot stop the event from occurring. Event listeners that handle multiple kinds of events may want to check cancelable before invoking their preventDefault
() methods. Most browser-native events that can be canceled are the ones that result from the user interacting with the page. Canceling the click, scroll, or beforeunload events would prevent the user from clicking on something, scrolling the page, or navigating away from the page, respectively. Custom events created by other JavaScript code control if they can be canceled when they are created. ...
...ch is true if the event can be canceled. Example For example, browser vendors are proposing that the wheel event can only be canceled the first time the listener is called -- any following wheel events cannot be canceled. function preventScrollWheel(event) { if (typeof event.cancelable !== 'boolean' || event.cancelable) { // The event can be canceled, so we do so. event.preventDefault
(); } else { // The event cannot be canceled, so it is not safe // to call preventDefault
() on it. console.warn(`The following event couldn't be canceled:`); console.dir(event); } } document.addEventListener('wheel', preventScrollWheel); Notes Whether an event can be canceled or not is something that's determined when that event is initialized. To cancel an event, call the p...
...This keeps the implementation from executing the default action that is associated with the event. Specifications Specification Status Comment DOMThe definition of 'Event.cancelable' in that specification. ...
Event.defaultPrevented - Web APIs
Syntax var defaultWasPrevented = event.defaultPrevented; Value A Boolean, where true indicates that the default user agent action was prevented, and false indicates that it was not. Example This example logs attempts to visit links from two <a> elements. JavaScript is used to prevent the second link from working. ...
...ion was prevented, and false indicates that it was not. Example This example logs attempts to visit links from two <a> elements. JavaScript is used to prevent the second link from working. ...
... Living Standard ...
EventSource - Web APIs
Once the connection is opened, incoming messages from the server are delivered to your code in the form of events. If there is an event field in the incoming message, the triggered event is the same as the event field value. ...
... "Won't fix" in Chrome and Firefox. This limit is per browser + domain, so that means that you can open 6 SSE connections across all of the tabs to www.example1.com and another 6 SSE connections to www.example2.com. (from Stackoverflow). When using HTTP/2, the maximum number of simultaneous HTTP streams is negotiated between the server and the client (defaults to 100). Constructor EventSource
() Creates a new EventSource to handle receiving server-sent events from a specified URL, optionally in credentials mode. Properties This interface also inherits properties from its parent, EventTarget. EventSource.readyState Read only A number representing the state of the connection. Possible values are CONNECTING (0), OPEN (1), or CLOSED (2). EventSource.url Read only A DOMString repr...
...ent is dispatched on an EventSource object. EventSource.onmessage Is an EventHandler called when a message event is received, that is when a message is coming from the source. EventSource.onopen Is an EventHandler called when an open event is received, that is when the connection was just opened. Methods This interface also inherits methods from its parent, EventTarget. EventSource.close
() Closes the connection, if any, and sets the readyState attribute to CLOSED. If the connection is already closed, the method does nothing. Events error Fired when a connection to an event source failed to open. message Fired when data is received from an event source. open Fired when a connection to an event source has opened. Additionally, the event source itself may send messages wi...
FederatedCredential - Web APIs
ity provider. A federated identity provider is an entity that a website trusts to correctly authenticate a user, and that provides an API for that purpose. OpenID Connect is an example of a federated identity provider framework. In browsers that support it, an instance of this interface may be passed in the credential member of the init object for global fetch. Constructor FederatedCredential
() Creates a new FederatedCredential object. Properties Inherits properties from its ancestor, Credential. FederatedCredential.provider Read only Returns a USVString containing a credential's federated identity provider. FederatedCredential.protocol Read only Returns a DOMString containing a credential's federated identity protocol. Event handlers None. Methods None. Examples var ...
... credential's federated identity provider. FederatedCredential.protocol Read only Returns a DOMString containing a credential's federated identity protocol. Event handlers None. Methods None. Examples var cred = new FederatedCredential({ id: id, name: name, provider: 'https://account.google.com', iconURL: iconUrl }); // Store it navigator.credentials.store(cred) .then(function
() { // Do something else. }); Specifications Specification Status Comment Credential Management Level 1 Working Draft Initial definition. Browser compatibility The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request...
... WebView Android Full support 51Chrome Android Full support 51Firefox Android ? Opera Android ? Safari iOS ? Samsung Internet Android Full support 5.0FederatedCredential
() constructor Non-standardChrome Full support 51Edge Full support <=79Firefox ? IE ? Opera ? Safari ? WebView Android Full support 51Chrome Androi...
FetchEvent.preloadResponse - Web APIs
as 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
(). ...
...e.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. ...
...=> { event.respondWith(async function
() { // Respond from the cache if we can const cachedResponse = await caches.match(event.request); if (cachedResponse) return cachedResponse; // Else, use the preloaded response, if it's there const response = await event.preloadResponse; if (response) return response; // Else try the network. return fetch(event.request); }
()); }); Specifications Specification Status Comment Service WorkersThe definition of 'preloadResponse' in that specification. Working Draft Initial definition. ...
File - Web APIs
The File interface provides information about files and allows JavaScript in a web page to access their content. File objects are generally retrieved from a FileList object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile
() API on an HTMLCanvasElement. A File object is a specific kind of a Blob, and can be used in any context that a Blob can. In particular, FileReader, URL.createObjectURL
(), createImageBitmap
(), and XMLHttpRequest.send
() accept both Blobs and Files. See Using files from web applications for more information and examples. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: mi...
... Instance properties File.prototype.lastModified Read only Returns the last modified time of the file, in millisecond since the UNIX epoch (January 1st, 1970 at Midnight). File.prototype.lastModifiedDate Read only Returns the last modified Date of the file referenced by the File object. File.prototype.nameRead only Returns the name of the file refe...
...y Returns the size of the file in bytes. File.prototype.type Read only Returns the MIME type of the file. Instance methods The File interface doesn't define any methods, but inherits methods from the Blob interface: Blob.prototype.slice([start[, end[, contentType]]]) Returns a new Blob object containing the data in the specified range of bytes of the source Blob. Blob.prototype.stream
() Transforms the File into a ReadableStream that can be used to read the File contents. Blob.prototype.text
() Transforms the File into a stream and reads it to completion. It returns a promise that resolves with a USVString (text). Blob.prototype.arrayBuffer
() Transforms the File into a stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer. Specifications ...
FileReader: abort event - Web APIs
The abort event is fired when a read has been aborted: for instance because the program called FileReader.abort
(). Bubbles No Cancelable No Interface ProgressEvent Event handler property FileReader.onabort Examples Live example HTML <div class="example"> <div class="file-select"> <label for="avatar">Choose a profile picture:</label> <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg"> </div> <img src="" class="preview" height="200" alt="Image preview..."> <div class="event-log"> <label>Event log:</label> <textarea readonly class="event-log-contents"></textarea> </div> </div> CSS img.preview { margin: 1rem 0; } .event...
...elect { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } JS const fileInput = document.querySelector('input[type="file"]'); const preview = document.querySelector('img.preview'); const eventLog = document.querySelector('.event-log-contents'); const reader = new FileReader
(); function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addListeners(reader) { reader.addEventListener('loadstart', handleEvent); reader.addEventListener('load', handleEvent); reader.addEventListener('loadend', handleE...
..., handleEvent); reader.addEventListener('progress', handleEvent); reader.addEventListener('error', handleEvent); reader.addEventListener('abort', handleEvent); } function handleSelected(e) { eventLog.textContent = ''; const selectedFile = fileInput.files[0]; if (selectedFile) { addListeners(reader); reader.readAsDataURL(selectedFile); } reader.abort
(); } fileInput.addEventListener('change', handleSelected); Result Specifications Specification Status File API Working Draft ...
FileReader: error event - Web APIs
The error event is fired when the read failed due to an error (for example, because the file was not found or not readable). ...
...le). ...
...ror Examples const fileInput = document.querySelector('input[type="file"]'); const reader = new FileReader
(); function handleSelected(e) { const selectedFile = fileInput.files[0]; if (selectedFile) { reader.addEventListener('error',
() => { console.error(`Error occurred reading file: ${selectedFile.name}`); }); reader.addEventListener('load',
() => { console.error(`File: ${selectedFile.name} read successfully`); }); reader.readAsDataURL(selectedFile); } } fileInput.addEventListener('change', handleSelected); Specifications Specification Status File API Working Draft ...
FileSystem - Web APIs
This interface will not grant you access to the users filesystem. Instead you will have a "virtual drive" within the browser sandbox. If you want to gain access to the users filesystem you need to invoke the user by eg. ...
...n the browser sandbox. If you want to gain access to the users filesystem you need to invoke the user by eg. installing a Chrome extension. The relevant Chrome API can be found here. Basic concepts There are two ways to get access to a FileSystem object: You can directly ask for one representing a sandboxed file system created just for your web app directly by calling window.requestFileSystem
(). If that call is successful, it executes a callback handler, which receives as a parameter a FileSystem object describing the file system. You can get it from a file system entry object, through its filesystem property. Properties FileSystem.name Read only A USVString representing the file system's name. This name is unique among the entire list of exposed file systems. FileSystem.root ...
...It's not available for use in file or folder picker panels (such as when you use an <input> element with the HTMLInputElement.webkitdirectory attribute.Firefox Full support 50IE No support NoOpera Full support 15Prefixed Full support ...
FontFaceSet - Web APIs
, indicating a font-face set has started loading. FontFaceSet.onloadingdone An EventListener called whenever an event of type loadingdone is fired, indicating that a font face set has finished loading. FontFaceSet.onloadingerror An EventListener called whenever an event of type loadingerror is fired, indicating that an error occurred whilst loading a font-face set. ...
...FontFaceSet.onloadingdone An EventListener called whenever an event of type loadingdone is fired, indicating that a font face set has finished loading. FontFaceSet.onloadingerror An EventListener called whenever an event of type loadingerror is fired, indicating that an error occurred whilst loading a font-face set. Methods FontFaceSet.add
() Adds a font to the font set. ...
... font face set has finished loading. FontFaceSet.onloadingerror An EventListener called whenever an event of type loadingerror is fired, indicating that an error occurred whilst loading a font-face set. Methods FontFaceSet.add
() Adds a font to the font set. FontFaceSet.check
() A Boolean that indicates whether a font is loaded, but doesn't initiate a load when it isn't. FontFaceSet.clear
() Removes all manually-added fonts from the font set. CSS-connected fonts are unaffected. FontFaceSet.delete
() Removes a manually-added font from the font set. CSS-connected fonts are unaffected. FontFaceSet.load
() Returns a Promise which resolves to a list of font-faces for a requested font. Specifications Specification Status Comment CSS Font Loading Module Level 3...
FormDataEvent.formData - Web APIs
taEvent interface contains the FormData object representing the data contained in the form when the event was fired. Syntax formData = formDataEvent.formData Returns A FormData object. ...
... Living Standard ...
... Living Standard ...
FullscreenOptions.navigationUI - Web APIs
Syntax let fullscreenOptions = { navigationUI: value }; Value The value of the navigationUI property must be one of the following strings. The default is "auto". "hide" The browser's navigation interface will be hidden and the entire dimensions of the screen will be allocated to the display of the element. ...
...l present page navigation controls and possibly other user interface; the dimensions of the element (and the perceived size of the screen) will be clamped to leave room for this user interface. "auto" The browser will choose which of the above settings to apply. This is the default value. Example In this example, the entire document is placed into full-screen mode by calling requestFullscreen
() on the document's Document.documentElement, which is the document's root <html> element. let elem = document.documentElement; elem.requestFullscreen({ navigationUI: "show" }).then({}).catch(err => { alert(`An error occurred while trying to switch into full-screen mode: ${err.message} (${err.name})`); }); The promise's resolve handler does nothing, but if the promise is rejected, an error me...
...tElement, which is the document's root <html> element. let elem = document.documentElement; elem.requestFullscreen({ navigationUI: "show" }).then({}).catch(err => { alert(`An error occurred while trying to switch into full-screen mode: ${err.message} (${err.name})`); }); The promise's resolve handler does nothing, but if the promise is rejected, an error message is displayed by calling alert
(). Specifications Specification Status Comment Fullscreen APIThe definition of 'FullscreenOptions' in that specification. Living Standard Initial definition ...
Gamepad.buttons - Web APIs
the button values are stores as an array of double values, whereas in Firefox Navigator.getGamepads doesn't need a prefix, and the button values are stored as an array of GamepadButton objects; it is the GamepadButton.value or GamepadButton.pressed properties of these we need to access, depending on what type of buttons they are. In this simple example I've just allowed either. ...
...vigator.getGamepads doesn't need a prefix, and the button values are stored as an array of GamepadButton objects; it is the GamepadButton.value or GamepadButton.pressed properties of these we need to access, depending on what type of buttons they are. In this simple example I've just allowed either. ...
...s they are. In this simple example I've just allowed either. ...
GamepadButton - Web APIs
the button values are stored as an array of double values, whereas in Firefox Navigator.getGamepads doesn't need a prefix, and the button values are stored as an array of GamepadButton objects; it is the GamepadButton.value or GamepadButton.pressed properties of these we need to access, depending on what type of buttons they are. In this simple example I've just allowed either. ...
...vigator.getGamepads doesn't need a prefix, and the button values are stored as an array of GamepadButton objects; it is the GamepadButton.value or GamepadButton.pressed properties of these we need to access, depending on what type of buttons they are. In this simple example I've just allowed either. ...
...s they are. In this simple example I've just allowed either. ...
GeolocationCoordinates.longitude - Web APIs
ing coordinates once they're returned. JavaScript The JavaScript code below creates an event listener so that when the user clicks on a button, the location information is retrieved and displayed. ...
...This is an asynchronous request, so we provide a callback which receives as in put a GeolocationPosition object describing the determined position. From the GeolocationPosition object, we ...
...Fixed(2); }); }); After setting up variables to more conveniently reference the button element and the two elements into which the latitude and logitude will be drawn, the event listener is established by calling addEventListener
() on the <button> element. When the user clicks the button, we'll fetch and display the location information. Upon receiving a click event, we call getCurrentPosition
() to request the device's current position. This is an asynchronous request, so we provide a callback which receives as in put a GeolocationPosition object describing the determined position. From the GeolocationPosition object, we obtain the user's latitude and longitude using position.coords.latitude and position.coords.longitude so we can update the displayed coordinates. The two <span> element...
GestureEvent - Web APIs
Properties This interface also inherits properties of its parents, UIEvent and Event. ...
... two digits since the event's beginning. Expressed as a floating-point multiple of the initial distance between the digits at the beginning of the gesture. Values below 1.0 indicate an inward pinch (zoom out). Values above 1.0 indicate an outward unpinch (zoom in). Initial value: 1.0 Methods This interface also inherits methods of its parents, UIEvent and Event. GestureEvent.initGestureEvent
() Initializes the value of an GestureEvent. If the event has already being dispatched, this method does nothing. Gesture event types gesturestart gesturechange gestureend Specifications Not part of any specification. Apple has a description at the Safari Developer Library. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to con...
... NoChrome Android No support NoFirefox Android No support NoOpera Android No support NoSafari iOS Full support 2Samsung Internet Android No support NoGestureEvent
() constructor Non-standardChrome No support NoEdge No support NoFirefox No support NoIE No support NoOpera No support NoSafari Full support ...
GlobalEventHandlers.ondragend - Web APIs
log("dragStart"); // Change the source element's background color to signify drag has started ev.currentTarget.style.border = "dashed"; ev.dataTransfer.setData("text", ev.target.id); } function dragover_handler(ev) { console.log("dragOver"); // Change the target element's border to signify a drag over event // has occurred ev.currentTarget.style.background = "lightblue"; ev.preventDefault
(); } function drop_handler(ev) { console.log("Drop"); ev.preventDefault
(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragenter_handler(ev) { console.log("dragEnter"); // Change the source element's background color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.lo...
...(ev) { console.log("dragEnd"); // Change the target element's background color to visually indicate // the drag ended. ...
...ment's border back to green to signify a dragexit event ev.currentTarget.style.background = "green"; } function init
() { // Set handlers for the source's enter/leave/end/exit events var el=document.getElementById("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init
();"> <h1>Examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(...
GlobalEventHandlers.ondragenter - Web APIs
log("dragStart"); // Change the source element's background color to signify drag has started ev.currentTarget.style.border = "dashed"; ev.dataTransfer.setData("text", ev.target.id); } function dragover_handler(ev) { console.log("dragOver"); // Change the target element's border to signify a drag over event // has occurred ev.currentTarget.style.background = "lightblue"; ev.preventDefault
(); } function drop_handler(ev) { console.log("Drop"); ev.preventDefault
(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragenter_handler(ev) { console.log("dragEnter"); // Change the source element's background color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.lo...
...(ev) { console.log("dragEnd"); // Change the target element's background color to visually indicate // the drag ended. ...
...ment's border back to green to signify a dragexit event ev.currentTarget.style.background = "green"; } function init
() { // Set handlers for the source's enter/leave/end/exit events var el=document.getElementById("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init
();"> <h1>Examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(...
GlobalEventHandlers.ondragexit - Web APIs
log("dragStart"); // Change the source element's background color to signify drag has started ev.currentTarget.style.border = "dashed"; ev.dataTransfer.setData("text", ev.target.id); } function dragover_handler(ev) { console.log("dragOver"); // Change the target element's border to signify a drag over event // has occurred ev.currentTarget.style.background = "lightblue"; ev.preventDefault
(); } function drop_handler(ev) { console.log("Drop"); ev.preventDefault
(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragenter_handler(ev) { console.log("dragEnter"); // Change the source element's background color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.lo...
...(ev) { console.log("dragEnd"); // Change the target element's background color to visually indicate // the drag ended. ...
...ment's border back to green to signify a dragexit event ev.currentTarget.style.background = "green"; } function init
() { // Set handlers for the source's enter/leave/end/exit events var el=document.getElementById("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init
();"> <h1>Examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(...
GlobalEventHandlers.ondragleave - Web APIs
log("dragStart"); // Change the source element's border to signify drag has started ev.currentTarget.style.border = "dashed"; ev.dataTransfer.setData("text", ev.target.id); } function dragover_handler(ev) { console.log("dragOver"); // Change the target element's background color to signify a drag over event // has occurred ev.currentTarget.style.background = "lightblue"; ev.preventDefault
(); } function drop_handler(ev) { console.log("Drop"); ev.preventDefault
(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragenter_handler(ev) { console.log("dragEnter"); // Change the source element's background color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.lo...
...nsole.log("dragEnd"); // Change the target element's background color to visually indicate // the drag ended. ...
...kground color back to green to signify a dragexit event ev.currentTarget.style.background = "green"; } function init
() { // Set handlers for the source's enter/leave/end/exit events var el=document.getElementById("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init
();"> <h1>Examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(...
HTMLAnchorElement - Web APIs
states that rev is no longer obsolete, whereas the WHATWG living standard still has it labeled obsolete. Until this discrepancy is resolved, you should still assume it is obsolete. HTMLAnchorElement.shape Is a DOMString representing the shape of the active area. Methods Inherits methods from its parent, HTMLElement, and implements those from HTMLHyperlinkElementUtils. ...
...still has it labeled obsolete. Until this discrepancy is resolved, you should still assume it is obsolete. HTMLAnchorElement.shape Is a DOMString representing the shape of the active area. Methods Inherits methods from its parent, HTMLElement, and implements those from HTMLHyperlinkElementUtils. HTMLElement.blur
() Removes the keyboard focus from the current element. HTMLElement.focus
() Gives the keyboard focus to the current element. HTMLHyperlinkElementUtils.toString
() Returns a USVString containing the whole URL. It is a synonym for HTMLHyperlinkElementUtils.href, though it can't be used to modify the value. The blur
() and focus
() methods are inherited from HTMLElement from HTML5 on, but were defined on HTMLAnchorElement in DOM Level 2 HTML and earlier specifications. S...
...on. Living Standard The following property has been added: download. Technically, the URL-related properties, media, host, hostname, pathname, port, protocol, search, and hash, have been moved to the HTMLHyperlinkElementUtils mixin, and HTMLAnchorElement implements this mixin. HTML5The definition of 'HTMLAnchorElement' in that specification. Recommendation The methods blur
() and focus
(), as well as the properties tabindex and accessKey, are now defined on HTMLElement. The following properties are now obsolete: charset, coords, name, rev, and shape. The following properties have been added: hash, host, hostname, media, pathname, port, protocol, relList, search, and text. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLAnch...
HTMLElement: gotpointercapture event - Web APIs
The gotpointercapture event is fired when an element captures a pointer using setPointerCapture
(). Bubbles Yes Cancelable No Interface PointerEvent Event handler property ongotpointercapture Examples This example gets a <p> element and listens for the gotpointercapture event. It then calls setPointerCapture
() on the element on a pointerdown event, which will trigger gotpointercapture. ...
... Cancelable No Interface PointerEvent Event handler property ongotpointercapture Examples This example gets a <p> element and listens for the gotpointercapture event. It then calls setPointerCapture
() on the element on a pointerdown event, which will trigger gotpointercapture. ...
... gotpointercapture. ...
HTMLElement: transitionrun event - Web APIs
The transitionrun event is fired when a CSS transition is first created, i.e. before any transition-delay has begun. ...
... Cancelable No Interface TransitionEvent Event handler property ontransitionrun Examples This code adds a listener to the transitionrun event: el.addEventListener('transitionrun',
() => { console.log('Transition is running but hasn\'t necessarily started transitioning yet'); }); The same, but using the ontransitionrun property instead of addEventListener
(): el.ontransitionrun =
() => { console.log('Transition started running, and will start transitioning when the transition delay has expired'); }; Live example In the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition">Hover over me</div> <div class="message"></div> .transition { width: 100px; height: 100px; backgro...
...ackground; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate where the transitionstart and transitionrun events fire. const el = document.querySelector('.transition'); const message = document.querySelector('.message'); el.addEventListener('transitionrun', function
() { message.textContent = 'transitionrun fired'; }); el.addEventListener('transitionstart', function
() { message.textContent = 'transitionstart fired'; }); el.addEventListener('transitionend', function
() { message.textContent = 'transitionend fired'; }); The difference is that: transitionrun fires when the transition is created (i.e. at the start of any delay). transitionstart fire...
HTMLFormElement: submit event - Web APIs
is sent to indicate the form's submit action has been triggered includes a submitter property, which is the button that was invoked to trigger the submit request. The submit event fires when the user clicks a submit button (<button> or <input type="submit">) or presses Enter while editing a field (e.g. <input type="text">) in a form. ...
...">) or presses Enter while editing a field (e.g. <input type="text">) in a form. The event is not sent to the form when calling the form.submit
() method directly. Note: Trying to submit a form that does not pass validation triggers an invalid event. In this case, the validation prevents form submission, and thus there is no submit event. Examples This example uses EventTarget.addEventListener
() to listen for form submit, and logs the current Event.timeStamp whenever that occurs, then prevents the default action of submitting the form. HTML <form id="form"> <label>Test field: <input type="text"></label> <br><br> <button type="submit">Submit form</button> </form> <p id="log"></p> JavaScript function logSubmit(event) { log.textContent = `Form Submitted! Time stamp: ${event.time...
... logs the current Event.timeStamp whenever that occurs, then prevents the default action of submitting the form. HTML <form id="form"> <label>Test field: <input type="text"></label> <br><br> <button type="submit">Submit form</button> </form> <p id="log"></p> JavaScript function logSubmit(event) { log.textContent = `Form Submitted! Time stamp: ${event.timeStamp}`; event.preventDefault
(); } const form = document.getElementById('form'); const log = document.getElementById('log'); form.addEventListener('submit', logSubmit); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'submit' in that specification. Working Draft No change HTML 5.2The definition of 'submit' in that specification. Recomme...
HTMLImageElement.complete - Web APIs
it to load the images in the background. But imagine that you have other code that needs to only run when the image has completed loading, such as a command that performs red-eye removal on the image in the lightbox. While ideally this command wouldn't even be executed if the image hasn't fully loaded, for improved reliability you want to check to ensure this is the case. So the fixRedEyeCommand
() function, which is called by the button that triggers red-eye removal, checks the value of the lightbox image's complete property before attempting to do its work. This is demonstrated in the code below. let lightboxElem = document.querySelector("#lightbox"); let lightboxImgElem = lightboxElem.querySelector("img"); let lightboxControlsElem = lightboxElem.querySelector(".toolbar"); async functio...
...e of the lightbox image's complete property before attempting to do its work. This is demonstrated in the code below. ...
...nc function loadImage(url, elem) { return new Promise((resolve, reject) => { elem.onload =
() => resolve(elem); elem.onerror = reject; elem.src = url; }); } async function lightBox(url) { lightboxElem.style.display = "block"; await loadImage("https://somesite.net/huge-image.jpg", lightboxImgElem); lightboxControlsElem.disabled = false; } /* ... */ function fixRedEyeCommand
() { if (lightboxElem.style.display === "block" && lightboxImgElem.complete) { fixRedEye(lightboxImgElem); } else { /* can't start doing this until the image is fully loaded */ } } Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLImageElement.complete' in that specification. Unknown Browser compatibility...
HTMLMediaElement: emptied event - Web APIs
The emptied event is fired when the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load
() method is called to reload it. Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onemptied Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's emptied event, then post a message when that event handler has reacted to the event firing. ...
...celable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onemptied Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's emptied event, then post a message when that event handler has reacted to the event firing. ...
...mptied Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's emptied event, then post a message when that event handler has reacted to the event firing. Using addEventListener
(): const video = document.querySelector('video'); video.addEventListener('emptied', (event) => { console.log('Uh oh. The media is empty. Did you call load
()?'); }); Using the onemptied event handler property: const video = document.querySelector('video'); video.onemptied = (event) => { console.log('Uh oh. The media is empty. Did you call load
()?'); }; Specifications Specification Status HTML Living StandardThe definition of 'emptied media event' in that specification. Living Standard HTML5The definition of 'emp...
HTMLMediaElement: play event - Web APIs
Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onplay Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's play event, then post a message when that event handler has reacted to the event firing. ...
... Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's play event, then post a message when that event handler has reacted to the event firing. Using addEventListener
(): const video = document.querySelector('video'); video.addEventListener('play', (event) => { console.log('The Boolean paused property is now false. ...
...('video'); video.addEventListener('play', (event) => { console.log('The Boolean paused property is now false. Either the ' + 'play
() method was called or the autoplay attribute was toggled.'); }); Using the onplay event handler property: const video = document.querySelector('video'); video.onplay = (event) => { console.log('The Boolean paused property is now false. Either the ' + 'play
() method was called or the autoplay attribute was toggled.'); }; Specifications Specification Status HTML Living StandardThe definition of 'play media event' in that specification. Living Standard HTML5The definition of 'play media event' in that specification. Recommendation ...
HTMLScriptElement - Web APIs
ior instead of the default blocking behavior. Note: The exact processing details for these attributes are complex, involving many different aspects of HTML, and therefore are scattered throughout the specification. These algorithms describe the core ideas, but they rely on the parsing rules for <script> start and end tags in HTML, in foreign content, and in XML; the rules for the document.write
() method; the handling of scripting; and so on. HTMLScriptElement.crossOrigin Is a DOMString reflecting the CORS setting for the script element. For scripts from other origins, this controls if error information will be exposed. HTMLScriptElement.text Is a DOMString that joins and returns the contents of all Text nodes inside the <script> element (ignoring other nodes like comments) in t...
...for the script element. For scripts from other origins, this controls if error information will be exposed. HTMLScriptElement.text Is a DOMString that joins and returns the contents of all Text nodes inside the <script> element (ignoring other nodes like comments) in tree order. On setting, it acts the same way as the textContent IDL attribute. Note: When inserted using the document.write
() method, <script> elements execute (typically synchronously), but when inserted using innerHTML or outerHTML, they do not execute at all. HTMLScriptElement.noModule Is a Boolean that if true, stops the script's execution in browsers that support ES2015 modules -- used to run fallback scripts in older browsers that do not support JavaScript modules. HTMLScriptElement.referrerPolicy Is a DOM...
... Living Standard HTML 5.1The definition of 'HTMLScriptElement' in that specification. Recommendation HTML5The definition of 'HTMLScriptElement' in...
HTMLVideoElement - Web APIs
an unsigned long with the count of presented frames which were painted on the screen. HTMLVideoElement.mozFrameDelay Read only Returns an double with the time which the last painted video frame was late by, in seconds. HTMLVideoElement.mozHasAudio Read only Returns a boolean indicating if there is some audio associated with the video. Microsoft Extensions HTMLVideoElement.msFrameStep
() Steps the video by one frame forward or one frame backward. HTMLVideoElement.msHorizontalMirror Gets or sets whether a video element is flipped horizontally in the display. HTMLVideoElement.msInsertVideoEffect
() Inserts the specified video effect into the media pipeline. HTMLVideoElement.msIsLayoutOptimalForPlayback Read only Indicates whether the video can be rendered more efficie...
...sStereo3D Read only Determines whether the system considers the loaded video source to be stereo 3-D or not. Value set to true indicates source is stereo 3D. HTMLVideoElement.msZoom Controls whether the video frame is trimmed to fit the video display. Methods Inherits methods from its parent, HTMLMediaElement, and from its ancestor HTMLElement. ...
...ement. HTMLVideoElement.getVideoPlaybackQuality
() Returns a VideoPlaybackQuality object that contains the current playback metrics. This information includes things like the number of dropped or corrupted frames, as well as the total number of frames. Events Inherits methods from its parent, HTMLMediaElement, and from its ancestor HTMLElement. Listen to these events using addEventListener
() or by assigning an event listener to the oneventname property of this interface. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLVideoElement' in that specification. Living Standard ...
IDBCursor.key - Web APIs
hing like this (its the album title in each case, which is our key). The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. ...
... it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. ...
...only"); var objectStore = transaction.objectStore('rushAlbumList'); objectStore.openCursor
().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year; list.appendChild(listItem); console.log(cursor.key); cursor.continue
(); } else { console.log('Entries all displayed.'); } }; }; Specifications Specification Status Comment Indexed Database API 2.0The definition of 'key' in that specification. Recommendation Indexed Database API DraftThe definition of 'key' in that specification. Recommendation Browser compatibility The compatibility table o...
IDBCursor.primaryKey - Web APIs
he album title in each case, which is our primarykey): Hemispheres The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. ...
... it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. ...
... var objectStore = transaction.objectStore('rushAlbumList'); objectStore.openCursor
().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year; list.appendChild(listItem); console.log(cursor.primaryKey); cursor.continue
(); } else { console.log('Entries all displayed.'); } }; }; Specifications Specification Status Comment Indexed Database API 2.0The definition of 'primaryKey' in that specification. Recommendation Indexed Database API DraftThe definition of 'primaryKey' in that specification. Recommendation Browser compatibility The compati...
IDBCursor.request - Web APIs
erty of the IDBCursor interface returns the IDBRequest used to obtain the cursor. Note: This feature is available in Web Workers. Syntax var request = cursor.request; Value An IDBRequest object instance. Examples When you open a cursor, the request property is then available on that cursor object, to tell you what request object the cursor originated from. ...
...ct instance. Examples When you open a cursor, the request property is then available on that cursor object, to tell you what request object the cursor originated from. ...
... Recommendation Initial definition. ...
IDBCursor.source - Web APIs
mes: DOMStringList, keyPath: "albumTitle", name: "rushAlbumList"...} The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. ...
... it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. ...
...y"); var objectStore = transaction.objectStore('rushAlbumList'); objectStore.openCursor
().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year; list.appendChild(listItem); console.log(cursor.source); cursor.continue
(); } else { console.log('Entries all displayed.'); } }; }; Specifications Specification Status Comment Indexed Database API 2.0The definition of 'source' in that specification. Recommendation Indexed Database API DraftThe definition of 'source' in that specification. Recommendation Browser compatibility The compatibility t...
IDBCursorSync - Web APIs
ecords in a database. You can have only one instance of IDBCursorSync representing a cursor, but you can have an unlimited number of cursors at the same time. Operations are performed on the underlying index or object store. It enables an application to synchronously process all the records in the cursor's range. Method overview bool continue (in optional any key); void remove
() raises (IDBDatabaseException); Attributes Attribute Type Description count readonly unsigned long long The total number of objects that share the current key. direction readonly unsigned short The direction of traversal of the cursor. See Constants for possible values. key readonly any The key for the record at the cursor's p...
...This cursor does not include duplicates, and its direction is monotonically increasing in the order of keys. PREV 2 This cursor includes duplicates, and its direction is monotonically decreasing in the order of keys. PREV_NO_DUPLICATE 3 This cursor does not include duplicates, and its direction is monotonically decreasing in the order of keys. ...
...ontinue
() Advances the cursor to the next position along its direction, to the item whose key matches the optional key parameter. If no key is specified, advance to the immediate next position. Returns false if the cursor has reached the end of its range; otherwise returns true. bool continue ( in optional any key ); Parameters key The key to which to move the cursor's position. remove
() Deletes the record at the cursor's position, without changing the cursor's position void delete ( ) raises (DatabaseException); Exceptions This method can raise an IDBDatabaseException with the following code: NOT_ALLOWED_ERR If the underlying index or object store does not support updating the record because it is open in the READ_ONLY or SNAPSHOT_READ mode. ...
IDBCursorWithValue.value - Web APIs
hin each iteration we log the value of the cursor with cursor.value. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. ...
... it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. ...
...ly"); var objectStore = transaction.objectStore('rushAlbumList'); objectStore.openCursor
().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year; list.appendChild(listItem); console.log(cursor.value); cursor.continue
(); } else { console.log('Entries all displayed.'); } }; }; Specifications Specification Status Comment Indexed Database API 2.0The definition of 'source' in that specification. Recommendation Indexed Database API DraftThe definition of 'IDBDatabase' in that specification. Recommendation Browser compatibility The compatibili...
IDBCursorWithValue - Web APIs
use a cursor to iterate through all the records in the object store. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. ...
... it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. ...
...action(['rushAlbumList'], "readonly"); var objectStore = transaction.objectStore('rushAlbumList'); objectStore.openCursor
().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listItem = document.createElement('li'); listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year; list.appendChild(listItem); cursor.continue
(); } else { console.log('Entries all displayed.'); } }; }; Specifications Specification Status Comment Indexed Database API 2.0The definition of 'IDBCursorWithValue' in that specification. Recommendation Indexed Database API DraftThe definition of 'IDBCursorWithValue' in that specification. Recommendation Browser compatibility ...
IDBDatabase: close event - Web APIs
The close event is fired on IDBDatabase when the database connection is unexpectedly closed. This could happen, for example, if the underlying storage is removed or if the user clears the database in the browser's history preferences. Note that it is not fired if the database connection is closed normally using IDBDatabase.close
(). Bubbles No Cancelable No Interface Event Event handler property onerror Examples This example opens a database and listens for the close event: // Open the database const dBOpenRequest = window.indexedDB.open('toDoList', 4); dBOpenRequest.onupgradeneeded = (event) => { const db = event.target.result; // Create an objectStore for this database const objectStore = db.createObjectStore('toDoList', { ...
...ours', 'hours', { unique: false }); objectStore.createIndex('minutes', 'minutes', { unique: false }); objectStore.createIndex('day', 'day', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; dBOpenRequest.onsuccess = (event) => { const db = dBOpenRequest.result; db.addEventListener('close',
() => { console.log('Database connection closed'); }); }; The same example, using the onclose property instead of addEventListener
(): // Open the database const dBOpenRequest = window.indexedDB.open('toDoList', 4); dBOpenRequest.onupgradeneeded = (event) => { const db = event.target.result; // Create an objectStore for this database const objectStore = db.createObjectStore('toDoLis...
...e.createIndex('hours', 'hours', { unique: false }); objectStore.createIndex('minutes', 'minutes', { unique: false }); objectStore.createIndex('day', 'day', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; dBOpenRequest.onsuccess = (event) => { const db = dBOpenRequest.result; db.onclose =
() => { console.log('Database connection closed'); }; }; ...
IDBDatabase: error event - Web APIs
The error event is fired on IDBDatabase when a request returns an error and the event bubbles up to the connection object. ...
...bjectStore.createIndex('day', 'day', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; dBOpenRequest.onsuccess = (event) => { const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2020 }; const db = dBOpenRequest.result; db.addEventListener('error',
() => { console.log(`Error adding new item: ${newItem.taskTitle}`); }); // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); const objectStore = transaction.objectStore('toDoList'); const objectStoreRequest = objectStore.add(newItem); }; The same example, using the onerror property instead of addEventListener
()...
...e: false }); objectStore.createIndex('day', 'day', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; dBOpenRequest.onsuccess = (event) => { const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2020 }; const db = dBOpenRequest.result; db.onerror =
() => { console.log(`Error adding new item: ${newItem.taskTitle}`); }; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); const objectStore = transaction.objectStore('toDoList'); const objectStoreRequest = objectStore.add(newItem); }; ...
IDBIndex.keyPath - Web APIs
ectStore.openCursor except that the returned records are sorted based on the index, not the primary key. The key path of the current index is logged to the console: it should be returned as lName. Finally, we iterate through each record, and insert the data into an HTML table. ...
... into an HTML table. ...
... Recommendation Indexed Database API DraftThe definition of 'keyPath' in that specification. Recommendation Browser compatibility The compatibility t...
IDBIndex.multiEntry - Web APIs
tStore.openCursor except that the returned records are sorted based on the index, not the primary key. The multi-entry status of the index is logged to the console: it should be returned as false. Finally, we iterate through each record, and insert the data into an HTML table. ...
...to an HTML table. ...
... Recommendation Indexed Database API DraftThe definition of 'multiEntry' in that specification. Recommendation Browser compatibility The compatibi...
IDBIndex.objectStore - Web APIs
d to the console: it should be returned something like this: IDBObjectStore { name: "contactsList", keyPath: "id", indexNames: DOMStringList[7], transaction: IDBTransaction, autoIncrement: false } Finally, we iterate through each record, and insert the data into an HTML table. ...
...o an HTML table. ...
... Recommendation Indexed Database API DraftThe definition of 'objectStore' in that specification. Recommendation Browser compatibility The compati...
IDBIndex.unique - Web APIs
ObjectStore.openCursor except that the returned records are sorted based on the index, not the primary key. The unique status of the index is logged to the console: it should be returned as false. Finally, we iterate through each record, and insert the data into an HTML table. ...
...a into an HTML table. ...
... Recommendation Indexed Database API DraftThe definition of 'unique' in that specification. Recommendation Browser compatibility The compatibility tab...
IDBOpenDBRequest - Web APIs
o,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">IDBOpenDBRequest</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Also inherits methods from its parents IDBRequest and EventTarget. Methods No methods, but inherits methods from its parents IDBRequest and EventTarget. Events Listen to these events using addEventListener
() or by assigning an event listener to the oneventname property of this interface. blocked Fired when an open connection to a database is blocking a versionchange transaction on the same database. Also available via the onblocked property. upgradeneeded Fired when an attempt was made to open a database with a version number higher than its current version. Also available via the onupgradeneed...
...event handlers act on the database being opened. DBOpenRequest.onerror = function(event) { note.innerHTML += '<li>Error loading database.</li>'; }; DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db // variable. ...
...HTML += '<li>Error loading database.</li>'; }; DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db // variable. ...
IDBRequest: success event - Web APIs
The success event is fired when an IDBRequest succeeds. ...
...bbles No Cancelable No Interface Event Event handler property onsuccess Examples This example tries to open a database and listens for the success event using addEventListener
(): // Open the database const openRequest = window.indexedDB.open('toDoList', 4); openRequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror =
() => { console.log('Error creating database'); }; // Create an objectStore for this database var objectStore = db.createObjectStore('toDoList', { keyPath: 'taskTitle' }); // define what data items the objectStore will contain objectStore.createIndex('hours', 'hours', { unique: false }); objectStore.createIndex('minutes', 'minutes', { unique: false }); objectStore.createIndex('da...
...createIndex('year', 'year', { unique: false }); }; openRequest.addEventListener('success', (event) => { console.log('Database opened successfully!'); }); The same example, but using the onsuccess event handler property: // Open the database const openRequest = window.indexedDB.open('toDoList', 4); openRequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror =
() => { console.log('Error creating database'); }; // Create an objectStore for this database var objectStore = db.createObjectStore('toDoList', { keyPath: 'taskTitle' }); // define what data items the objectStore will contain objectStore.createIndex('hours', 'hours', { unique: false }); objectStore.createIndex('minutes', 'minutes', { unique: false }); objectStore.createIndex('da...
IDBTransaction: complete event - Web APIs
The complete handler is executed when a transaction successfully completed. ...
...r is executed when a transaction successfully completed. ...
...objectStore('toDoList'); const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2019 }; const objectStoreRequest = objectStore.add(newItem); }; Using the oncomplete property: // Open the database const DBOpenRequest = window.indexedDB.open('toDoList', 4); DBOpenRequest.onupgradeneeded = event => { const db = event.target.result; db.onerror =
() => { console.log('Error creating database'); }; // Create an objectStore for this database var objectStore = db.createObjectStore('toDoList', { keyPath: 'taskTitle' }); // define what data items the objectStore will contain objectStore.createIndex('hours', 'hours', { unique: false }); objectStore.createIndex('minutes', 'minutes', { unique: false }); objectStore.createIndex('da...
IDBTransaction.db - Web APIs
king example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...xample live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
... open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransaction.error - Web APIs
king example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...xample live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
... open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransaction: error event - Web APIs
The error event is fired on IDBTransaction when a request returns an error and the event bubbles up to the transaction object. ...
...y', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; dBOpenRequest.onsuccess = (event) => { const db = dBOpenRequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); transaction.addEventListener('error',
() => { console.log(`Error adding new item: ${newItem.taskTitle}`); }); const objectStore = transaction.objectStore('toDoList'); const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2020 }; const objectStoreRequest = objectStore.add(newItem); }; The same example, using the onerror property instead of addEventListener
(): // Open the databas...
...Index('day', 'day', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; dBOpenRequest.onsuccess = (event) => { const db = dBOpenRequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); transaction.onerror =
() => { console.log(`Error adding new item: ${newItem.taskTitle}`); }; const objectStore = transaction.objectStore('toDoList'); const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2020 }; const objectStoreRequest = objectStore.add(newItem); }; ...
IDBTransaction.oncomplete - Web APIs
king example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...xample live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
... open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransaction.onerror - Web APIs
king example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
...xample live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
... open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. ...
InstallEvent - Web APIs
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.wa...
...es a new InstallEvent object. 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 ca...
... 'https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif' ]; console.log('Handling install event. Resources to pre-fetch:', urlsToPrefetch); event.waitUntil( caches.open(CURRENT_CACHES['prefetch']).then(function(cache) { return cache.addAll(urlsToPrefetch.map(function(urlToPrefetch) { return new Request(urlToPrefetch, {mode: 'no-cors'}); })).then(function
() { console.log('All resources have been fetched and cached.'); }); }).catch(function(error) { console.error('Pre-fetching failed:', error); }) ); }); Specifications Specification Status Comment Service Workers Working Draft As of May 2015, the install event is an instance of ExtendableEvent rather than a child of it. ...
KeyframeEffect - Web APIs
Properties KeyframeEffect.target Gets and sets the element, or originating element of the pseudo-element, being animated by this object. This may be null for animations that do not target a specific element or pseudo-element. ...
...ite Gets and sets the iteration composite operation for resolving the property value changes of this keyframe effect. KeyframeEffect.composite Gets and sets the composite operation property for resolving the property value changes between this and other keyframe effects. Methods This interface inherits some of its methods from its parent, AnimationEffect. ...
...yframe effect. KeyframeEffect.composite Gets and sets the composite operation property for resolving the property value changes between this and other keyframe effects. Methods This interface inherits some of its methods from its parent, AnimationEffect. AnimationEffect.getComputedTiming
() Returns the calculated, current timing values for this keyframe effect. KeyframeEffect.getKeyframes
() Returns the computed keyframes that make up this effect along with their computed keyframe offsets. AnimationEffect.getTiming
() The EffectTiming object associated with the animation containing all the animation's timing values. KeyframeEffect.setKeyframes
() Replaces the set of keyframes that make up this effect. AnimationEffect.updateTiming
() Updates the specified timing properties. E...
LargestContentfulPaint - Web APIs
ontentfulPaint.loadTime The time the element was loaded. LargestContentfulPaint.size The intrinsic size of the element returned as the area (width * height). LargestContentfulPaint.id The id of the element. This property returns an empty string when there is no id. LargestContentfulPaint.url If the element is an image, the request url of the image. Methods LargestContentfulPaint.toJSON
() Returns the above properties as JSON. Examples The following example shows how to create a PerformanceObserver that listens for largest-contentful-paint entries and logs the LCP value to the console. This example also demonstrates how to include buffered entries (those that ocurred before observer
() was called), which is done by setting the buffered option to true. Note that in this example...
...er
() was called), which is done by setting the buffered option to true. Note that in this example data is only sent to the server when the user leaves the tab. // Catch errors since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let lcp; const po = new PerformanceObserver((entryList) => { const entries = entryList.getEntries
(); const lastEntry = entries[entries.length - 1]; // Update `lcp` to the latest value, using `renderTime` if it's available, // otherwise using `loadTime`. (Note: `renderTime` may not be available on // image elements loaded cross-origin without the `Timing-Allow-Origin` header.) lcp = lastEntry.renderTime || lastEntry.loadTime; }); po.observe({type: 'largest-contentful-pa...
...derTime` if it's available, // otherwise using `loadTime`. (Note: `renderTime` may not be available on // image elements loaded cross-origin without the `Timing-Allow-Origin` header.) lcp = lastEntry.renderTime || lastEntry.loadTime; }); po.observe({type: 'largest-contentful-paint', buffered: true}); // Send data to the server. addEventListener('visibilitychange', function fn
() { if (lcp && document.visibilityState === 'hidden') { console.log('LCP:', lcp); removeEventListener('visibilitychange', fn, true); } }, true); } catch (e) { // Do nothing if the browser doesn't support this API. } Specifications Specification Status Comment Largest Contentful PaintThe definition of 'LargestContentfulPaint' in that specification. ...
LayoutShift - Web APIs
mes the distance fraction (distance moved as a fraction of viewport). LayoutShift.hadRecentInput Returns true if there was a user input in the past 500 milliseconds. LayoutShift.lastInputTime Returns the time of the most recent user input. LayoutShift.sources Returns an array of LayoutShiftAttribution objects with information on the elements that were shifted. Methods LayoutShift.toJSON
() Converts the properties to JSON. Examples The following example shows how to capture layout shifts and log them to the console. Note that in this example data is only sent to the server when the user leaves the tab. // Catch errors since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let cumulativeLayoutShiftScore = 0; cons...
...ure layout shifts and log them to the console. Note that in this example data is only sent to the server when the user leaves the tab. // Catch errors since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let cumulativeLayoutShiftScore = 0; const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries
()) { // Only count layout shifts without recent user input. if (!entry.hadRecentInput) { cumulativeLayoutShiftScore += entry.value; } } }); observer.observe({type: 'layout-shift', buffered: true}); document.addEventListener('visibilitychange',
() => { if (document.visibilityState === 'hidden') { // Force any pending records to be dispatched. observer.takeRecord...
... { // Only count layout shifts without recent user input. if (!entry.hadRecentInput) { cumulativeLayoutShiftScore += entry.value; } } }); observer.observe({type: 'layout-shift', buffered: true}); document.addEventListener('visibilitychange',
() => { if (document.visibilityState === 'hidden') { // Force any pending records to be dispatched. observer.takeRecords
(); observer.disconnect
(); console.log('CLS:', cumulativeLayoutShiftScore); } }); } catch (e) { // Do nothing if the browser doesn't support this API. } Specifications Specification Status Comment Layout Instability APIThe definition of 'LayoutShift' in that specification. Editor's Draft Initial definition. ...
LocalFileSystemSync - Web APIs
ocument was last updated on March 2, 2012 and follows the W3C Specifications (Working Draft) drafted on April 19, 2011. This specification is more or less 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; //...
... EntrySync resolveLocalFileSystemSyncURL (in DOMString url) raises FileException; Constants Constant Value Description TEMPORARY 0 Transient storage that can be be removed by the browser at its discretion. PERSISTENT 1 Storage that stays in the browser unless the user or the app expunges it. Methods requestFileSystemSync
() Requests a file system where data should be stored. You access a sandboxed file system by requesting a LocalFileSystemSync object from within a web worker using this global method, window.requestFileSystemSync
(). [ RESEARCH ] FileSystemSync requestFileSystemSync( in unsigned short type, in unsigned long long size ); Parameters type The storage type of the file system. The values can be...
...emSync An object that represents the file system. Exceptions This method can raise an FileException with the following code: Exception Description SECURITY_ERROR The application does not have permission to access the file system interface. For example, you cannot run from file://. For more details, see the article on basic concepts. resolveLocalFileSystemSyncURL
() Allows the user to look up the Entry for a file or directory referred to by a local URL. void resolveLocalFileSystemURL( in DOMString url ); Parameter url The URL of a local file in the file system. Returns EntrySync An object that represents entries in the file system. Exceptions This method can raise a FileException with the following codes: Exception Description ...
LockedFile - Web APIs
eadonly or readwrite. LockedFile.active Read only A flag indicating if the file can be accessed (true) or not (false). LockedFile.location The position of the reading/writing pointer within the file. Events Handler LockedFile.oncomplete The complete event is triggered each time a read or write operation is successful. LockedFile.onabort The abort event is triggered each time the abort
() method is called. LockedFile.onerror The error event is triggered each time something goes wrong. Methods LockedFile.getMetadata
() Allows to retrieve the file metadata (size and date of the last modification). Returns a FileRequest. LockedFile.readAsArrayBuffer
() Allows to retrieve a part of the content of the file as an ArrayBuffer. Returns a FileRequest object. LockedFile.readAsText(...
...ckedFile.getMetadata
() Allows to retrieve the file metadata (size and date of the last modification). Returns a FileRequest. LockedFile.readAsArrayBuffer
() Allows to retrieve a part of the content of the file as an ArrayBuffer. Returns a FileRequest object. LockedFile.readAsText
() Allows to retrieve a part of the content of the file as a string. Returns a FileRequest object. LockedFile.write
() Allows to write some data in the file starting at the location offset. Returns a FileRequest object. LockedFile.append
() Allows to write some data at the end of the file. Returns a FileRequest object. LockedFile.truncate
() Allows to truncate the file's content. Returns a FileRequest object. LockedFile.flush
() Allows to guarantee that any buffered data has been transferred to disk. LockedF...
...to write some data in the file starting at the location offset. Returns a FileRequest object. LockedFile.append
() Allows to write some data at the end of the file. Returns a FileRequest object. LockedFile.truncate
() Allows to truncate the file's content. Returns a FileRequest object. LockedFile.flush
() Allows to guarantee that any buffered data has been transferred to disk. LockedFile.abort
() Makes the LockedFile inactive and cancels all ongoing operations. Specifications Specification Status Comment FileSystem API Editor's Draft Draft proposal. ...
MSGestureEvent - Web APIs
The MSGestureEvent is a proprietary interface specific to Internet Explorer and Microsoft Edge which represents events that occur due to touch gestures. Events using this interface include MSGestureStart, MSGestureEnd, MSGestureTap, MSGestureHold, MSGestureChange, and MSInertiaStart. MSGestureEvent derives from UIEvent, which in turn derives from Event. Though the MSGestureEvent.initGestureEvent
() method is kept for backward compatibility, the creation of an MSGestureEvent object should be done using the MSGestureEvent
() constructor. Constructor MSGestureEvent
() Creates an MSGestureEvent object. Properties This interface also inherits properties of its parents, UIEvent and Event. MSGestureEvent.expansion Read only The diameter of the gesture area. For example, the distance bet...
...Expressed in radians. MSGestureEvent.velocityExpansion Read only The velocity of the expansion of the gesture area. MSGestureEvent.velocityX Read only Velocity along the direction of the X-axis. MSGestureEvent.velocityY Read only Velocity along the direction of the Y-axis. Methods This interface also inherits methods of its parents, UIEvent and Event. MSGestureEvent.initGestureEvent
() Initializes the value of an MSGestureEvent. If the event has already being dispatched, this method does nothing. This method is deprecated as of Microsoft Edge. Gesture event types MSGestureStart MSGestureEnd MSGestureTap MSGestureHold MSGestureChange MSInertiaStart Specifications Not part of any specification. Microsoft has a description on MSDN. Browser compatibility The compa...
... NoChrome Android No support NoFirefox Android No support NoOpera Android No support NoSafari iOS No support NoSamsung Internet Android No support NoMSGestureEvent
() constructor Non-standardChrome No support NoEdge No support 12 -- 79Firefox No support NoIE Full support 10Opera No support NoSafari No support NoWe...
msExtendedCode - Web APIs
ill be fired. The element's error property will then contain an msExtendedCode read-only property with platform-specific error code information. ...
...-specific error code information. msExtendedCode is a read-only proprietary property specific to Internet Explorer and Microsoft Edge. ...
...de information. msExtendedCode is a read-only proprietary property specific to Internet Explorer and Microsoft Edge. ...
MediaKeySession - Web APIs
the CDM for the current media object and its associated keys or licenses. Event handlers MediaKeySession.onkeystatuseschange Sets the EventHandler called when there has been a change in the keys in a session or their statuses. MediaKeySession.onmessage Sets the EventHandler called when the content decryption module has generated a message for the session. ...
...ssion or their statuses. MediaKeySession.onmessage Sets the EventHandler called when the content decryption module has generated a message for the session. Methods MediaKeySession.close
() Returns a Promise after notifying the current media session is no longer needed and that the CDM should release any resources associated with this object and close it. MediaKeySession.generateRequest
() Returns a Promise after generating a media request based on initialization data. MediaKeySession.load
() Returns a Promise that resolves to a boolean value after loading data for a specified session object. ...
...current media session is no longer needed and that the CDM should release any resources associated with this object and close it. MediaKeySession.generateRequest
() Returns a Promise after generating a media request based on initialization data. MediaKeySession.load
() Returns a Promise that resolves to a boolean value after loading data for a specified session object. MediaKeySession.remove
() Returns a Promise after removing any session data associated with the current object. MediaKeySession.update
() Returns a Promise after loading messages and licenses to the CDM. Examples // TBD Specifications Specification Status Comment Encrypted Media ExtensionsThe definition of 'MediaKeySession' in that specification. Recommendation Initial definition. ...
MediaKeyStatusMap - Web APIs
The MediaKeyStatusMap interface of the EncryptedMediaExtensions API is a read-only map of media key statuses by key IDs. Properties MediaKeyStatusMap.size Read only Returns the number of key/value pars in the status map. Methods MediaKeyStatusMap.entries
() Read only Returns a new Iterator object containing an array of [key, value] for each element in the status map, in insertion order. ...
... Methods MediaKeyStatusMap.entries
() Read only Returns a new Iterator object containing an array of [key, value] for each element in the status map, in insertion order. MediaKeyStatusMap.forEach(callback[, argument]) Read only Calls callback once for each key-value pair in the status map, in insertion order. If argument is present it will be passed to the callback. MediaKeyStatusMap.get
() Read only Returns the value associated with the given key, or undefined if there is none. MediaKeyStatusMap.has
() Read only Returns a boolean asserting whether a value has been associated with the given key. MediaKeyStatusMap.keys
() Read only Returns a new Iterator object containing keys for each element in the status map, in insertion order. ...
...diaKeyStatusMap.get
() Read only Returns the value associated with the given key, or undefined if there is none. MediaKeyStatusMap.has
() Read only Returns a boolean asserting whether a value has been associated with the given key. MediaKeyStatusMap.keys
() Read only Returns a new Iterator object containing keys for each element in the status map, in insertion order. MediaKeyStatusMap.values
() Read only Returns a new Iterator object containing values for each element in the status map, in insertion order. MediaKeyStatusMap.[@@iterator]
() Read only Returns a new Iterator object containing an array of [key, value] for each element in the status map, in insertion order. Specifications Specification Status Comment Encrypted Media ExtensionsThe definition of ...
MediaRecorder.onpause - Web APIs
The MediaRecorder.onpause event handler (part of the MediaRecorder API) handles the pause event, allowing you to run code in response to the media recording being paused. The pause event is thrown as a result of the MediaRecorder.pause
() method being invoked. Syntax MediaRecorder.onpause = function(event) { ... } MediaRecorder.addEventListener('pause', function(event) { ... }) Example ... ...
... event handler (part of the MediaRecorder API) handles the pause event, allowing you to run code in response to the media recording being paused. The pause event is thrown as a result of the MediaRecorder.pause
() method being invoked. Syntax MediaRecorder.onpause = function(event) { ... } MediaRecorder.addEventListener('pause', function(event) { ... }) Example ... ...
...wing you to run code in response to the media recording being paused. The pause event is thrown as a result of the MediaRecorder.pause
() method being invoked. Syntax MediaRecorder.onpause = function(event) { ... } MediaRecorder.addEventListener('pause', function(event) { ... }) Example ... pause.onclick = function
() { if(mediaRecorder.state === "recording") { mediaRecorder.pause
(); // recording paused } else if(mediaRecorder.state === "paused") { mediaRecorder.resume
(); // resume recording } } mediaRecorder.onpause = function
() { // do something in response to // recording being paused } mediaRecorder.onresume = function
() { // do something in response to // recording being resumed } ... Properties None. Specificati...
MediaRecorder.onresume - Web APIs
The MediaRecorder.onresume event handler (part of the MediaRecorder API) handles the resume event, allowing you to run code in response to the media recording being resumed after pausing. The resume event is thrown as a result of the MediaRecorder.resume
() method being invoked. Syntax MediaRecorder.onresume = function(event) { ... } MediaRecorder.addEventListener('resume', function(event) { ... }) Example ... ...
... of the MediaRecorder API) handles the resume event, allowing you to run code in response to the media recording being resumed after pausing. The resume event is thrown as a result of the MediaRecorder.resume
() method being invoked. Syntax MediaRecorder.onresume = function(event) { ... } MediaRecorder.addEventListener('resume', function(event) { ... }) Example ... ...
...e in response to the media recording being resumed after pausing. The resume event is thrown as a result of the MediaRecorder.resume
() method being invoked. Syntax MediaRecorder.onresume = function(event) { ... } MediaRecorder.addEventListener('resume', function(event) { ... }) Example ... pause.onclick = function
() { if(MediaRecorder.state === "recording") { mediaRecorder.pause
(); // recording paused } else if(MediaRecorder.state === "paused") { mediaRecorder.resume
(); // resume recording } } mediaRecorder.onpause = function
() { // do something in response to // recording being paused } mediaRecorder.onresume = function
() { // do something in response to // recording being resumed } ... Properties None. Specificati...
MediaSource.readyState - Web APIs
he MediaSource interface returns an enum representing the state of the current MediaSource. The three possible values are: closed: The source is not currently attached to a media element. open: The source is attached to a media element and ready to receive SourceBuffer objects. ended: The source is attached to a media element but the stream has been ended via a call to MediaSource.endOfStream
(). Syntax var myReadyState = mediaSource.readyState; Value A DOMString. Example The following snippet is from a simple example written by Nick Desaulniers (view the full demo live, or download the source for further investigation.) if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) { var mediaSource = new MediaSource; //console.log(mediaSource.readyState); // closed ...
... Recommendation Initial definition. ...
... Recommendation Initial definition. ...
MediaTrackConstraints - Web APIs
For each constraint, you can typically specify an exact value you need, an ideal value you want, a range of acceptable values, and/or a value which you'd like to be as close to as possible. ...
... For each constraint, you can typically specify an exact value you need, an ideal value you want, a range of acceptable values, and/or a value which you'd like to be as close to as possible. ...
... by the camera, its driver or the OS. crop-and-scale means that the user agent can use cropping and downscaling on the camera output in order to satisfy other constraints that affect the resolution. Properties of shared screen tracks These constraints apply to MediaTrackConstraints objects specified as part of the DisplayMediaStreamConstraints object's video property when using getDisplayMedia
() to obtain a stream for screen sharing. cursor A ConstrainDOMString which specifies whether or not to include the mouse cursor in the generated track, and if so, whether or not to hide it while not moving. The value may be a single one of the following strings, or an array of them to allow the browser flexibility in deciding what to do about the cursor. always The mouse is always visi...
MediaTrackSettings - Web APIs
The MediaTrackSettings dictionary is used to return the current values configured for each of a MediaStreamTrack's settings. These values will adhere as closely as possible to any constraints previously described using a MediaTrackConstraints object and set using applyConstraints
(), and will adhere to the default constraints for any properties whose constraints haven't been changed, or whose customized constraints couldn't be matched. To learn more about how constraints and settings work, see Capabilities, constraints, and settings. Properties Some or all of the following will be included in the object, either because it's not supported by the browser or because it's not available due to context. For example, because RTP doesn't provide some of these values during negotiation of a WebRTC...
...rties of all media tracks deviceId A DOMString indicating the current value of the deviceId property. The device ID is a origin-unique string identifying the source of the track; this is usually a GUID. This value is specific to the source of the track's data and is not usable for setting constraints; it can, however, be used for initially selecting media when calling MediaDevices.getUserMedia
(). groupId A DOMString indicating the current value of the groupId property. The group ID is a browsing session-unique string identifying the source group of the track. Two devices (as identified by the deviceId) are considered part of the same group if they are from the same physical device. For instance, the audio input and output devices for the speaker and microphone built into a phone would ...
...output devices for the speaker and microphone built into a phone would share the same group ID, since they're part of the same physical device. The microphone on a headset would have a different ID, though. This value is specific to the source of the track's data and is not usable for setting constraints; it can, however, be used for initially selecting media when calling MediaDevices.getUserMedia
(). Properties of audio tracks autoGainControl A Boolean which indicates the current value of the autoGainControl property, which is true if automatic gain control is enabled and is false otherwise. channelCount A long integer value indicating the current value of the channelCount property, specifying the number of audio channels present on the track (therefore indicating how many audio samp...
Media Source API - Web APIs
ject. SourceBuffer Represents a chunk of media to be passed into an HTMLMediaElement via a MediaSource object. SourceBufferList A simple container list for multiple SourceBuffer objects. VideoPlaybackQuality Contains information about the quality of video being played by a <video> element, such as number of dropped or corrupted frames. ...
...or corrupted frames. Returned by the HTMLVideoElement.getVideoPlaybackQuality
() method. TrackDefault Provides a SourceBuffer with kind, label, and language information for tracks that do not contain this information in the initialization segments of a media chunk. TrackDefaultList A simple container list for multiple TrackDefault objects. Extensions to other interfaces URL.createObjectURL
() Creates an object URL pointing to a MediaSource object that can then be specified as the src value of an HTML media element to play a media stream. ...
... AudioTrack.sourceBuffer, VideoTrack.sourceBuffer, TextTrack.sourceBuffer Returns the SourceBuffer that created the track in question. Specifications Specification Status Comment Media Source Extensions Recommendation Initial definition. ...
MessageChannel.port1 - Web APIs
port of the message channel -- the port attached to the context that originated the channel. Note: This feature is available in Web Workers. Syntax channel.port1; Value A MessagePort object, the first port of the channel, that is the port attached to the context that originated the channel. Example In the following code block, you can see a new channel being created using the MessageChannel
() constructor. When the <iframe> has loaded, we pass MessageChannel.port2 to the <iframe> using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the <iframe> (using MessagePort.onmessage), putting it into a paragraph. The handleMessage method is associated to the port1 to listen when the message arrives. var channel = new Messa...
...tor. When the <iframe> has loaded, we pass MessageChannel.port2 to the <iframe> using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the <iframe> (using MessagePort.onmessage), putting it into a paragraph. The handleMessage method is associated to the port1 to listen when the message arrives. ...
... from the <iframe> (using MessagePort.onmessage), putting it into a paragraph. The handleMessage method is associated to the port1 to listen when the message arrives. var channel = new MessageChannel
(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded
() { otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } Specifications Specification Status Comment HTML Living StandardThe definition of 'port1' in that specification. Living Standard ...
MessageChannel - Web APIs
The MessageChannel interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. Note: This feature is available in Web Workers. Properties MessageChannel.port1 Read only Returns port1 of the channel. MessageChannel.port2 Read only Returns port2 of the channel. Constructor MessageChannel
() Returns a new MessageChannel object with two new MessagePort objects. Example In the following example, you can see a new channel being created using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we register an onmessage handler for MessageChannel.port1 and transfer MessageChannel.port2 to the IFrame using the window.postMessage method along with a message. When a message ...
...ted using the MessageChannel.MessageChannel constructor. When the IFrame has loaded, we register an onmessage handler for MessageChannel.port1 and transfer MessageChannel.port2 to the IFrame using the window.postMessage method along with a message. When a message is received back from the IFrame, the onMessage function simply outputs the message to a paragraph. ...
...rame using the window.postMessage method along with a message. When a message is received back from the IFrame, the onMessage function simply outputs the message to a paragraph. var channel = new MessageChannel
(); var output = document.querySelector('.output'); var iframe = document.querySelector('iframe'); // Wait for the iframe to load iframe.addEventListener("load", onLoad); function onLoad
() { // Listen for messages on port1 channel.port1.onmessage = onMessage; // Transfer port2 to the iframe iframe.contentWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } // Handle messages received on port1 function onMessage(e) { output.innerHTML = e.data; } For a full working example, see our channel messaging basic demo on Github (run it live too). Specifica...
MessagePort: message event - Web APIs
red on a MessagePort object when a message arrives on that channel. ...
...owsing context, such as another <iframe>, using code like this: const channel = new MessageChannel
(); const myPort = channel.port1; const targetFrame = window.top.frames[1]; const targetOrigin = 'https://example.org'; const messageControl = document.querySelector('#message'); const channelMessageButton = document.querySelector('#channel-message'); channelMessageButton.addEventListener('click',
() => { myPort.postMessage(messageControl.value); }) targetFrame.postMessage('init', targetOrigin, [channel.port2]); The target can receive the port and start listening for messages on it using code like this: window.addEventListener('message', (event) => { const myPort = event.ports[0]; myPort.addEventListener('message', (event) => { received.textContent = event.data; })...
...stMessage(messageControl.value); }) targetFrame.postMessage('init', targetOrigin, [channel.port2]); The target can receive the port and start listening for messages on it using code like this: window.addEventListener('message', (event) => { const myPort = event.ports[0]; myPort.addEventListener('message', (event) => { received.textContent = event.data; }); myPort.start
(); }); Note that the listener must call MessagePort.start
() before any messages will be delivered to this port. This is only needed when using the addEventListener
() method: if the receiver uses onmessage instead, start
() is called implicitly: window.addEventListener('message', (event) => { const myPort = event.ports[0]; myPort.onmessage = (event) => { received.textContent = even...
MessagePort: messageerror event - Web APIs
object when it receives a message that can't be deserialized. ...
...owsing context, such as another <iframe>, using code like this: const channel = new MessageChannel
(); const myPort = channel.port1; const targetFrame = window.top.frames[1]; const targetOrigin = 'https://example.org'; const messageControl = document.querySelector('#message'); const channelMessageButton = document.querySelector('#channel-message'); channelMessageButton.addEventListener('click',
() => { myPort.postMessage(messageControl.value); }) targetFrame.postMessage('init', targetOrigin, [channel.port2]); The target can receive the port and start listening for messages and message errors on it using code like this: window.addEventListener('message', (event) => { const myPort = event.ports[0]; myPort.addEventListener('message', (event) => { received.textContent =...
...eive the port and start listening for messages and message errors on it using code like this: window.addEventListener('message', (event) => { const myPort = event.ports[0]; myPort.addEventListener('message', (event) => { received.textContent = event.data; }); myPort.addEventListener('messageerror', (event) => { console.error(event.data); }); myPort.start
(); }); Note that the listener must call MessagePort.start
() before any messages will be delivered to this port. This is only needed when using the addEventListener
() method: if the receiver uses onmessage instead, start
() is called implicitly: window.addEventListener('message', (event) => { const myPort = event.ports[0]; myPort.onmessage = (event) => { received.textContent = even...
MessagePort.onmessage - Web APIs
The onmessage event handler of the MessagePort interface is an EventListener, called whenever an MessageEvent of type message is fired on the port -- that is, when the port receives a message. Note: This feature is available in Web Workers. Syntax channel.onmessage = function
() { ... }; Example In the following code block, you can see a new channel being created using the MessageChannel.MessageChannel constructor. ...
...ageChannel.MessageChannel constructor. When the IFrame has loaded, we pass MessageChannel.port2 to the IFrame using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame using onmessage, putting it into a paragraph -- MessageChannel.port1 is listened to, to check when the message arrives. ...
...s to a message being sent back from the IFrame using onmessage, putting it into a paragraph -- MessageChannel.port1 is listened to, to check when the message arrives. var channel = new MessageChannel
(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded
() { otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } For a full working example, see our channel messaging basic demo on Github (run it live too). Specifications Specification Status Comment HTML Living StandardThe definition of 'onmessage' ...
MouseEvent.pageX - Web APIs
HTML <div class="box"> <p> Move the mouse around in this box to watch its coordinates change. </p> <p> <code>pageX</code>...
... HTML <div class="box"> <p> Move the mouse around in this box to watch its coordinates change. </p> <p> <code>pageX</code>: <span id="x">n/a</span> </p> <p> ...
... = event.pageX; pageY.innerText = event.pageY; } box.addEventListener("mousemove", updateDisplay, false); box.addEventListener("mouseenter", updateDisplay, false); box.addEventListener("mouseleave", updateDisplay, false); The JavaScript code uses addEventListener
() to register the function updateDisplay
() as the event handler for the mousemove, mouseenter, and mouseleave events. updateDisplay
() simply replaces the contents of the <span> elements meant to contain the X and Y coordinates with the values of pageX and pageY. HTML <div class="box"> <p> Move the mouse around in this box to watch its coordinates change. </p> <p> <code>pageX</code>: <span id="x">n/a</span> </p> <p> <code>pageY</code>: <span id="y">n/a</span> </p> </div> The HTML is simple; the box we'...
MouseEvent.region - Web APIs
The MouseEvent.region read-only property returns the id of the canvas hit region affected by the event. If no hit region is affected, null is returned. Syntax var hitRegion = instanceOfMouseEvent.region Return value A DOMString representing the id of the hit region. Example Example of using the event.region combined with CanvasRenderingContext2D.addHitRegion
() method. ...
...gion is affected, null is returned. Syntax var hitRegion = instanceOfMouseEvent.region Return value A DOMString representing the id of the hit region. Example Example of using the event.region combined with CanvasRenderingContext2D.addHitRegion
() method. ...
...on = instanceOfMouseEvent.region Return value A DOMString representing the id of the hit region. Example Example of using the event.region combined with CanvasRenderingContext2D.addHitRegion
() method. ...
MouseEvent.screenX - Web APIs
Working Draft Redefines MouseEvent from long to double. Document Object Model (DOM) Level 3 Events SpecificationThe definiti...
... Working Draft Redefines MouseEvent from long to double. Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.screenX' in that specification. Obsolet...
... Working Draft Redefines MouseEvent from long to double. Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.screenX' in that specification. Obsolete No change from Document Object Mod...
MutationObserver - Web APIs
The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature, which was part of the DOM3 Events specification. Constructor MutationObserver
() Creates and returns a new MutationObserver which will invoke a specified callback function when DOM changes occur. Methods disconnect
() Stops the MutationObserver instance from receiving further notifications until and unless observe
() is called again. ...
...lacement for the older Mutation Events feature, which was part of the DOM3 Events specification. Constructor MutationObserver
() Creates and returns a new MutationObserver which will invoke a specified callback function when DOM changes occur. Methods disconnect
() Stops the MutationObserver instance from receiving further notifications until and unless observe
() is called again. observe
() Configures the MutationObserver to begin receiving notifications through its callback function when DOM changes matching the given options occur. takeRecords
() Removes all pending notifications from the MutationObserver's notification queue and returns them in a new Array of MutationRecord objects. Mutation Observer & customize resize event listener & demo https://codepen.io/webgeeker/full/...
... Living Standard ...
MutationObserverInit.attributes - Web APIs
erty is used to specify whether or not to watch for attribute value changes on the node or nodes being observed. Syntax var options = { attributes: true | false } Value A Boolean value indicating whether or not to report through the callback any changes to the values of attributes on the node or nodes being monitored. The default value is false. If true, the callback specified when observe
() was used to start observing the node or subtree will be called any time one or more attributes have changed on observed nodes. You can expand the capabilities of attribute mutation monitoring using other options: attributeFilter lets you specify specific attribute names to monitor instead of monitoring all attributes. attributeOldValue lets you specify whether or not you want the previous va...
...notifyUser("Attribute name " + mutation.attributeName + " changed to " + mutation.target[mutation.attributeName] + " (was " + mutation.oldValue + ")"); break; } }); } var targetNode = document.querySelector("#target"); var observer = new MutationObserver(callback); observer.observe(targetNode, { attributes: true, attributeOldValue: true }); The callback
() function--which will be passed into the observe
() method when starting the observer, looks at each item in the list of MutationRecord objects. For any items representing an attribute change (which can be detected by the value of MutationRecord.type being "attributes"), a function called notifyUser
() is used to tell the user the name of the attribute that changed as well as the attribute's new val...
...ch item in the list of MutationRecord objects. For any items representing an attribute change (which can be detected by the value of MutationRecord.type being "attributes"), a function called notifyUser
() is used to tell the user the name of the attribute that changed as well as the attribute's new value (mutation.target[mutation.attributeName]) and its old value (mutation.oldValue). When observe
() is called, the specified options are attributes and attributeOldValue, which means that changes to attribute values will be reported, and each mutation record will include the oldValue property specifying the attribute's previous value. Specifications Specification Status Comment DOMThe definition of 'MutationObserverInit.attributes' in that specification. Living ...
NavigatorPlugins.plugins - Web APIs
ect used to access Plugin objects either by name or as a list of items. The returned value is not a JavaScript array, but has the length property and supports accessing individual items using bracket notation (plugins[2]), as well as via item(index) and namedItem("name") methods. Examples The following example function returns the version of the Shockwave Flash plugin. function getFlashVersion
() { var flash = navigator.plugins.namedItem('Shockwave Flash'); if (typeof flash != 'object') { // flash is not present return undefined; } if(flash.version){ return flash.version; } else { //No version property (e.g. in Chrome) return flash.description.replace(/Shockwave Flash /,""); } } The following example displays information about the installed plugin(s). va...
...plugin(s). ...
...Length = navigator.plugins.length; document.body.innerHTML = pluginsLength + " Plugin(s)<br>" + '<table id="pluginTable"><thead>' +'<tr><th>Name</th><th>Filename</th><th>description</th><th>version</th></tr>' +'</thead><tbody></tbody></table>'; var table = document.getElementById('pluginTable'); for(var i = 0; i < pluginsLength; i++) { let newRow = table.insertRow
(); newRow.insertCell
().textContent = navigator.plugins[i].name; newRow.insertCell
().textContent = navigator.plugins[i].filename; newRow.insertCell
().textContent = navigator.plugins[i].description; newRow.insertCell
().textContent = navigator.plugins[i].version?navigator.plugins[i].version:""; } Notes The Plugin object exposes a small interface for getting information about the various plugins installed in your b...
OES_texture_float - Web APIs
The OES_texture_float extension is part of the WebGL API and exposes floating-point pixel types for textures. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default. Extended methods This extension extends WebGLRenderingContext.texImage2D
() and WebGLRenderingContext.texSubImage2D
(): The type parameter now accepts gl.FLOAT. The pixels parameter now accepts an ArrayBufferView of type Float32Array. Limitation: Linear filtering Linear filtering on floating-point textures is not allowed with this extension. If you set the mag...
... To use linear filtering on floating-point textures, enable the OES_texture_float_linear extension in addition to this extension. ...
... use linear filtering on floating-point textures, enable the OES_texture_float_linear extension in addition to this extension. Floating-point color buffers This extension implicitly enables the WEBGL_color_buffer_float extension (if supported), which allows rendering to 32-bit floating-point color buffers. Examples var ext = gl.getExtension('OES_texture_float'); var texture = gl.createTexture
(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.FLOAT, image); Specifications Specification Status Comment OES_texture_floatThe definition of 'OES_texture_float' in that specification. Recommendation Initial definition. ...
OES_texture_float_linear - Web APIs
The OES_texture_float_linear extension is part of the WebGL API and allows linear filtering with floating-point pixel types for textures. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is available to both, WebGL1 and WebGL2 contexts. Linear filtering The OES_texture_float extension alone does not allow linear filtering with floating-point textures. This extension enables this ability. ...
...nsions in the WebGL tutorial. Availability: This extension is available to both, WebGL1 and WebGL2 contexts. Linear filtering The OES_texture_float extension alone does not allow linear filtering with floating-point textures. This extension enables this ability. ...
...With the help of this extension, you can now set the magnification or minification filter in the WebGLRenderingContext.texParameter
() method to one of gl.LINEAR, gl.LINEAR_MIPMAP_NEAREST, gl.NEAREST_MIPMAP_LINEAR, or gl.LINEAR_MIPMAP_LINEAR, and use floating-point textures. Examples gl.getExtension('OES_texture_float'); gl.getExtension('OES_texture_float_linear'); var texture = gl.createTexture
(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.FLOAT, image); Specifications Specification Status Comment OES_texture_float_linearThe definition of 'OES_texture_float_linear' in that specification. Recommendation Initial definition. ...
OES_texture_half_float - Web APIs
The OES_texture_half_float extension is part of the WebGL API and adds texture formats with 16- (aka half float) and 32-bit floating-point components. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default. The constant in WebGL2 is gl.HALF_FLOAT. Constants ext.HALF_FLOAT_OES Half floating-point type (16-bit). Extended methods This extension extends WebGLRenderingContext.texImage2D
() and WebGLRenderingContext.texSubImage2D
(): The type parameter now accepts ext.HALF_FLOAT_OES. Limitation: Linear filtering Linear filt...
...type (16-bit). Extended methods This extension extends WebGLRenderingContext.texImage2D
() and WebGLRenderingContext.texSubImage2D
(): The type parameter now accepts ext.HALF_FLOAT_OES. Limitation: Linear filtering Linear filtering on half floating-point textures is not allowed with this extension. If you set the magnification or minification filter in the WebGLRenderingContext.texParameter
() method to one of gl.LINEAR, gl.LINEAR_MIPMAP_NEAREST, gl.NEAREST_MIPMAP_LINEAR, or gl.LINEAR_MIPMAP_LINEAR, and use half floating-point textures, the texture will be marked as incomplete. To use linear filtering on half floating-point textures, enable the OES_texture_half_float_linear extension in addition to this extension. Half floating-point color buffers This extension implicitly enables t...
...ring on half floating-point textures, enable the OES_texture_half_float_linear extension in addition to this extension. Half floating-point color buffers This extension implicitly enables the EXT_color_buffer_half_float extension (if supported), which allows rendering to 16-bit floating point formats. Examples var ext = gl.getExtension('OES_texture_half_float'); var texture = gl.createTexture
(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, ext.HALF_FLOAT_OES, image); Specifications Specification Status Comment OES_texture_half_floatThe definition of 'OES_texture_half_float' in that specification. Recommendation Initial definition. ...
OES_texture_half_float_linear - Web APIs
The OES_texture_half_float_linear extension is part of the WebGL API and allows linear filtering with half floating-point pixel types for textures. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is available to both, WebGL1 and WebGL2 contexts. Linear filtering The OES_texture_half_float extension alone does not allow linear filtering with half floating-point textures. This extension enables this ability. ...
...the WebGL tutorial. Availability: This extension is available to both, WebGL1 and WebGL2 contexts. Linear filtering The OES_texture_half_float extension alone does not allow linear filtering with half floating-point textures. This extension enables this ability. ...
..., you can now set the magnification or minification filter in the WebGLRenderingContext.texParameter
() method to one of gl.LINEAR, gl.LINEAR_MIPMAP_NEAREST, gl.NEAREST_MIPMAP_LINEAR, or gl.LINEAR_MIPMAP_LINEAR, and use half floating-point textures. Examples var halfFloat = gl.getExtension('OES_texture_half_float'); gl.getExtension('OES_texture_half_float_linear'); var texture = gl.createTexture
(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, halfFloat.HALF_FLOAT_OES, image); Specifications Specification Status Comment OES_texture_half_float_linearThe definition of 'OES_texture_half_float_linear' in that specification. Recommendation Initial defi...
OrientationSensor - Web APIs
ructions. Interfaces based on OrientationSensor Below is a list of interfaces based on the OrientationSensor interface. AbsoluteOrientationSensor RelativeOrientationSensor Properties OrientationSensor.quaternion Returns a four element Array whose elements contain the components of the unit quaternion representing the device's orientation. Methods OrientationSensor.populateMatrix
() Populates the given object with the rotation matrix based on the latest sensor reading. The rotation maxtrix is shown below. Examples Basic Example The following example, which is loosely based on Intel's Orientation Phone demo, instantiates an AbsoluteOrientationSensor with a frequency of 60 times a second. On each reading it uses OrientationSensor.quaternion to rotate a visual model of a ...
...llowing example, which is loosely based on Intel's Orientation Phone demo, instantiates an AbsoluteOrientationSensor with a frequency of 60 times a second. On each reading it uses OrientationSensor.quaternion to rotate a visual model of a phone. const options = { frequency: 60, referenceFrame: 'device' }; const sensor = new AbsoluteOrientationSensor(options); sensor.addEventListener('reading',
() => { // model is a Three.js object instantiated elsewhere. model.quaternion.fromArray(sensor.quaternion).inverse
(); }); sensor.addEventListener('error', error => { if (event.error.name == 'NotReadableError') { console.log("Sensor is not available."); } }); sensor.start
(); Permissions Example Using orientation sensors requires requsting permissions for multiple device sensors. Becuas...
...EventListener('error', error => { if (event.error.name == 'NotReadableError') { console.log("Sensor is not available."); } }); sensor.start
(); Permissions Example Using orientation sensors requires requsting permissions for multiple device sensors. Becuase the Permissions uses promises, a good way to request permissions is to use Promise.all. const sensor = new AbsoluteOrientationSensor
(); Promise.all([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...
OscillatorNode.detune - Web APIs
The detune property of the OscillatorNode interface is an a-rate AudioParam representing detuning of oscillation in cents. Syntax var oscillator = audioCtx.createOscillator
(); oscillator.detune.setValueAtTime(100, audioCtx.currentTime); // value in cents Note: though the AudioParam returned is read-only, the value it represents is not. Value An a-rate AudioParam. Example The following example shows basic usage of an AudioContext to create an oscillator node. For applied examples/information, check out our Violent Theremin demo (see app.js for relevant code). ...
...AudioParam returned is read-only, the value it represents is not. Value An a-rate AudioParam. Example The following example shows basic usage of an AudioContext to create an oscillator node. For applied examples/information, check out our Violent Theremin demo (see app.js for relevant code). ...
... An a-rate AudioParam. Example The following example shows basic usage of an AudioContext to create an oscillator node. For applied examples/information, check out our Violent Theremin demo (see app.js for relevant code). // create web audio api context var audioCtx = new (window.AudioContext || window.webkitAudioContext)
(); // create Oscillator node var oscillator = audioCtx.createOscillator
(); oscillator.type = 'square'; oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // value in hertz oscillator.detune.setValueAtTime(100, audioCtx.currentTime); // value in cents oscillator.start
(); Specifications Specification Status Comment Web Audio APIThe definition of 'detune' in that specification. Working Draft ...
PaintWorklet - Web APIs
The PaintWorklet interface of the CSS Painting API programmatically generates an image where a CSS property expects a file. Access this interface through CSS.paintWorklet. Properties PaintWorklet.devicePixelRatio Returns the current device's ratio of physical pixels to logical pixels. Event handlers None. Methods This interface inherits methods from Worklet. PaintWorklet.registerPaint
() Registers a class programmatically generate an image where a CSS property expects a file. CSS.PaintWorklet.addModule
() The addModule
() method, inhertied from the Worklet interface loads the module in the given JavaScript file and adds it to the current PaintWorklet. Examples The following three examples go together to show creating, loading, and using a PaintWorklet. Create a PaintWorklet ...
....addModule
() The addModule
() method, inhertied from the Worklet interface loads the module in the given JavaScript file and adds it to the current PaintWorklet. Examples The following three examples go together to show creating, loading, and using a PaintWorklet. Create a PaintWorklet The following shows an example worklet module. This should be in a separate js file. Note that registerPaint
() is called without a reference to PaintWorklet. ...
...int
() is called without a reference to PaintWorklet. class CheckerboardPainter { paint(ctx, geom, properties) { // Use `ctx` as if it was a normal canvas const colors = ['red', 'green', 'blue']; const size = 32; for(let y = 0; y < geom.height/size; y++) { for(let x = 0; x < geom.width/size; x++) { const color = colors[(x + y) % colors.length]; ctx.beginPath
(); ctx.fillStyle = color; ctx.rect(x * size, y * size, size, size); ctx.fill
(); } } } } // Register our class under a specific name registerPaint('checkerboard', CheckerboardPainter); Load a PaintWorklet The following example demonstrates loading the above worklet from its js file and does so by feature detection. <script> if ('paintWorklet' in CSS) { C...
PannerNode.coneOuterGain - Web APIs
The default is 0, and its value can be in the range 0-1. ...
...The default is 0, and its value can be in the range 0-1. ...
... 90) * (Math.PI / 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
PasswordCredential - Web APIs
The interface of the Credential Management API provides information about a username/password pair. In supporting browsers an instance of this class may be passed in the credential member of the init object for global fetch. Note: This interface is restricted to top-level contexts and cannot be used from an <iframe>. Constructor PasswordCredential
()Secure context Creates a new PasswordCredential object. Properties Inherits properties from its ancestor, Credential. PasswordCredential.additionalData Secure context One of a FormData instance, a URLSearchParams instance, or null. The data in the objects will be added to the request body and sent to the remote endpoint with the credentials. PasswordCredential.iconURL Read only Secure context A USVString containing a URL poin...
... the password field when submitting the current object to a remote endpoint via fetch. This property defaults to 'password', but may be overridden to match whatever the backend service expects. Event handlers None. Methods None. Examples var cred = new PasswordCredential({ id: id, password: password, name: name, iconURL: iconUrl }); navigator.credentials.store(cred) .then(function
() { // Do something else. }); Specifications Specification Status Comment Credential Management Level 1 Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull reques...
... WebView Android Full support 51Chrome Android Full support 51Firefox Android ? Opera Android ? Safari iOS ? Samsung Internet Android Full support 5.0PasswordCredential
() constructor Non-standardChrome Full support 51Edge Full support <=79Firefox ? IE ? Opera ? Safari ? WebView Android Full support 51Chrome Androi...
PaymentResponse.onpayerdetailchange - Web APIs
ction which is called to handle the payerdetailchange event when the user makes changes to their personal information while editing a payment request form. ...
...user, requesting that any mistakes be corrected // Options for PaymentRequest
(), indicating that shipping address, // payer email address, name, and phone number all be collected. const options = { requestShipping: true, requestPayerEmail: true, requestPayerName: true, requestPayerPhone: true, }; const request = new PaymentRequest(methods, details, options); const response = request.show
(); // Get the data from the response let { payerName: oldPayerName, payerEmail: oldPayerEmail, payerPhone: oldPayerPhone, } = response; // Set up a handler for payerdetailchange events, to // request corrections as needed. response.onpayerdetailchange = async ev => { const promisesToValidate = []; const { payerName, payerEmail, payerPhone } = response; // Validate each value which ...
... Candidate Recommendation Initial definition. ...
Payment processing concepts - Web APIs
using some form of cryptographic challenge. If the merchant doesn't successfully validate, it's not allowed to use the payment handler. The exact validation technology depends on the payment handler, and merchant validation is entirely optional. In the end, the only thing that the web site or app is responsible for is fetching the merchant's validation key and passing it into the event's complete
() method. paymentRequest.onmerchantvalidation = function(event) { event.complete(fetchValidationData(event.validationURL)); } In this example, fetchValidationData
() is a function which loads the payment handler specific identifying information from the address given by validationURL. Note this function must go through the merchant server, because a client typically does not access the validati...
... Thus, it's important to note that the user agent never sends a merchantvalidation event, unless the user agent itself implements a payment handler. ...
... merchantvalidation event, unless the user agent itself implements a payment handler. For instance, Safari has integrated support for Apple Pay, so the Apple Pay payment handler uses this to ensure that Apple Pay can be used to pay the merchant by sending merchantvalidation to the client, instructing it to fetch the server's validation data and deliver it to the payment handler by calling complete
(). Specifications Specification Status Comment Payment Request API Candidate Recommendation Initial definition. Basic Card Payment Working Draft Defines BasicCardRequest and BasicCardResponse. Payment Method Identifiers Candidate Recommendation Defines payment method identifiers and how they are validated, and, where applicable, minted a...
Pbkdf2Params - Web APIs
The Pbkdf2Params dictionary of the Web Crypto API represents the object that should be passed as the algorithm parameter into SubtleCrypto.deriveKey
(), when using the PBKDF2 algorithm. Properties name A DOMString. This should be set to PBKDF2. hash A DOMString representing the digest algorithm to use. This may be one of: SHA-1 SHA-256 SHA-384 SHA-512 Warning: SHA-1 is considered vulnerable in most cryptographic applications, but is still considered safe in PBKDF2. However, it's advisable to transition away from it everywhere, so unless you need to use SHA-1, don't. Use a different digest algorithm instead. ...
... SHA-1 is considered vulnerable in most cryptographic applications, but is still considered safe in PBKDF2. However, it's advisable to transition away from it everywhere, so unless you need to use SHA-1, don't. Use a different digest algorithm instead. salt A BufferSource. This should be a random or pseudo-random value of at least 16 bytes. Unlike the input key material passed into deriveKey
(), salt does not need to be kept secret. iterations A Number representing the number of times the hash function will be executed in deriveKey
(). This determines how computationally expensive (that is, slow) the deriveKey
() operation will be. In this context, slow is good, since it makes it more expensive for an attacker to run a dictionary attack against the keys. The general guidance here is to ...
...omputationally expensive (that is, slow) the deriveKey
() operation will be. In this context, slow is good, since it makes it more expensive for an attacker to run a dictionary attack against the keys. The general guidance here is to use as many iterations as possible, subject to keeping an acceptable level of performance for your application. Examples See the examples for SubtleCrypto.deriveKey
(). Specifications Specification Status Comment Web Cryptography APIThe definition of 'SubtleCrypto.Pbkdf2Params' in that specification. Recommendation ...
PerformanceEntry.entryType - Web APIs
y frame, navigation PerformanceFrameTiming, PerformanceNavigationTiming URL The document's address. resource PerformanceResourceTiming URL The resolved URL of the requested resource. This value doesn't change even if the request is redirected. mark PerformanceMark DOMString The name used when the mark was created by calling performance.mark
(). measure PerformanceMeasure DOMString name used when the measure was created by calling performance.measure
(). paint PerformancePaintTiming DOMString Either 'first-paint' or 'first-contentful-paint'. longtask PerformanceLongTaskTiming DOMString reports instances of long tasks Example The following example shows the use of the ...
...ing name used when the measure was created by calling performance.measure
(). paint PerformancePaintTiming DOMString Either 'first-paint' or 'first-contentful-paint'. longtask PerformanceLongTaskTiming DOMString reports instances of long tasks Example The following example shows the use of the entryType property. ...
...ormanceLongTaskTiming DOMString reports instances of long tasks Example The following example shows the use of the entryType property. ...
PerformanceNavigationTiming.type - Web APIs
-only property returns a string representing the type of navigation. The value must be one of the following: navigate Navigation started by clicking a link, entering the URL in the browser's address bar, form submission, or initializing through a script operation other than reload and back_forward as listed below. reload Navigation is through the browser's reload operation or location.reload
(). ...
...r's reload operation or location.reload
(). back_forward Navigation is through the browser's history traversal operation. prerender Navigation is initiated by a prerender hint. This property is Read only . Syntax perfEntry.type; Return Value A string which is one of the values listed above. Example The following example illustrates this property's usage. ...
...on.reload
(). back_forward Navigation is through the browser's history traversal operation. prerender Navigation is initiated by a prerender hint. This property is Read only . Syntax perfEntry.type; Return Value A string which is one of the values listed above. Example The following example illustrates this property's usage. ...
PeriodicWave - Web APIs
The PeriodicWave interface defines a periodic waveform that can be used to shape the output of an OscillatorNode. PeriodicWave has no inputs or outputs; it is used to define custom oscillators when calling OscillatorNode.setPeriodicWave
(). The PeriodicWave itself is created/returned by AudioContext.createPeriodicWave
(). Constructor PeriodicWave.PeriodicWave
() Creates a new PeriodicWave object instance using the default values for all properties. If you wish to establish custom property values at the outset, use the AudioContext.createPeriodicWave
() factory method instead. Properties None; also, PeriodicWave doesn't inherit any properties. Methods None; also, PeriodicWave doesn't inherit any methods. Example The following example illustrates simple usage of createPeriodicWave(...
...ave
() factory method instead. Properties None; also, PeriodicWave doesn't inherit any properties. Methods None; also, PeriodicWave doesn't inherit any methods. Example The following example illustrates simple usage of createPeriodicWave
(), to create a PeriodicWave object containing a simple sine wave. var real = new Float32Array(2); var imag = new Float32Array(2); var ac = new AudioContext
(); var osc = ac.createOscillator
(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createPeriodicWave(real, imag, {disableNormalization: true}); osc.setPeriodicWave(wave); osc.connect(ac.destination); osc.start
(); osc.stop(2); This works because a sound that contains only a fundamental tone is by definition a sine wave Here, we create a PeriodicWave with two values. The fi...
... values. The first value is the DC offset, which is the value at which the oscillator starts. 0 is good here, because we want to start the curve at the middle of the [-1.0; 1.0] range. The second and subsequent values are sine and cosine components. You can think of it as the result of a Fourier transform, where you get frequency domain values from time domain value. Here, with createPeriodicWave
(), you specify the frequencies, and the browser performs an inverse Fourier transform to get a time domain buffer for the frequency of the oscillator. Here, we only set one component at full volume (1.0) on the fundamental tone, so we get a sine wave. The coefficients of the Fourier transform should be given in ascending order (i.e. (a+bi)ei,(c+di)e2i,(f+gi)e3i\left(a+bi\right)e^{i} , \left(c+di\r...
Permissions - Web APIs
The Permissions interface of the Permissions API provides the core Permission API functionality, such as methods for querying and revoking permissions Methods Permissions.query
() Returns the user permission status for a given API. Permissions.request
() Requests permission to use a given API. This is not currently supported in any browser. Permissions.requestAll
() Requests permission to use a given set of APIs. This is not currently supported in any browser. Permissions.revoke
() Revokes the permission currently set on a given API. ...
...}); Specification Specification Status Comment PermissionsThe definition of 'Permissions' in that specification. Working Draft Initial definition. ...
...}); Specification Specification Status Comment PermissionsThe definition of 'Permissions' in that specification. Working Draft Initial definition. ...
Multi-touch interaction - Web APIs
#target3 { background: white; border: 1px solid black; } </style> Global state To support multi-touch interaction, preserving a pointer's event state during various event phases is required. This application uses three arrays to cache event state, one cache per target element. // Log events flag var logEvents = false; // Event caches, one per touch target var evCache1 = new Array
(); var evCache2 = new Array
(); var evCache3 = new Array
(); Register event handlers Event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup. The handler for pointerup is used for the pointercancel, pointerout and pointerleave events, since these four events have the same semantics in this application. function set_handlers(name) { // Install event ...
...tById(name); el.onpointerdown = pointerdown_handler; el.onpointermove = pointermove_handler; // Use same handler for pointer{up,cancel,out,leave} events since // the semantics for these events - in this app - are the same. el.onpointerup = pointerup_handler; el.onpointercancel = pointerup_handler; el.onpointerout = pointerup_handler; el.onpointerleave = pointerup_handler; } function init
() { set_handlers("target1"); set_handlers("target2"); set_handlers("target3"); } Pointer down The pointerdown event is fired when a pointer (mouse, pen/stylus or touch point on a touchscreen) makes contact with the contact surface. The event's state must be cached, in case this down event is part of a multi-touch interaction. In this application, when a pointer is placed down on an element, ...
...event(ev); update_background(ev); ev.target.style.border = "1px solid black"; } Application UI The application uses <div> elements for the touch areas and provides buttons to enable logging and to clear the log. To prevent the browser's default touch behavior from overriding this application's pointer handling, the touch-action property is applied to the <body> element. ...
Pinch zoom gestures - Web APIs
' target areas. <style> div { margin: 0em; padding: 2em; } #target { background: white; border: 1px solid black; } </style> Global state Supporting a two-pointer gesture requires preserving a pointer's event state during various event phases. This application uses two global variables to cache the event state. ...
...ent state. // Global vars to cache event state var evCache = new Array
(); var prevDiff = -1; Register event handlers Event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup. The handler for pointerup is used for the pointercancel, pointerout and pointerleave events since these four events have the same semantics in this application. function init
() { // Install event handlers for the pointer target var el=document.getElementById("target"); el.onpointerdown = pointerdown_handler; el.onpointermove = pointermove_handler; // Use same handler for pointer{up,cancel,out,leave} events since // the semantics for these events - in this app - are the same. el.onpointerup = pointerup_handler; el.onpointercancel = pointerup_handler; el.onpoint...
...han two then reset diff tracker if (evCache.length < 2) { prevDiff = -1; } } Application UI The application uses a <div> element for the touch area and provides buttons to enable logging and to clear the log. To prevent the browser's default touch behavior from overriding this application's pointer handling, the touch-action property is applied to the <body> element. ...
PopStateEvent - Web APIs
PopStateEvent is an event handler for the popstate event on the window. A popstate event is dispatched to the window every time the active history entry changes between two history entries for the same document. If the history entry being activated was created by a call to history.pushState
() or was affected by a call to history.replaceState
(), the popstate event's state property contains a copy of the history entry's state object. Note: Just calling history.pushState
() or history.replaceState
() won't trigger a popstate event. The popstate event is only triggered by doing a browser action such as a clicking on the back button (or calling history.back
() in JavaScript). And the event is only triggered when the user navigates between two history entries for the same document. No...
...e at http://example.com/example.html running the following code will generate alerts as indicated: window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + JSON.stringify(event.state)); }; history.pushState({page: 1}, "title 1", "?page=1"); history.pushState({page: 2}, "title 2", "?page=2"); history.replaceState({page: 3}, "title 3", "?page=3"); history.back
(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back
(); // alerts "location: http://example.com/example.html, state: null history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3} Note that even though the original history entry (for http://example.com/example.html) has no state object associated with it, a popstate e...
... Specifications Specification Status Comment HTML Living StandardThe definition of 'PopStateEvent' in that specification. ...
ProgressEvent - Web APIs
Properties Also inherits properties from its parent Event. ProgressEvent.lengthComputable Read only Is a Boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not. ProgressEvent.loaded Read only ...
...elf, not headers and other overhead. ProgressEvent.total Read only Is an unsigned long long representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this only represent the content itself, not headers and other overhead. Methods Also inherits methods from its parent Event. ...
... Also inherits methods from its parent Event. ProgressEvent.initProgressEvent
() Initializes a ProgressEvent created using the deprecated Document.createEvent("ProgressEvent") method. Examples The following example adds a ProgressEvent to a new XMLHTTPRequest and uses it to display the status of the request. var progressBar = document.getElementById("p"), client = new XMLHttpRequest
() client.open("GET", "magical-unicorns") client.onprogress = function(pe) { if(pe.lengthComputable) { progressBar.max = pe.total progressBar.value = pe.loaded } } client.onloadend = function(pe) { progressBar.value = pe.loaded } client.send
() Specifications Specification Status Comment XMLHttpRequestThe definition of 'ProgressEvent' in that specification. ...
RTCDataChannel.bufferedAmountLowThreshold - Web APIs
t is considered "low." The default value is 0. When the number of buffered outgoing bytes, as indicated by the bufferedAmount property, falls to or below this value, a bufferedamountlow event is fired. This event may be used, for example, to implement code which queues more messages to be sent whenever there's room to buffer them. Listeners may be added with onbufferedamountlow or addEventListener
(). The user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. As messages are actually sent, this value is reduced accordingly. bufferedamountlow events are not fired after the data channel is closed. Syntax var threshold = aDataChannel.bufferedAmountLowThreshold; aDataChannel.bufferedA...
...untLowThreshold = threshold; Value The number of queued outgoing data bytes below which the buffer is considered to be "low." Example In this snippet of code, bufferedAmountLowThreshold is set to 64kB, and a handler for the bufferedamountlow event is established by setting the RTCDataChannel.onbufferedamountlow property to a function which should send more data into the buffer by calling send
(). ...
... In this snippet of code, bufferedAmountLowThreshold is set to 64kB, and a handler for the bufferedamountlow event is established by setting the RTCDataChannel.onbufferedamountlow property to a function which should send more data into the buffer by calling send
(). var dc = peerConnection.createDataChannel("File Transfer"); dc.bufferedAmountLowThreshold = 65535; dc.onbufferedamountlow = function
() { /* use send
() to queue more data to be sent */ }; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.bufferedAmountLowThreshold' in that specification. Candidate Recommendation Initial specification. ...
RTCDataChannelEvent - Web APIs
The RTCDataChannelEvent
() constructor returns a new RTCDataChannelEvent object, which represents a datachannel event. These events sent to an RTCPeerConnection when its remote peer is asking to open an RTCDataChannel between the two peers. You will rarely if ever construct an RTCDataChannelEvent by hand; instead, the WebRTC layer will generate and deliver them to you at the appropriate time. Just listen for the datachannel event to be received by the RTCPeerConnection and when you receive it, use the RTCDataChannelEvent.channel property to gain access to the data channel which has been opened. ...
...peers. You will rarely if ever construct an RTCDataChannelEvent by hand; instead, the WebRTC layer will generate and deliver them to you at the appropriate time. Just listen for the datachannel event to be received by the RTCPeerConnection and when you receive it, use the RTCDataChannelEvent.channel property to gain access to the data channel which has been opened. ...
...ever construct an RTCDataChannelEvent by hand; instead, the WebRTC layer will generate and deliver them to you at the appropriate time. Just listen for the datachannel event to be received by the RTCPeerConnection and when you receive it, use the RTCDataChannelEvent.channel property to gain access to the data channel which has been opened. ...
RTCDtlsTransport - Web APIs
sport contains a reference to the underlying RTCIceTransport.state Read only The state read-only property of the RTCDtlsTransport interface provides information which describes a Datagram Transport Layer Security (DTLS) transport state.MethodsThis interface has no methods. Description Allocation of DTLS transports RTCDtlsTransport objects are created when an app calls either setLocalDescription
() or setRemoteDescription
(). The number of DTLS transports created and how they're used depends on the bundling mode used when creating the RTCPeerConnection. Whether bundling is used depends on what the other endpoint is able to negotiate. All browsers support bundling, so when both endpoints are browsers, you can rest assured that bundling will be used. Some non-browser legacy endpoints, howeve...
...nels RTCDataChannels use SCTP to communicate. All of a peer connection's data channels share a single RTCSctpTransport, found in the connection's sctp property. You can, in turn, identify the RTCDtlsTransport used to securely encapsulate the data channels' SCTP communications by looking at the RTCSctpTransport object's transport property. Examples This example presents a function, tallySenders
(), which iterates over an RTCPeerConnection's RTCRtpSenders, tallying up how many of them are in various states. The function returns an object containing properties whose values indicate how many of the senders are in each state. let pc = new RTCPeerConnection({ bundlePolicy: "max-bundle" }); /* ... */ function tallySenders(pc) { let results = { transportMissing: 0, connectionPending:...
...tates. The function returns an object containing properties whose values indicate how many of the senders are in each state. let pc = new RTCPeerConnection({ bundlePolicy: "max-bundle" }); /* ... ...
RTCError - Web APIs
The RTCError interface describes an error which has occurred while handling WebRTC operations. It's based upon the standard DOMException interface that describes general DOM errors. Constructor RTCError
() Creates and returns a new RTCError object initialized with the properties of the provided RTCErrorInit dictionary and, optionally, a string to use as the value of the error's message property. Properties In addition to the properties defined by the parent interface, DOMException, RTCError includes the following properties: errorDetail Read only A DOMString specifying the WebRTC-specific error code identifying the type of error that occurred. receivedAlert Read only An unsigned long integer value indicating the fatal DTLS error which was received from the network. Only vali...
... Any other error i...
...yAlertMessage("Data Channel Error", alertMessage); } else { terminateMyConnection
(); } }); If the error is an SDP syntax error--indicated by its errorDetail property being sdp-syntax-error--, a message string is constructed to present the error message and the line number within the SDP at which the error occurred. This message is then displayed using a function called showMyAlertMessage
(), which stands in for whatever output mechanism this code might use. Any other error is treated as terminal, causing a terminateMyConnection
() function to be called. The above example uses addEventListener
() to add the handler for error events. You can also use the RTCDataChannel object's onerror event handler property, like this: dataChannel.onerror = (event) => { let error = event.error; ...
RTCIceCandidate.type - Web APIs
You can't specify the value of type in the options object, but the address is automatically extracted from the candidate a-line, if it's formatted properly, being taken from its cand-type field. Syntax var type = RTCIceCandidate.type; Value A DOMString whose value is one of those defined by the RTCIceCandidateType enumerated type. These candidate types are listed in order of priority; the higher in the list they are, the more efficient they are. ...
...ary address assigned by the STUN server to represent the candidate's peer anonymously. relay The candidate is a relay candidate, obtained from a TURN server. The relay candidate's IP address is an address the TURN server uses to forward the media between the two peers. ...
... that information was missing from the candidate's a-line, which will cause RTCPeerConnection.addIceCandidate
() to throw an OperationError exception. Example In this example, the candidate's type is used to present a modified user interface for host candidates (those where the ip refers directly to the remote peer, rather than an intermediary). if (candidate.type == "host") { showHostControls
(); } else { hideHostControls
(); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCIceCandidate.type' in that specification. Candidate Recommendation Initial definition. ...
RTCIceCandidateInit - Web APIs
Properties candidate Optional The ICE candidate-attribute. ...
... Properties candidate Optional The ICE candidate-attribute. ...
... Properties candidate Optional The ICE candidate-attribute. ...
RTCIceCandidatePair - Web APIs
The RTCIceCandidatePair dictionary describes a pair of ICE candidates which together comprise a description of a viable connection between two WebRTC endpoints. It is used as the return value from RTCIceTransport.getSelectedCandidatePair
() to identify the currently-selected candidate pair identified by the ICE agent. Properties local An RTCIceCandidate describing the configuration of the local end of the connection. remote The RTCIceCandidate describing the configuration of the remote end of the connection. ...
... An RTCIceCandidate describing the configuration of the local end of the connection. remote The RTCIceCandidate describing the configuration of the remote end of the connection. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. ...
...p to update an on-screen display showing the protocol used by the currently selected candidate pair. var iceTransport = pc.getSenders
()[0].transport.iceTransport; var localProto = document.getElementById("local-protocol"); var remoteProto = document.getElementById("remote-protocol"); iceTransport.onselectedcandidatepairchange = function(event) { var pair = iceTransport.getSelectedCandidatePair
(); localProtocol.innerText = pair.local.protocol.toUpperCase
(); remoteProtocol.innerText = pair.remote.protocol.toUpperCase
(); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCIceCandidatePair' in that specification. Candidate Recommendation Initial specification. ...
RTCIceTransport: gatheringstatechange event - Web APIs
the connection including every RTCIceTransport used by every RTCRtpSender and every RTCRtpReceiver on the entire connection. In contrast, gatheringstatechange represents changes to the candidate gathering state for a single transport. Examples This example creates a handler for gatheringstatechange events on each RTCRtpSender associated with a given RTCPeerConnection. ...
...RTCRtpReceiver on the entire connection. In contrast, gatheringstatechange represents changes to the candidate gathering state for a single transport. Examples This example creates a handler for gatheringstatechange events on each RTCRtpSender associated with a given RTCPeerConnection. ...
...etSenders
().forEach(sender => { sender.transport.iceTransport.addEventListener("gatheringstatechange", ev => { let transport = ev.target; if (transport.gatheringState === "complete") { /* this transport has finished gathering candidates, but others may still be working on it */ } }, false); Likewise, you can use the ongatheringstatechange event handler property: pc.getSenders
().forEach(sender => { sender.transport.iceTransport.ongatheringstatechange = ev => { let transport = ev.target; if (transport.gatheringState === "complete") { /* this transport has finished gathering candidates, but others may still be working on it */ } }; }); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication B...
RTCIceTransport.onselectedcandidatepairchange - Web APIs
candidate pair that the RTCIceTransport will be using for communication with the remote peer. This event will occur at least once, and may occur more than once if the ICE agent continues to identify candidate pairs that will work better, more closely match the requested parameters, and so forth. The event handler can determine the current state by calling the transport's getSelectedCandidatePair
() method, which returns a RTCIceCandidatePair whose RTCIceCandidatePair.local and RTCIceCandidatePair.global properties specify RTCIceCandidate objects describing the local and remote candidates that are currently being used. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candid...
...r whose RTCIceCandidatePair.local and RTCIceCandidatePair.global properties specify RTCIceCandidate objects describing the local and remote candidates that are currently being used. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. ...
...p to update an on-screen display showing the protocol used by the currently selected candidate pair. var iceTransport = pc.getSenders
()[0].transport.iceTransport; var localProto = document.getElementById("local-protocol"); var remoteProto = document.getElementById("remote-protocol"); iceTransport.onselectedcandidatepairchange = function(event) { var pair = iceTransport.getSelectedCandidatePair
(); localProtocol.innerText = pair.local.protocol.toUpperCase
(); remoteProtocol.innerText = pair.remote.protocol.toUpperCase
(); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCIceTransport.onselectedcandidatepairchange' in that specification. Candidate Recommendation Initial specification...
RTCIceTransport: statechange event - Web APIs
rifying, and selecting a valid candidate pair is prior to successfully connecting the two peers for WebRTC communications. ...
... the two peers for WebRTC communications. Bubbles No Cancelable No Interface Event Event handler property RTCIceTransport.onstatechange Examples Given an RTCPeerConnection, pc, the following code creates an event handler that calls a function named handleFailure
() if the ICE transport enters a failure state. ...
...that calls a function named handleFailure
() if the ICE transport enters a failure state. let iceTransport = pc.getSenders
()[0].transport.iceTransport; iceTransport.addEventListener("statechange", ev => { if (iceTransport.state === "failed") { handleFailure(pc); } }, false); The same code, using the onstatechange event handler property, looks like this: let iceTransport = pc.getSenders
()[0].transport.iceTransport; iceTransport.onstatechange = ev => { if (iceTransport.state === "failed") { handleFailure(pc); } }; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'statechange' in that specification. Candidate Recommendation ...
RTCPeerConnection.onaddstream - Web APIs
The RTCPeerConnection.onaddstream event handler is a property containing the code to execute when the addstream event, of type MediaStreamEvent, is received by this RTCPeerConnection. Such an event is sent when a MediaStream is added to this connection by the remote peer. The event is sent immediately after the call setRemoteDescription
() and doesn't wait for the result of the SDP negotiation. Important: This property has been removed from the specification; you should now use RTCPeerConnection.ontrack to watch for track events instead. It is included here in order to help you adapt existing code and understand existing samples, which may not be up-to-date yet. Syntax rtcPeerConnection.onaddstream = eventHandler; Value A function which handles addstream events. These events, of ty...
..., which may not be up-to-date yet. Syntax rtcPeerConnection.onaddstream = eventHandler; Value A function which handles addstream events. These events, of type MediaStreamEvent, are sent when streams are added to the connection by the remote peer. The first time an event occurs may be nearly immediately after the remote end of the connection is set using RTCPeerConnection.setRemoteDescription
(); it doesn't wait for a particular stream to be accepted or rejected using SDP negotiation. Example This code, based on an older version of our Signaling and video calling sample, responds to addstream events by setting the video source for a <video> element to the stream specified in the event, and then enabling a "hang up" button in the app's user interface. pc.onaddstream = function(event) {...
... ...
RTCPeerConnection.onsignalingstatechange - Web APIs
The onsignalingstatechange event handler property of the RTCPeerConnection interface specifies a function to be called when the signalingstatechange event occurs on an RTCPeerConnection interface. The function receives as input the event object of type Event; this event is sent when the peer connection's signalingState changes, which may happen either because of a call to setLocalDescription
() or to setRemoteDescription
(). Syntax rtcPeerConnection.onsignalingstatechange = errorHandler; Value Set this to a function which you provide that receives an Event object as input; this contains the signalingstatechange event. This event object doesn't provide details about what changed, but you can examine the signalingState property to determine what the new state is. You may also, as always, ...
...e = errorHandler; Value Set this to a function which you provide that receives an Event object as input; this contains the signalingstatechange event. This event object doesn't provide details about what changed, but you can examine the signalingState property to determine what the new state is. ...
... handle the event here */ }); Example This snippet shows a handler for signalingstatechange that looks for the "have-local-pranswer" signaling state--indicating that a remote offer has been received and a local description of type "pranswer" has been applied in response. pc.onsignalingstatechange = function(event) { if (pc.signalingState === "have-local-pranswer") { // setLocalDescription
() has been called with an answer } }; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.onsignalingstatechange' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection.peerIdentity - Web APIs
occcurs while attempting to validate an incoming identity assertion (that is, the information describing a peer's identity), the promise is rejected. If there isn't already a target peer identity, peerIdentity is set to a newly created promise and the process begins again, until the process succeeds or no further attempts to authenticate occur. ...
...already a target peer identity, peerIdentity is set to a newly created promise and the process begins again, until the process succeeds or no further attempts to authenticate occur. Note: The promise returned by setRemoteDescription
() cannot resolve until any target peer identity that's been set is validated. If the identity hasn't been validated yet, the promise returned by setRemoteDescription
() will be rejected. If there's no target peer identity, setRemoteDescription
() doesn't need to wait for validation to occur before it resolves. Example In this example, a function, getIdentityAssertion
(), is created which asynchronously waits for the peer's identity to be verified, then returns the identity to the caller. If an error occurs and the promise is rejected, this logs the error to the...
...*/ async function getIdentityAssertion(pc) { try { const identity = await pc.peerIdentity; return identity; } catch(err) { console.log("Error identifying remote peer: ", err); return null; } } Specifications Specification Status Comment Identity for WebRTC Candidate Recommendation Initial specification. ...
RTCSessionDescription - Web APIs
r The session description object describes a provisional answer; that is, a response to a previous offer that is not the final answer. It is usually employed by legacy hardware. rollback This special type with an empty session description is used to roll back to the previous stable state. Methods The RTCSessionDescription doesn't inherit any methods. RTCSessionDescription
() This constructor returns a new RTCSessionDescription. The parameter is a RTCSessionDescriptionInit dictionary containing the values to assign the two properties. RTCSessionDescription.toJSON
() Returns a JSON description of the object. The values of both properties, type and sdp, are contained in the generated JSON. Example signalingChannel.onmessage = function (evt) { if (!pc) ...
...roperties. RTCSessionDescription.toJSON
() Returns a JSON description of the object. The values of both properties, type and sdp, are contained in the generated JSON. ...
... Candidate Recommendation Initial definition. ...
Range.commonAncestorContainer - Web APIs
th refer to the same node, this node is the common ancestor container. Since a Range need not be continuous, and may also partially select nodes, this is a convenient way to find a Node which encloses a Range. This property is read-only. To change the ancestor container of a Node, consider using the various methods available to set the start and end positions of the Range, such as Range.setStart
() and Range.setEnd
(). Syntax rangeAncestor = range.commonAncestorContainer; Example In this example, we create an event listener to handle pointerup events on a list. The listener gets the common ancestors of each piece of selected text, and triggers an animation to highlight them. HTML <ul> <li>Strings <ul> <li>Cello</li> <li>Violin <ul> <li>First Chair</l...
... </ul> </li> </ul> CSS The .highlight class created below uses a set of CSS @keyframes to animate a fading outline. ...
... Living Standard No change. ...
ReadableStreamBYOBReader - Web APIs
The ReadableStreamBYOBReader interface of the Streams API represents a BYOB ("bring your own buffer") reader that can be used to read stream data supplied by the developer (e.g. a custom ReadableStream
() constructor). Constructor ReadableStreamBYOBReader
() Creates and returns a ReadableStreamBYOBReader object instance. Properties ReadableStreamBYOBReader.closed Read only Allows you to write code that responds to an end to the streaming process. Returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors. Methods ReadableStreamBYOBReader.cancel
() Cancels the stream, signaling a loss of interest in the stream by a consumer. The supplied reason argument will be given to the underlying source, which may or ma...
... Examples TBD. ...
... Examples TBD. ...
RelativeOrientationSensor - Web APIs
rant permission to the 'accelerometer', and 'gyroscope' device sensors 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 RelativeOrientationSensor.RelativeOrientationSensor
() Creates a new RelativeOrientationSensor object. Properties No specific properties; inherits methods from its ancestors OrientationSensor and Sensor. Event handlers No specific event handlers; inherits methods from its ancestor, Sensor. Methods No specific methods; inherits methods from its ancestors OrientationSensor and Sensor. Examples Basic Example The following example, which is lo...
...ntiates an RelativeOrientationSensor with a frequency of 60 times a second. Note that the Intel demo this is based on uses the AbsoluteOreintationSensor. On each reading it uses OrientationSensor.quaternion to rotate a visual model of a phone. const options = { frequency: 60, referenceFrame: 'device' }; const sensor = new RelativeOrientationSensor(options); sensor.addEventListener('reading',
() => { // model is a Three.js object instantiated elsewhere. model.quaternion.fromArray(sensor.quaternion).inverse
(); }); sensor.addEventListener('error', error => { if (event.error.name == 'NotReadableError') { console.log("Sensor is not available."); } }); sensor.start
(); Permissions Example Using orientation sensors requires requsting permissions for multiple device sensors. Becuas...
...EventListener('error', error => { if (event.error.name == 'NotReadableError') { console.log("Sensor is not available."); } }); sensor.start
(); Permissions Example Using orientation sensors requires requsting permissions for multiple device sensors. Becuase the Permissions uses promises, a good way to request permissions is to use Promise.all. const sensor = new RelativeOrientationSensor
(); Promise.all([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...
ResizeObserver - Web APIs
. See The box model for further explanation. ResizeObserver avoids infinite callback loops and cyclic dependencies that are often created when resizing via a callback function. It does this by only processing elements deeper in the DOM in subsequent frames. Implementations should, if they follow the specification, invoke resize events before paint and after layout. Constructor ResizeObserver
() Creates and returns a new ResizeObserver object. Properties None. Methods ResizeObserver.disconnect
() Unobserves all observed Element targets of a particular observer. ResizeObserver.observe
() Initiates the observing of a specified Element. ResizeObserver.unobserve
() Ends the observing of a specified Element. Examples In the resize-observer-text.html (see source) example, we use t...
...to the <div>'s width changing. ...
... Editor's Draft Initial definition. ...
Response.type - Web APIs
l, same origin response, with all headers exposed except "Set-Cookie" and "Set-Cookie2?. cors: Response was received from a valid cross-origin request. Certain headers and the body may be accessed. error: Network error. No useful information describing the error is available. The Response's status is 0, headers are empty and immutable. This is the type for a Response obtained from Response.error
(). opaque: Response for "no-cors" request to cross-origin resource. Severely restricted. opaqueredirect: The fetch request was made with redirect: "manual". The Response's status is 0, headers are empty, body is null and trailer is empty. Note: An "error" Response never really gets exposed to script: such a response to a fetch
() would reject the promise. Syntax var myType = response.type; ...
...is 0, headers are empty, body is null and trailer is empty. Note: An "error" Response never really gets exposed to script: such a response to a fetch
() would reject the promise. Syntax var myType = response.type; Value A ResponseType string indicating the type of the response. Example In our Fetch Response example (see Fetch Response live) we create a new Request object using the Request
() constructor, passing it a JPG path. We then fetch this request using fetch
(), extract a blob from the response using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch
() block we log the response type to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(m...
...se using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch
() block we log the response type to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.type); // returns basic by default response.blob
().then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); }); Specifications Specification Status Comment FetchThe definition of 'type' in that specification. Living Standard Initial definition ...
SVGGraphicsElement: paste event - Web APIs
Interface ClipboardEvent Event handler property onpaste If the cursor is in an editable context (for example, in a <textarea> or an element with contenteditable attribute set to true) then the default action is to insert the contents of the clipboard into the document at the cursor position. A handler for this event can access the clipboard contents by calling getData
() on the event's clipboardData property. To override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventDefault
(), and then insert its desired data manually. It's possible to construct and dispatch a synthetic paste event, but this will not affect the document's contents.
... Clipboard API and events Working Draft Initial definition ...
... Clipboard API and events Working Draft Initial definition ...
Screen Capture API - Web APIs
reen Capture API introduces additions to the existing Media Capture and Streams API to let the user select a screen or portion of a screen (such as a window) to capture as a media stream. This stream can then be recorded or shared with others over the network. Screen Capture API concepts and usage The Screen Capture API is relatively simple to use. ...
...eam. This stream can then be recorded or shared with others over the network. Screen Capture API concepts and usage The Screen Capture API is relatively simple to use. Its sole method is MediaDevices.getDisplayMedia
(), whose job is to ask the user to select a screen or portion of a screen to capture in the form of a MediaStream. To start capturing video from the screen, you call getDisplayMedia
() on the instance of Media navigator.mediaDevices: captureStream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions); The Promise returned by getDisplayMedia
() resolves to a MediaStream which streams the captured media. See the article Using the Screen Capture API for a more in-depth look at how to use the API to capture screen contents as a stream. Additions to existing interfa...
...MediaStream which streams the captured media. See the article Using the Screen Capture API for a more in-depth look at how to use the API to capture screen contents as a stream. Additions to existing interfaces The Screen Capture API doesn't have any interfaces of its own; instead, it adds one method to the existing MediaDevices interface. MediaDevices interface MediaDevices.getDisplayMedia
() The getDisplayMedia
() method is added to the MediaDevices interface. Similar to getUserMedia
(), this method creates a promise that resolves with a MediaStream containing the display area selected by the user, in a format that matches the specified options. Additions to existing dictionaries The Screen Capture API adds properties to the following dictionaries defined by other specifications. ...
ScrollToOptions - Web APIs
The ScrollToOptions dictionary of the CSSOM View spec contains properties specifying where an element should be scrolled to, and whether the scrolling should be smooth. A ScrollToOptions dictionary can be provided as a parameter for the following methods: Window.scroll
() Window.scrollBy
() Window.scrollTo
() Element.scroll
() Element.scrollBy
() Element.scrollTo
() Properties ScrollToOptions.top Specifies the number of pixels along the Y axis to scroll the window or element. ScrollToOptions.left Specifies the number of pixels along the X axis to scroll the window or element. ScrollToOptions.behavior Specifies whether the scrolling should animate smoothly, or happen instantly in a single jump. This is actually defined on the ScrollOptions dictionary, which is implemented by Scr...
...clude a form that allows the user to enter three values -- two numbers representing the left and top properties (i.e. the positions to scroll to along the X and Y axes), and a checkbox indicating whether they want smooth scrolling enabled or not. ...
...s (i.e. the positions to scroll to along the X and Y axes), and a checkbox indicating whether they want smooth scrolling enabled or not. When the form is submitted, an event handler is run that puts the entered values into a ScrollToOptions dictionary, and then invokes the Window.ScrollTo
() method, passing the dictionary as a parameter: form.addEventListener('submit', (e) => { e.preventDefault
(); var scrollOptions = { left: leftInput.value, top: topInput.value, behavior: scrollInput.checked ? 'smooth' : 'auto' } window.scrollTo(scrollOptions); }); Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'ScrollToOptions' in that specification. Working Draft ...
Sensor APIs - Web APIs
: 'device' }); accelerometer.addEventListener('error', event => { // Handle runtime errors. if (event.error.name === 'NotAllowedError') { // Branch to code for requesting permission. } else if (event.error.name === 'NotReadableError' ) { console.log('Cannot connect to the sensor.'); } }); accelerometer.addEventListener('reading',
() => reloadOnShake(accelerometer)); accelerometer.start
(); } catch (error) { // Handle construction errors. if (error.name === 'SecurityError') { // See the note above about feature policy. console.log('Sensor construction was blocked by a feature policy.'); } else if (error.name === 'ReferenceError') { console.log('Sensor is not supported by the User Agent.'...
...mission before attempting to use the sensor. navigator.permissions.query({ name: 'accelerometer' }) .then(result => { if (result.state === 'denied') { console.log('Permission to use accelerometer sensor is denied.'); return; } // Use the sensor. }); An alternative approach is to attempt to use the error and listen for the SecurityError. const sensor = new AbsoluteOrientationSensor
(); sensor.start
(); sensor.onerror = event => { if (event.error.name === 'SecurityError') console.log("No permissions to use AbsoluteOrientationSensor."); }; The following table describes for each sensor type, the name required for the Permissions API, the <iframe> element's allow attribute and the Feature-Policy directive. Sensor permissions Sensor Permission/Feature Policy Nam...
... AccelerometerSecure context Provides the acceleration applied to the device along all three axes. AmbientLightSensorSecure context Returns the current light level or illuminance of the ambient light around the hosting device. GyroscopeS...
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:...
...fication object itself. Note: Trying to create a notification inside the ServiceWorkerGlobalScope using the Notification
() constructor will throw an error. Syntax ServiceWorkerGlobalScope.onnotificationclick = function(NotificationEvent) { ... ...
... Living Standard Initial definition. ...
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
s 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. Consider using another method to synchronize subscription information between your service worker and the app server, or make sure your code using fetch
() is robust enough to handle cases where attempts to exchange data fail. Note: In earlier drafts of the specification, this...
... You can also use the onpushsubscriptionchange event handler property to set up the event handler: self.onpushsubscriptionchange = event => { event.waitUntil(swRegistration.p...
... }, body: JSON.stringify({ endpoint: subscription.endpoint }) }); }) ); }, false); When a pushsubscriptionchange event arrives, indicating that the subscription has expired, we resubscribe by calling the push manager's subscribe
() method. When the returned promise is resolved, we receive the new subscription. This is delivered to the app server using a fetch
() call to post a JSON formatted rendition of the subscription's endpoint to the app server. You can also use the onpushsubscriptionchange event handler property to set up the event handler: self.onpushsubscriptionchange = event => { event.waitUntil(swRegistration.pushManager.subscribe(event.oldSubscription.options) .then(subscription => { /* ... */ ) }; Specifications S...
SpeechSynthesisUtterance.onstart - Web APIs
The onstart property of the SpeechSynthesisUtterance interface represents an event handler that will run when the utterance has begun to be spoken (when the start event fires.) This occurs when the SpeechSynthesis.speak
() method is invoked. Syntax speechSynthesisUtteranceInstance.onstart = function
() { ... }; Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices
(); ... ...
...s.speak
() method is invoked. Syntax speechSynthesisUtteranceInstance.onstart = function
() { ... }; Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices
(); ... ...
... Draft ...
SpeechSynthesisUtterance.pitch - Web APIs
ce. Some speech synthesis engines or voices may constrain the minimum and maximum rates further. If SSML is used, this value will be overridden by prosody tags in the markup. ...
... maximum rates further. If SSML is used, this value will be overridden by prosody tags in the markup. Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices
(); ... ...
... Draft ...
SpeechSynthesisUtterance.rate - Web APIs
c. Some speech synthesis engines or voices may constrain the minimum and maximum rates further. If SSML is used, this value will be overridden by prosody tags in the markup. ...
... maximum rates further. If SSML is used, this value will be overridden by prosody tags in the markup. Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices
(); ... ...
... Draft ...
SpeechSynthesisUtterance.text - Web APIs
Hello I am speaking'; Value A DOMString representing the text to the synthesised. The maximum length of the text that can be spoken in each utterance is 32,767 characters. ...
...ynthesised. The maximum length of the text that can be spoken in each utterance is 32,767 characters. Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices
(); ... ...
... Draft ...
SpeechSynthesisUtterance.voice - Web APIs
The voice property of the SpeechSynthesisUtterance interface gets and sets the voice that will be used to speak the utterance. This should be set to one of the SpeechSynthesisVoice objects returned by SpeechSynthesis.getVoices
(). If not set by the time the utterance is spoken, the voice used will be the most suitable default voice available for the utterance's lang setting. Syntax var myVoice = speechSynthesisUtteranceInstance.voice; speechSynthesisUtteranceInstance.voice = speechSynthesisVoiceInstance; Value A SpeechSynthesisVoice object. Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices
(); ... in...
...thesisUtteranceInstance.voice = speechSynthesisVoiceInstance; Value A SpeechSynthesisVoice object. Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices
(); ... ...
...tVoices
(); ... inputForm.onsubmit = function(event) { event.preventDefault
(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedOption) { utterThis.voice = voices[i]; } } synth.speak(utterThis); inputTxt.blur
(); } Specifications Specification Status Comment Web Speech APIThe definition of 'voice' in that specification. Draft ...
SpeechSynthesisUtterance.volume - Web APIs
e = 0.5; Value A float that represents the volume value, between 0 (lowest) and 1 (highest.) If SSML is used, this value will be overridden by prosody tags in the markup. ...
...west) and 1 (highest.) If SSML is used, this value will be overridden by prosody tags in the markup. Examples var synth = window.speechSynthesis; var inputForm = document.querySelector('form'); var inputTxt = document.querySelector('input'); var voiceSelect = document.querySelector('select'); var voices = synth.getVoices
(); ... ...
... Draft ...
StereoPannerNode.pan - Web APIs
The pan property of the StereoPannerNode interface is an a-rate AudioParam representing the amount of panning to apply. The value can range between -1 (full left pan) and 1 (full right pan). Syntax var audioCtx = new AudioContext
(); var panNode = audioCtx.createStereoPanner
(); panNode.pan.value = -0.5; Returned value An a-rate AudioParam containing the panning to apply. Note: Though the AudioParam returned is read-only, the value it represents is not. Example In our StereoPannerNode example (see source code) HTML we have a simple <audio> element along with a slider <input> to increase and decrease pan value. In the JavaScript we create a MediaElementAudioSourceNode and a StereoPannerNode, and connect the two together using the connect
() method. We then use an oninput event handl...
...ther using the connect
() method. We then use an oninput event handler to change the value of the StereoPannerNode.pan parameter and update the pan value display when the slider is moved. Moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. ...
...Audio = document.querySelector('audio'); var panControl = document.querySelector('.panning-control'); var panValue = document.querySelector('.panning-value'); pre.innerHTML = myScript.innerHTML; // Create a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it var source = audioCtx.createMediaElementSource(myAudio); // Create a stereo panner var panNode = audioCtx.createStereoPanner
(); // Event handler function to increase panning to the right and left // when the slider is moved panControl.oninput = function
() { panNode.pan.setValueAtTime(panControl.value, audioCtx.currentTime); panValue.innerHTML = panControl.value; } // connect the MediaElementAudioSourceNode to the panNode // and the panNode to the destination, so we can play the // music and adjust the panning usin...
Storage API - Web APIs
ser agent disposes of site data in order to make room for other things. Note: This feature is available in Web Workers. Site storage--the data stored for a Web site which is managed by the Storage Standard--includes: IndexedDB databases Cache API data Service Worker registrations Web Storage API data managed using window.localStorage History state information saved using History.pushState
() Application caches Notification data Other kinds of site-accessible, site-specific data that may be maintained Site storage units The site storage system described by the Storage Standard and interacted with using the Storage API consists of a single site storage unit for each origin. In essence, every Web site or Web application has its own storage unit into which its data gets placed. The...
...". If it becomes necessary to consider clearing persistent boxes, the user agent will notify the user and provide a way to clear one or more persistent boxes as needed. To change an origin's box mode requires permission to use the "persistent-storage" feature. Data persistence and clearing If the site or app has the "persistent-storage" feature permission, it can use the StorageManager.persist
() method to request that its box be made persistent. It's also possible for the user agent to decide to make the site's storage unit persistent due to usage characteristics or other metrics. The "persistent-storage" feature's permission-related flags, algorithms, and types are all set to the standard defaults for a permission, except that the permission state must be the same across the entire orig...
...for the origin's use, and should be less than the available space on the device to help prevent overruns. User agents may use any method they choose to determine the size of origins' quotas, and are encouraged by the specification to provide popular or frequently-used sites with extra space. To determine the estimated quota and usage values for a given origin, use the navigator.storage.estimate
() method, which returns a promise that, when resolved, receives a StorageEstimate that contains these figures. For example: navigator.storage.estimate
().then(estimate => { // estimate.quota is the estimated quota // estimate.usage is the estimated number of bytes used }); Specifications Specification Status Comment Storage Living Standard Initial definition. ...
Text - Web APIs
. If an element has no markup within its content, it has a single child implementing Text that contains the element's text. However, if the element contains markup, it is parsed into information items and Text nodes that form its children. New documents have a single Text node for each block of text. Over time, more Text nodes may be created as the document's content changes. The Node.normalize
() method merges adjacent Text objects back into a single node for each block of text. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink...
... Properties Inherits properties from its parent, CharacterData. Text.isElementContentWhitespace Read only Returns a Boolean flag indicating whether or not the text node contains only whitespace. Text.wholeText Read only Returns a DOMString containing the text of all Text nodes logically adjacent to this Node, concate...
... Replaces the text of the current node and all logically adjacent nodes with the specified text. Text.splitText Breaks the node into two nodes at a specified offset. Specifications Specification Status Comment DOMThe definition of 'Text' in that specification. Living Standard Removed the isElementContentWhitespace property. Removed the replaceWholeText
() method. Added the Text
() constructor. Added the assignedSlot property. Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Text' in that specification. Obsolete Added the isElementContentWhitespace and wholeText properties. Added the replaceWholeText
() method. Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Text' in...
TextDecoder - Web APIs
ific text encoding, such as UTF-8, ISO-8859-2, KOI8-R, GBK, etc. A decoder takes a stream of bytes as input and emits a stream of code points. Examples Representing text with typed arrays This example shows how to decode a Chinese/Japanese character , as represented by five different typed arrays: Uint8Array, Int8Array, Uint16Array, Int16Array, and Int32Array. ...
...([-24336, -18514]); let i32arr = new Int32Array([-1213292304]); console.log(utf8decoder.decode(u8arr)); console.log(utf8decoder.decode(i8arr)); console.log(utf8decoder.decode(u16arr)); console.log(utf8decoder.decode(i16arr)); console.log(utf8decoder.decode(i32arr)); Handling non-UTF8 text In this example, we decode the Russian text "??????, ???!", which means "Hello, world." In our TextDecoder
() constructor, we specify the Windows-1251 character encoding, which is appropriate for Cyrillic script. let win1251decoder = new TextDecoder('windows-1251'); let bytes = new Uint8Array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]); console.log(win1251decoder.decode(bytes)); // ??????, ???! Constructor TextDecoder
() Returns a newly constructed TextDecoder that will generate a co...
...aining the name of the decoder, that is a string describing the method the TextDecoder will use. TextDecoder.prototype.fatalRead only Is a Boolean indicating whether the error mode is fatal. TextDecoder.prototype.ignoreBOMRead only Is a Boolean indicating whether the byte order marker is ignored. Methods The TextDecoder interface doesn't inherit any method. TextDecoder.prototype.decode
() Returns a DOMString containing the text decoded with the method of the specific TextDecoder object. Specifications Specification Status Comment EncodingThe definition of 'TextDecoder' in that specification. Living Standard Initial definition. ...
TouchEvent - Web APIs
Properties This interface inherits properties from its parent, UIEvent and Event. TouchEvent.altKey Read only A Boolean value indicating whether or not the alt key was down when the touch event was fired. TouchEvent.changedTouches Read only A TouchList of all the Touch objects representing individual points of contact whose states changed between the previ...
...e kind occurred that canceled the touch; this might happen if a modal alert pops up during the interaction. The touch point has left the document window and moved into the browser's UI area, a plug-in, or other external content. The user has placed more touch points on the screen than can be supported, in which case the earliest Touch in the TouchList gets canceled. Using with addEventListener
() and preventDefault
() It's important to note that in many cases, both touch and mouse events get sent (in order to let non-touch-specific code still interact with the user). If you use touch events, you should call preventDefault
() to keep the mouse event from being sent as well. The exception to this is Chrome, starting with version 56 (desktop, Chrome for android, and android webview), where t...
...in order to let non-touch-specific code still interact with the user). If you use touch events, you should call preventDefault
() to keep the mouse event from being sent as well. The exception to this is Chrome, starting with version 56 (desktop, Chrome for android, and android webview), where the default value for the passive option for touchstart and touchmove is true and calls to preventDefault
() will have no effect. To override this behavior, you need to set the passive option to false, after which calling preventDefault
() will work as specified. The change to treat listeners as passive by default prevents the listener from blocking page rendering while a user is scrolling. A demo is available on the Google Developer site. GlobalEventHandlers The GlobalEventHandlers mixin defines these...
USBInTransferResult - Web APIs
Properties USBInTransferResult.dataRead only Returns a DataView object containing the data received from the USB device, if any. USBInTransferResult.statusRead only Returns the status of the transfer request, one of: "ok" - The transfer was successful. ...
... Properties USBInTransferResult.dataRead only Returns a DataView object containing the data received from the USB device, if any. USBInTransferResult.statusRead only Returns the status of the transfer request, one of: "ok" - The transfer was successful. ...
...ta received from the USB device, if any. USBInTransferResult.statusRead only Returns the status of the transfer request, one of: "ok" - The transfer was successful. "stall" - The device indicated an error by generating a stall condition on the endpoint. A stall on the control endpoint does not need to be cleared. A stall on a bulk or interrupt endpoint must be cleared by calling clearHalt
() before transferIn
() can be called again. "babble" - The device responded with more data than was expected. Specifications Specification Status Comment WebUSBThe definition of 'USBInTransferResult' in that specification. Draft Initial definition. ...
USBOutTransferResult - Web APIs
Properties USBOutTransferResult.bytesWrittenRead only Returns the number of bytes from the transfer request that were sent to the device. ...
... Properties USBOutTransferResult.bytesWrittenRead only Returns the number of bytes from the transfer request that were sent to the device. ...
...ittenRead only Returns the number of bytes from the transfer request that were sent to the device. USBOutTransferResult.statusRead only Returns the status of the transfer request, one of: "ok" - The transfer was successful. "stall" - The device indicated an error by generating a stall condition on the endpoint. A stall on a bulk or interrupt endpoint must be cleared by calling clearHalt
() before transferOut
() can be called again. Specifications Specification Status Comment WebUSBThe definition of 'USBOutTransferResult' in that specification. Draft Initial definition. ...
User Timing API - Web APIs
er Timing methods that extend the Performance interface. For more details and example code regarding these two performance event types and the methods, see Using the User Timing API. Performance marks A performance mark is a named performance entry that is created by the application. The mark is a timestamp in the browser's performance timeline. Creating a performance mark The performance.mark
() method is used to create a performance mark. The method takes one argument, the name of the mark (for example performance.mark("mark-1")). The mark's performance entry will have the following property values: entryType - set to "mark". name - set to the "name" given when the mark was created. startTime - set to the timestamp when mark
() was called. duration - set to "0" (a mark has no dura...
...Finding only mark entries requires checking each entry's entryType for "mark". ...
...reName is the measure's name and startMarkName and endMarkName are the start and end names, respectively, of the marks the measure will be placed between (in the performance timeline). The measure's performance entry will have the following property values: entryType - set to "measure". name - set to the "name" given when the measure was created. startTime - set to the timestamp when measure
() was called. duration - set to a DOMHighResTimeStamp that is the duration of the measure (typically, the end mark timestamp minus the start mark timestamp). Retrieving performance measures The Performance interface has three methods that can be used to retrieve a measure: performance.getEntries
() Returns all performance entries in the performance timeline. Finding the measure entries requi...
VideoPlaybackQuality.creationTime - Web APIs
ince the browsing context was created this quality sample was recorded. Syntax value = videoPlaybackQuality.creationTime; Value A DOMHighResTimeStamp object which indicates the number of milliseconds that elapased between the time the browsing context was created and the time at which this sample of the video quality was obtained. For details on how the time is determined, see Performance.now
(). Example This example calls getVideoPlaybackQuality
() to obtain a VideoPlaybackQuality object, then determines what percentage of frames have been lost by either corruption or being dropped. If that exceeds 10% (0.1), a function called lostFramesThresholdExceeded
() is called to, perhaps, update a quality indicator to show an increase in frame loss. var videoElem = document.getElementById("my_v...
... Editor's Draft Initial definition. ...
...dropped. If that exceeds 10% (0.1), a function called lostFramesThresholdExceeded
() is called to, perhaps, update a quality indicator to show an increase in frame loss. var videoElem = document.getElementById("my_vid"); var quality = videoElem.getVideoPlaybackQuality
(); if ((quality.corruptedVideoFrames + quality.droppedVideoFrames)/quality.totalVideoFrames > 0.1) { lostFramesThresholdExceeded
(); } Specifications Specification Status Comment Media Playback QualityThe definition of 'VideoPlaybackQuality.corruptedVideoFrames' in that specification. Editor's Draft Initial definition. ...
VideoPlaybackQuality.totalVideoFrames - Web APIs
loaded. Syntax value = videoPlaybackQuality.totalVideoFrames; Value The total number of frames that the <video> element has displayed or dropped since the media was loaded into it. Essentially, this is the number of frames the element would have presented had no problems occurred. This value is reset when the media is reloaded or replaced. ...
...umber of frames the element would have presented had no problems occurred. This value is reset when the media is reloaded or replaced. Example This example calls getVideoPlaybackQuality
() to obtain a VideoPlaybackQuality object, then determines what percentage of frames have been lost by either corruption or being dropped. If that exceeds 10% (0.1), a function called lostFramesThresholdExceeded
() is called to, perhaps, update a quality indicator to show an increase in frame loss. ...
...y
() to obtain a VideoPlaybackQuality object, then determines what percentage of frames have been lost by either corruption or being dropped. If that exceeds 10% (0.1), a function called lostFramesThresholdExceeded
() is called to, perhaps, update a quality indicator to show an increase in frame loss. var videoElem = document.getElementById("my_vid"); var quality = videoElem.getVideoPlaybackQuality
(); if ((quality.corruptedVideoFrames + quality.droppedVideoFrames)/quality.totalVideoFrames > 0.1) { lostFramesThresholdExceeded
(); } A similar algorithm might be used to attempt to switch to a lower-resolution video that requires less bandwidth, in order to avoid dropping frames. Specifications Specification Status Comment Media Playback QualityThe definition of 'Vide...
VideoTrackList: change event - Web APIs
The change event is fired when a video track is made active or inactive, for example by changing the track's selected property. ...
...ange Examples Using addEventListener
(): const videoElement = document.querySelector('video'); videoElement.videoTracks.addEventListener('change', (event) => { console.log(`'${event.type}' event fired`); }); // changing the value of `selected` will trigger the `change` event const toggleTrackButton = document.querySelector('.toggle-track'); toggleTrackButton.addEventListener('click',
() => { const track = videoElement.videoTracks[0]; track.selected = !track.selected; }); Using the onchange event handler property: const videoElement = document.querySelector('video'); videoElement.videoTracks.onchange = (event) => { console.log(`'${event.type}' event fired`); }; // changing the value of `selected` will trigger the `change` event const toggleTrackButton = document.query...
... Living Standard ...
WEBGL_compressed_texture_astc - Web APIs
The WEBGL_compressed_texture_astc extension is part of the WebGL API and exposes Adaptive Scalable Texture Compression (ASTC) compressed texture formats to WebGL. For more information, see the article Using ASTC Texture Compression for Game Assets by nvidia. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: ASTC compression is typically available on Mali ARM GPUs, Intel GPUs, and Nividia Tegra chips. This extension is available to both, WebGL1 and WebGL2 contexts. Methods This extension exposes one new methods. ext.getSupportedProfiles
() Returns an array of strings containing the names of the ASTC profiles supported by the implementation. Constants The ...
...vidia Tegra chips. This extension is available to both, WebGL1 and WebGL2 contexts. Methods This extension exposes one new methods. ext.getSupportedProfiles
() Returns an array of strings containing the names of the ASTC profiles supported by the implementation. Constants The compressed texture formats are exposed by 28 constants and can be used in two functions: compressedTexImage2D
() and compressedTexSubImage2D
(). Constants Blocks Bits per pixel ArrayBuffer byteLength bytes if height and width are 512 ext.COMPRESSED_RGBA_ASTC_4x4_KHR ext.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 4x4 8.00 floor((width + 3) / 4) * floor((height + 3) / 4) * 16 262144 ext.COMPRESSED_RGBA_ASTC_5x4_KHR ext.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR ...
... Recommendation Initial definition. ...
WEBGL_compressed_texture_atc - Web APIs
art of the WebGL API and exposes 3 ATC compressed texture formats. ATC is a proprietary compression algorithm for compressing textures on handheld devices. Compressed textures reduce the amount of memory needed to store a texture on the GPU, allowing for higher resolution textures or more of the same resolution textures. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: ATC compression is typically available on mobile devices with Adreno GPUs, that are currently only built into Qualcomm Snapdragon devices. This extension is available to both, WebGL1 and WebGL2 contexts. Constants The compressed texture formats are exposed by 3 constants and can be used in two funct...
...ion, see also Using Extensions in the WebGL tutorial. Availability: ATC compression is typically available on mobile devices with Adreno GPUs, that are currently only built into Qualcomm Snapdragon devices. This extension is available to both, WebGL1 and WebGL2 contexts. Constants The compressed texture formats are exposed by 3 constants and can be used in two functions: compressedTexImage2D
() and compressedTexSubImage2D
(). ext.COMPRESSED_RGB_ATC_WEBGL Compresses RGB textures with no alpha channel. ext.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL Compresses RGBA textures using explicit alpha encoding (useful when alpha transitions are sharp). ext.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL Compresses RGBA textures using interpolated alpha encoding (useful when alpha transitions ar...
...t.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL Compresses RGBA textures using explicit alpha encoding (useful when alpha transitions are sharp). ext.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL Compresses RGBA textures using interpolated alpha encoding (useful when alpha transitions are gradient). Examples var ext = gl.getExtension('WEBGL_compressed_texture_atc'); var texture = gl.createTexture
(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.compressedTexImage2D(gl.TEXTURE_2D, 0, ext.COMPRESSED_RGB_ATC_WEBGL, 512, 512, 0, textureData); Specifications Specification Status Comment WEBGL_compressed_texture_atcThe definition of 'WEBGL_compressed_texture_atc' in that specification. Draft Initial definition. ...
WEBGL_compressed_texture_pvrtc - Web APIs
The WEBGL_compressed_texture_pvrtc extension is part of the WebGL API and exposes four PVRTC compressed texture formats. Compressed textures reduce the amount of memory needed to store a texture on the GPU, allowing for higher resolution textures or more of the same resolution textures. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: PVRTC is typically only available on mobile devices with PowerVR chipsets. It is used in all generations of the iPhone, iPod Touch and iPad and supported on certain Android devices that use a PowerVR GPU. This extension is available to both, WebGL1 and WebGL2 contexts. Note: On iOS devices, this extension is named WEBKIT_WEBGL_compres...
... in all generations of the iPhone, iPod Touch and iPad and supported on certain Android devices that use a PowerVR GPU. This extension is available to both, WebGL1 and WebGL2 contexts. Note: On iOS devices, this extension is named WEBKIT_WEBGL_compressed_texture_pvrtc. Constants The compressed texture formats are exposed by four constants and can be used in two functions: compressedTexImage2D
() (where the height and width parameters must be powers of 2) and compressedTexSubImage2D
() (where the the height and width parameters must equal the current values of the existing texture and the xoffset and yoffset parameters must be 0). ext.COMPRESSED_RGB_PVRTC_4BPPV1_IMG RGB compression in 4-bit mode. One block for each 4x4 pixels. ext.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG RGBA compression in ...
...PRESSED_RGBA_PVRTC_4BPPV1_IMG RGBA compression in 4-bit mode. One block for each 4x4 pixels. ext.COMPRESSED_RGB_PVRTC_2BPPV1_IMG RGB compression in 2-bit mode. One block for each 8x4 pixels. ext.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG RGBA compression in 2-bit mode. One block for each 8x4 pixels. Examples var ext = gl.getExtension('WEBGL_compressed_texture_pvrtc'); var texture = gl.createTexture
(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.compressedTexImage2D(gl.TEXTURE_2D, 0, ext.COMPRESSED_RGB_PVRTC_4BPPV1_IMG, 512, 512, 0, textureData); Specifications Specification Status Comment WEBGL_compressed_texture_pvrtcThe definition of 'WEBGL_compressed_texture_pvrtc' in that specification. Draft Initial definition. ...
Basic scissoring - Web APIs
<< PreviousNext >> In this example, we see how to draw simple rectangles and squares using WebGL scissoring operations. Scissoring establishes a clipping region outside which drawing will not occur. Clearing the drawing buffer when scissoring applies This is a simple demonstration of a rendering with scissor
(). Although the clear
() drawing command writes the clear color (set by clearColor
()) to all pixels in the drawing buffer, scissor
() defines a mask that only allows pixels inside the specified rectangular area to be updated. This is a good opportunity to talk about the difference between pixels and fragments. A pixel is a picture element (in practice, a point) on the screen, or a single element of the drawing buffer, that area in memory that holds your pixel data (such ...
...n the screen. If they fail the test, they are immediately discarded, no further processing occurs, and pixels are not updated. Because only fragments within the specified rectangular area successfully pass the scissor test, only pixels inside that area are updated, and we get a rectangle on the screen. The scissoring stage of the pipeline is disabled by default. We enable it here using the enable
() method (you will also use enable
() to activate many other features of WebGL; hence, the use of the SCISSOR_TEST constant as an argument in this case). This again demonstrates the typical order of commands in WebGL. We first tweak WebGL state. In this case, enabling the scissor test and establishing a rectangular mask. Only when the WebGL state has been satisfactorily tweaked, we execute the drawi...
...le
() to activate many other features of WebGL; hence, the use of the SCISSOR_TEST constant as an argument in this case). This again demonstrates the typical order of commands in WebGL. We first tweak WebGL state. In this case, enabling the scissor test and establishing a rectangular mask. Only when the WebGL state has been satisfactorily tweaked, we execute the drawing command (in this case, clear
()) that starts the processing of fragments down the graphics pipeline. <p>Result of of scissoring.</p> <canvas>Your browser 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; } window.addEventListener("load", function set...
Clearing by clicking - Web APIs
e same click event handler to both canvas and // button. var canvas = document.querySelector("#canvas-view"); var button = document.querySelector("#color-switcher"); canvas.addEventListener("click", switchColor, false); button.addEventListener("click", switchColor, false); // A variable to hold the WebGLRenderingContext. var gl; // The click event handler. function switchColor
() { // Referring to the externally defined gl variable. // If undefined, try to obtain the WebGLRenderingContext. // If failed, alert user of failure. // Otherwise, initialize the drawing buffer (the viewport). if (!gl) { gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { alert("Failed to get WebGL context.\n" ...
...nvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { alert("Failed to get WebGL context.\n" + "Your browser or device may not support WebGL."); return; } gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); } // Get a random color value using a helper function. ...
...t a random color value using a helper function. var color = getRandomColor
(); // Set the clear color to the random color. gl.clearColor(color[0], color[1], color[2], 1.0); // Clear the context with the newly set color. This is // the function call that actually does the drawing. gl.clear(gl.COLOR_BUFFER_BIT); } // Random color helper function. function getRandomColor
() { return [Math.random
(), Math.random
(), Math.random
()]; } }, false); The source code of this example is also available on GitHub. << PreviousNext >> ...
Compressed texture formats - Web APIs
ats such as PNG and JPG. As compressed textures require hardware support, therefore no specific formats are required by WebGL; instead, a context can make different formats available, depending on hardware support. This site shows which formats are supported in the used browser. Usage of compressed formats first requires activating the respective extension with WebGLRenderingContext.getExtension
(). If supported, it will return an extension object with constants for the added formats and the formats will also be returned by calls to gl.getParameter(gl.COMPRESSED_TEXTURE_FORMATS). (E.g. ext.COMPRESSED_RGBA_S3TC_DXT1_EXT for the WEBGL_compressed_texture_s3tc extension.) These can then be used with compressedTexImage[23]D or compressedTexSubImage[23]D instead of texImage2D calls. Note that We...
... No WEBGL_compressed_texture_pvrtc Width and height must be powers of 2. No No WEBGL_compressed_texture_s3tc Width and height must be multiples of 4. Yes No WEBGL_compressed_texture_s3tc_srgb Width and height must be multiples of 4. ...
...texture = gl.createTexture
(); gl.bindTexture(gl.TEXTURE_2D, texture); // create texture object on GPU const ext = gl.getExtension('WEBGL_compressed_texture_s3tc'); // will be null if not supported if (ext) { // the file is already in the correct compressed format const dataArrayBuffer = await fetch('/textures/foobar512x512.RGBA_S3TC_DXT1') .then(response => response.arrayBuffer
()); gl.compressedTexImage2D(gl.TEXTURE_2D, 0, // set the base image level ext.COMPRESSED_RGBA_S3TC_DXT1_EXT, // the compressed format we are using 512, 512, // width, height of the image 0, // border, always 0 new DataView(dataArrayBuffer)); gl.generateMipMap
(); // create mipmap levels, like we would for a standard image return texture; } } ...
Matrix math for the web - Web APIs
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. ...
...ranslationMatrix = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 ]; Place the distances along the three axes in the corresponding positions in the translation matrix, then multiply it by the point or matrix you need to move through 3D space. Manipulating the DOM with a matrix A really easy way to start using a matrix is to use the CSS matrix3d
() transform. First we'll set up a simple <div> with some content. The style is not shown, but it's set to a fixed width and height and is centered on the page. The <div> has a transition set for the transform so that matrix is animated in making it easy to see what is being done. <div id='move-me' class='transformable'> <h2>Move me with a matrix</h2> <p>Lorem ipsum dolor sit amet, consectetur ...
... the reverse order that the operations intuitively happen. For instance, to scale something down by 80%, move it down 200 pixels, and then rotate about the origin 90 degrees would look something like the following in pseudo-code. transformation = rotate * translate * scale Composing multiple transformations The function that we will be using to compose our matrices is multiplyArrayOfMatrices
(), which is part of the set of utility functions introduced near the top of this article. It takes an array of matrices and multiplies them together, returning the result. In WebGL shader code, this is built into the language and the * operator can be used. Additionally this example uses scale
() and translate
() functions, which return matrices as defined above. let transformMatrix = MDN.multiplyAr...
Getting started with WebGL - Web APIs
e WebGL's capabilities, making it easier to build 3D applications and games, such as THREE.js and BABYLON.js. Preparing to render in 3D The first thing you need in order to use WebGL for rendering is a canvas. The HTML fragment below declares a canvas that our sample will draw into. ...
...WebGL for rendering is a canvas. The HTML fragment below declares a canvas that our sample will draw into. <body> <canvas id="glCanvas" width="640" height="480"></canvas> </body> Preparing the WebGL context The main
() function in our JavaScript code, is called when our script is loaded. Its purpose is to set up the WebGL context and start rendering content. // // start here // function main
() { const canvas = document.querySelector("#glCanvas"); // Initialize the GL context const gl = canvas.getContext("webgl"); // Only continue if WebGL is available and working if (gl === null) { alert("Unable to initialize WebGL. Your browser or machine may not support it."); return; } // Set clear color to black, fully opaque gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear t...
... } // Set clear color to black, fully opaque gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear the color buffer with specified clear color gl.clear(gl.COLOR_BUFFER_BIT); } window.onload = main; The first thing we do here is obtain a reference to the canvas, assigning it to a variable named canvas. Once we have the canvas, we try to get a WebGLRenderingContext for it by calling getContext
() and passing it the string "webgl". If the browser does not support WebGL, getContext
() will return null in which case we display a message to the user and exit. If the context is successfully initialized, the variable gl is our reference to it. In this case, we set the clear color to black, and clear the context to that color (redrawing the canvas with the background color). At this point, you...
Lighting in WebGL - Web APIs
face. We'll see how to do that when we look at the code for the shader. Building the normals for the vertices The first thing we need to do is generate the array of normals for all the vertices that comprise our cube. Since a cube is a very simple object, this is easy to do; obviously for more complex objects, calculating the normals will be more involved. ...
...w Float32Array(vertexNormals), gl.STATIC_DRAW); ... return { position: positionBuffer, normal: normalBuffer, textureCoord: textureCoordBuffer, indices: indexBuffer, }; This should look pretty familiar by now; we create a new buffer, bind it to be the buffer we're working with, then send along our array of vertex normals into the buffer by calling bufferData
(). Then we add the code to drawScene
() to bind the normals array to a shader attribute so the shader code can get access to it: // Tell WebGL how to pull out the normals from // the normal buffer into the vertexNormal attribute. { const numComponents = 3; const type = gl.FLOAT; const normalize = false; const stride = 0; const offset = 0; gl.bindBuffer(gl.ARRAY_BUFFER...
... gl.uniformMatrix4fv( programInfo.uniformLocations.normalMatrix, false, normalMatrix); Update the shaders Now that all the data the shaders need is available to them, we need to update the code in the shaders themselves. The vertex shader The first thing to do is update the v...
Using WebGL extensions - Web APIs
ns. WEBGL_: Extensions that are WebGL-specific and intended to be compatible with multiple web browsers. It should also be used for extensions which originated with the OpenGL ES or OpenGL APIs, but whose behavior has been significantly altered. Querying available extensions The WebGL context supports querying what extensions are available. var available_extensions = gl.getSupportedExtensions
(); The WebGLRenderingContext.getSupportedExtensions
() method returns an array of strings, one for each supported extension. Extension list The current extensions are: ANGLE_instanced_arrays EXT_blend_minmax EXT_color_buffer_float EXT_color_buffer_half_float EXT_disjoint_timer_query EXT_float_blend EXT_frag_depth EXT_sRGB EXT_shader_texture_lod EXT_texture_compression_bptc EXT_tex...
... ...
...ension
(). For example: var float_texture_ext = gl.getExtension('OES_texture_float'); The return value is null if the extension is not supported, or an extension object otherwise. Extension objects If an extension defines specific symbols or functions that are not available in the core specification of WebGL, they will be available on the extension object returned by the call to gl.getExtension
(). ...
WebRTC Statistics API - Web APIs
The WebRTC API has a vast array of statistics available, covering the entire breadth of the WebRTC connectivity system, from sender to receiver and peer to peer. Collecting statistics You can collect statistics at various levels throughout the WebRTC hierarchy of objects. Most broadly, you can call getStats
() on an RTCPeerConnection to get statistics for the connection overall. In this example, a new RTCPeerConnection is created, and then setInterval
() is used to set the function getConnectionStats
() to be called every second. That function, in turn, uses getStats
() to obtain statistics for the connection and to make use of that data. try { myPeerConnection = new RTCPeerConnection(pcOptions); statsInterval = window.setInterval(getConnectionStats, 1000); /* add event handlers, e...
...be called every second. That function, in turn, uses getStats
() to obtain statistics for the connection and to make use of that data. ...
...This object contains a Map of named dictionaries based on RTCStats and its affiliated types. This example specifically looks for the report whose type is inbound-rtp and whose kind is video. This way, we look only at the video-related statistics for the local RTCRtpReceiver resp...
WebXR Device API - Web APIs
returns the window's instance of XRSystem, which is the mechanism by which your code accesses the WebXR API. Using the XRSystem interface, you can create XRSessions to represent actual AR and/or VR sessions. XRFrame While presenting an XR session, the state of all tracked objects which make up the session are represented by an XRFrame. To get an XRFrame, call the session's requestAnimationFrame
() method, providing a callback which will be called with the XRFrame once available. Events which communicate tracking states will also use XRFrame to contain that information. XRRenderState Provides a set of configurable properties which change how the imagery output by an XRSession is composited. XRSession Provides the interface for interacting with XR hardware. Once an XRSession is obtained ...
...ich will be called with the XRFrame once available. Events which communicate tracking states will also use XRFrame to contain that information. XRRenderState Provides a set of configurable properties which change how the imagery output by an XRSession is composited. XRSession Provides the interface for interacting with XR hardware. Once an XRSession is obtained from navigator.xr.requestSession
(), the session can be used to check the position and orientation of the viewer, query the device for environment information, and present the virtual or augmented world to the user. XRSpace XRSpace is an opaque base class on which all virtual coordinate system interfaces are based. Positions in WebXR are always expressed in relation to a particular XRSpace at the time at which a particular XFrame...
...nt when the state of an XRReferenceSpace changes. XRSessionEvent Sent to indicate that the state of an XRSession has changed. For example, if the position and/or orient Extensions to the WebGL API The WebGL API is extended by the WebXR specification to augment the WebGL context to allow it to be used to render views for display by a WebXR device. WebGLRenderingContextBase.makeXRCompatibile
() Configures the WebGL context to be compatible with WebXR. If the context was not initially created with the xrCompatible property set to true, you must call makeXRCompatible
() prior to attempting to use the WebGL context for WebXR rendering. Returns a Promise which resolves once the context has been prepared, or is rejected if the context cannot be configured for use by WebXR. Guides and tutor...
Web audio spatialization basics - Web APIs
e where they are in space and in which direction they are facing. They remain static. The pannerNode can then calculate its sound position relative to the position of the listener. Let's create our context and listener and set the listener's position to emulate a person looking into our room: const AudioContext = window.AudioContext || window.webkitAudioContext; const audioCtx = new AudioContext
(); const listener = audioCtx.listener; const posX = window.innerWidth/2; const posY = window.innerHeight/2; const posZ = 300; listener.positionX.value = posX; listener.positionY.value = posY; listener.positionZ.value = posZ-5; We could move the listener left or right using positionX, up or down using positionY, or in or out of the room using positionZ. Here we are setting the listener to be in ...
...er.orientationX.value = x; panner.orientationY.value = y; panner.orientationZ.value = z; break; } boombox.style.transform = 'translateX('+transform.xAxis+'px) translateY('+transform.yAxis+'px) scale('+transform.zAxis+') rotateY('+transform.rotateY+'deg) rotateX('+transform.rotateX+'deg)'; const move = prevMove || {}; move.frameId = requestAnimationFrame(
() => moveBoombox(direction, move)); return move; } Wiring up our controls Wiring up out control buttons is comparatively simple -- now we can listen for a mouse event on our controls and run this function, as well as stop it when the mouse is released: // for each of our controls, move the boombox and change the position values moveControls.forEach(function(el) { let moving; el.add...
... return move; } Wiring up our controls Wiring up out control buttons is comparatively simple -- now we can listen for a mouse event on our controls and run this function, as well as stop it when the mouse is released: // for each of our controls, move the boombox and change the position values moveControls.forEach(function(el) { let moving; el.addEventListener('mousedown', function
() { let direction = this.dataset.control; if (moving && moving.frameId) { window.cancelAnimationFrame(moving.frameId); } moving = moveBoombox(direction); }, false); window.addEventListener('mouseup', function
() { if (moving && moving.frameId) { window.cancelAnimationFrame(moving.frameId); } }, false) }) Summar...
Window: beforeunload event - Web APIs
Interface Event Event handler property onbeforeunload This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page. If the user confirms, the browser navigates to the new page, otherwise it cancels the navigation. According to the specification, to show the confirmation dialog an event handler should call preventDefault
() on the event. However note that not all browsers support this method, and some instead require the event handler to implement one of two legacy methods: assigning a string to the event's returnValue property returning a string from the event handler. Some browsers used to display the returned string in the confirmation dialog, enabling the event handler to display a custom message to the u...
...may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all. Attaching an event handler/listener to window or document's beforeunload event prevents browsers from using in-memory page navigation caches, like Firefox's Back-Forward cache or WebKit's Page Cache. The HTML specification states that calls to window.alert
(), window.confirm
(), and window.prompt
() methods may be ignored during this event. See the HTML specification for more details. Examples The HTML specification states that authors should use the Event.preventDefault
() method instead of using Event.returnValue. However, this is not supported by all browsers. window.addEventListener('beforeunload', (event) => { // Cancel the event as stated by t...
... event.returnValue = ''; }); Specifications Specification Status Comment HTML Living StandardThe definition of 'beforeunload' in that specification. Living Standard HTML5The definition of 'beforeunload' in that specification. ...
Window.closed - Web APIs
urrent window has an opener using the window.opener property and that the opener isn't closed: // Check that an opener exists and is not closed if (window.opener && !window.opener.closed) { window.opener.location.href = 'http://www.mozilla.org'; } Note that popups can only access the window that opened them. ...
...n opener using the window.opener property and that the opener isn't closed: // Check that an opener exists and is not closed if (window.opener && !window.opener.closed) { window.opener.location.href = 'http://www.mozilla.org'; } Note that popups can only access the window that opened them. ...
... 'http://www.mozilla.org'; } Note that popups can only access the window that opened them. Refreshing a previously opened popup In this example the function refreshPopupWindow
() calls the reload
() method of the popup's location object to refresh its data. If the popup hasn't been opened yet or the user has closed it a new window is opened. const popupWindow = null; function refreshPopupWindow
() { if (popupWindow && !popupWindow.closed) { // popupWindow is open, refresh it popupWindow.location.reload(true); } else { // Open a new popup window popupWindow = window.open('popup.html', 'dataWindow'); } } Specification Specification Status Comment HTML Living StandardThe definition of 'window.closed' in that specification. Living Standard ...
Window.crypto - Web APIs
ct allows web pages access to certain cryptographic related services. Although the property itself is read-only, all of its methods (and the methods of its child object, SubtleCrypto) are not read-only, and therefore vulnerable to attack by polyfill. Although window.crypto is available on all windows, the returned Crypto object only has one usable feature in insecure contexts: the getRandomValues
() method. In general, you should use this API only in secure contexts. Syntax var cryptoObj = window.crypto || window.msCrypto; // for IE 11 Value An instance of the Crypto interface, providing access to general-purpose cryptography and a strong random-number generator. Example This example uses the Window.crypto property to access the getRandomValues
() method. JavaScript genRandomNumbers ...
...ould use this API only in secure contexts. Syntax var cryptoObj = window.crypto || window.msCrypto; // for IE 11 Value An instance of the Crypto interface, providing access to general-purpose cryptography and a strong random-number generator. Example This example uses the Window.crypto property to access the getRandomValues
() method. ...
...ion getRandomNumbers
() { var array = new Uint32Array(10); window.crypto.getRandomValues(array); var randText = document.getElementById("myRandText"); randText.innerHTML = "The random numbers are: " for (var i = 0; i < array.length; i++) { randText.innerHTML += array[i] + " "; } } HTML <p id="myRandText">The random numbers are: </p> <button type="button" onClick='genRandomNumbers
()'>Generate 10 random numbers</button> Result Specifications Specification Status Comment Web Cryptography APIThe definition of 'Window.crypto' in that specification. Recommendation Initial definition ...
Window.innerHeight - Web APIs
innerHeight is taken from the height of the window's layout viewport. The width can be obtained using the innerWidth property. Syntax let intViewportHeight = window.innerHeight; Value An integer value indicating the window's layout viewport height in pixels. The property is read only and has no default value. To change the width of the window, call one of its resize methods, such as resizeTo
() or resizeBy
(). Usage notes To obtain the height of the window minus its horizontal scroll bar and any borders, use the root <html> element's clientHeight
() property instead. Both innerHeight and innerWidth are available on any window or any object that behaves like a window, such as a tab or frame. Example Assuming a frameset var intFrameHeight = window.innerHeight; // or var intFrameHeigh...
... To get the outer height of a window, i.e. the height of the whole browser window, see window.outerHeight. Graphical example The following figure shows the difference between outerHeight and innerHeight. Specification Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'window.innerHeight' in that specificatio...
...turn the height of the frame viewport within the frameset var intFramesetHeight = parent.innerHeight; // will return the height of the viewport of the closest frameset var intOuterFramesetHeight = top.innerHeight; // will return the height of the viewport of the outermost frameset FIXME: link to an interactive demo here To change the size of a window, see window.resizeBy
() and window.resizeTo
(). To get the outer height of a window, i.e. the height of the whole browser window, see window.outerHeight. Graphical example The following figure shows the difference between outerHeight and innerHeight. Specification Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'window.innerHeight' in that specification. Working Draft ...
Window: resize event - Web APIs
The resize event fires when the document view (window) has been resized. Bubbles No Cancelable No Interface UIEvent Event handler property onresize In some earlier browsers it was possible to register resize event handlers on any HTML element. It is still possible to set onresize attributes or use addEventListener
() to set a handler on any element. However, resize events are only fired on the window object (i.e. returned by document.defaultView). Only handlers registered on the window object will receive resize events. There is a proposal to allow all elements to be notified of resize changes. See Resize Observer to read the draft document, and GitHub issues to read the on-going discussions. Examples Window size logger The followin...
...ng in an <iframe>, you'll need to actually get the <iframe> to resize before you see an effect. ...
... Obsolete CSS Object Model (CSSOM) View ModuleThe definition of 'resize' in that specification. Working Draft ...
Window.screenLeft - Web APIs
troduced everywhere due to popularity. Syntax leftWindowPos = window.screenLeft Returns A number equal to the number of CSS pixels from the left edge of the browser viewport to the left edge of the screen. Examples In our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. ...
...example, you'll see a canvas onto which has been drawn a circle. In this example we are using screenLeft/screenTop plus Window.requestAnimationFrame
() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...nitialTop = window.screenTop + canvasElem.offsetTop; function positionElem
() { let newLeft = window.screenLeft + canvasElem.offsetLeft; let newTop = window.screenTop + canvasElem.offsetTop; let leftUpdate = initialLeft - newLeft; let topUpdate = initialTop - newTop; ctx.fillStyle = 'rgb(0, 0, 0)'; ctx.fillRect(0, 0, width, height); ctx.fillStyle = 'rgb(0, 0, 255)'; ctx.beginPath
(); ctx.arc(leftUpdate + (width/2), topUpdate + (height/2) + 35, 50, degToRad(0), degToRad(360), false); ctx.fill
(); pElem.textContent = 'Window.screenLeft: ' + window.screenLeft + ', Window.screenTop: ' + window.screenTop; window.requestAnimationFrame(positionElem); } window.requestAnimationFrame(positionElem); Also in the code we include a snippet that detects whether screenLeft is sup...
Window.screenTop - Web APIs
s introduced everywhere due to popularity. Syntax topWindowPos = window.screenTop Returns A number equal to the number of CSS pixels from the top edge of the browser viewport to the top edge of the screen. Examples In our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. ...
...example, you'll see a canvas onto which has been drawn a circle. In this example we are using screenLeft/screenTop plus Window.requestAnimationFrame
() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...nitialTop = window.screenTop + canvasElem.offsetTop; function positionElem
() { let newLeft = window.screenLeft + canvasElem.offsetLeft; let newTop = window.screenTop + canvasElem.offsetTop; let leftUpdate = initialLeft - newLeft; let topUpdate = initialTop - newTop; ctx.fillStyle = 'rgb(0, 0, 0)'; ctx.fillRect(0, 0, width, height); ctx.fillStyle = 'rgb(0, 0, 255)'; ctx.beginPath
(); ctx.arc(leftUpdate + (width/2), topUpdate + (height/2) + 35, 50, degToRad(0), degToRad(360), false); ctx.fill
(); pElem.textContent = 'Window.screenLeft: ' + window.screenLeft + ', Window.screenTop: ' + window.screenTop; window.requestAnimationFrame(positionElem); } window.requestAnimationFrame(positionElem); Also in the code we include a snippet that detects whether screenLeft is sup...
WindowClient - Web APIs
The WindowClient interface of the ServiceWorker API represents the scope of a service worker client that is a document in a browsing context, controlled by an active worker. 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. WindowClient.visibilityState Read only Indicates the visibility of the current client. This value can be...
....focused Read only A boolean that indicates whether the current client has focus. WindowClient.visibilityState Read only Indicates the visibility of the current client. This value can be one of "hidden", "visible", or "prerender". ...
... Working Draft Initial definition ...
WindowEventHandlers.onbeforeunload - Web APIs
ent is still cancelable. Note: To combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with. Moreover, some don't display them at all. Syntax window.addEventListener("beforeunload", function(event) { ... }); window.onbeforeunload = function(event) { ... ...
...n't display them at all. Syntax window.addEventListener("beforeunload", function(event) { ... }); window.onbeforeunload = function(event) { ... }; Typically, it is better to use window.addEventListener
() and the beforeunload event, instead of onbeforeunload. Example This example prompts the user before unloading. The HTML specification states that authors should use the Event.preventDefault
() method instead of using Event.returnValue to prompt the user. ...
... it is better to use window.addEventListener
() and the beforeunload event, instead of onbeforeunload. Example This example prompts the user before unloading. The HTML specification states that authors should use the Event.preventDefault
() method instead of using Event.returnValue to prompt the user. ...
WindowEventHandlers.onpopstate - Web APIs
The onpopstate property of the WindowEventHandlers mixin is the EventHandler for processing popstate events on the window. A popstate event is dispatched to the window each time the active history entry changes between two history entries for the same document. If the activated history entry was created by a call to history.pushState
(), or was affected by a call to history.replaceState
(), the popstate event's state property contains a copy of the history entry's state object. Note: Calling history.pushState
() or history.replaceState
() won't trigger a popstate event. The popstate event is only triggered by performing a browser action, such as clicking on the back button (or calling history.back
() in JavaScript), when navigating between two history entries for the same document. Syntax ...
...e at http://example.com/example.html running the following code will generate alerts as indicated: window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + JSON.stringify(event.state)); }; history.pushState({page: 1}, "title 1", "?page=1"); history.pushState({page: 2}, "title 2", "?page=2"); history.replaceState({page: 3}, "title 3", "?page=3"); history.back
(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back
(); // alerts "location: http://example.com/example.html, state: null history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3} Note that even though the original history entry (for http://example.com/example.html) has no state object associated with it, a popstate e...
... Specifications Specification Status Comment HTML Living StandardThe definition of 'onpopstate' in that specification. ...
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
()). ...
...d 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
()). ...
..."); 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: ${event.data}`) }; The worker posts messages using self.postMessage
(): // static/scripts/worker.js self.postMessage('I\'m alive!'); Specifications Specification Status HTML Living Standard Living Standard ...
XMLHttpRequest: abort event - Web APIs
The abort event is fired when a request has been aborted, for example because the program called XMLHttpRequest.abort
(). Bubbles No Cancelable No Interface ProgressEvent Event handler property onabort Examples Live example HTML <div class="controls"> <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" /> <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" /> <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" /> </div> <textarea readonly class="event-log"></textarea> CSS .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; ...
...Listeners(xhr) { xhr.addEventListener('loadstart', handleEvent); xhr.addEventListener('load', handleEvent); xhr.addEventListener('loadend', handleEvent); xhr.addEventListener('progress', handleEvent); xhr.addEventListener('error', handleEvent); xhr.addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest
(); addListeners(xhr); xhr.open("GET", url); xhr.send
(); return xhr; } xhrButtonSuccess.addEventListener('click',
() => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.addEventListener('click',
() => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.addEventListener('click',
() => { runXHR('https://mdn.mozil...
... xhr.send
(); return xhr; } xhrButtonSuccess.addEventListener('click',
() => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.addEventListener('click',
() => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.addEventListener('click',
() => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort
(); }); Result Specifications Specification Status Comment XMLHttpRequest Living Standard ...
XMLHttpRequest.onreadystatechange - Web APIs
alled when the readystatechange event is fired, that is every time the readyState property of the XMLHttpRequest changes. Warning: This should not be used with synchronous requests and must not be used from native code. Syntax XMLHttpRequest.onreadystatechange = callback; Values callback is the function to be executed when the readyState changes. ...
... This should not be used with synchronous requests and must not be used from native code. Syntax XMLHttpRequest.onreadystatechange = callback; Values callback is the function to be executed when the readyState changes. ...
...e = function
() { // In local files, status is 0 upon success in Mozilla Firefox if(xhr.readyState === XMLHttpRequest.DONE) { var status = xhr.status; if (status === 0 || (status >= 200 && status < 400)) { // The request has been completed successfully console.log(xhr.responseText); } else { // Oh no! There has been an error with the request! ...
XMLHttpRequest.responseText - Web APIs
The read-only XMLHttpRequest property responseText returns the text received from a server following a request being sent. Syntax var resultText = XMLHttpRequest.responseText; Value A DOMString which contains either the textual data received using the XMLHttpRequest or null if the request failed or "" if the request has not yet been sent by calling send
(). While handling an asynchronous request, the value of responseText always has the current content received from the server, even if it's incomplete because the data has not been completely received yet. You know the entire content has been received when the value of readyState becomes XMLHttpRequest.DONE (4), and status becomes 200 ("OK"). Exceptions InvalidStateError The XMLHttpRequest.responseType is not set to eit...
...t. You know the entire content has been received when the value of readyState becomes XMLHttpRequest.DONE (4), and status becomes 200 ("OK"). Exceptions InvalidStateError The XMLHttpRequest.responseType is not set to either the empty string or "text". Since the responseText property is only valid for text content, any other value is an error condition. ...
...ions InvalidStateError The XMLHttpRequest.responseType is not set to either the empty string or "text". Since the responseText property is only valid for text content, any other value is an error condition. ...
XMLHttpRequest.statusText - Web APIs
PRequest.status which indicates a numerical status code, this property contains the text of the response status, such as "OK" or "Not Found". If the request's readyState is in UNSENT or OPENED state, the value of statusText will be an empty string. If the server response doesn't explicitly specify a status text, statusText will assume the default value "OK". ...
... request's readyState is in UNSENT or OPENED state, the value of statusText will be an empty string. If the server response doesn't explicitly specify a status text, statusText will assume the default value "OK". ...
... will be an empty string. If the server response doesn't explicitly specify a status text, statusText will assume the default value "OK". ...
XMLHttpRequestEventTarget.onerror - Web APIs
The XMLHttpRequestEventTarget.onerror is the function called when an XMLHttpRequest transaction fails due to an error. Syntax XMLHttpRequest.onerror = callback; Values callback is the function to be executed when the request fails. ...
...LHttpRequestEventTarget.onerror is the function called when an XMLHttpRequest transaction fails due to an error. Syntax XMLHttpRequest.onerror = callback; Values callback is the function to be executed when the request fails. ...
...saction fails due to an error. Syntax XMLHttpRequest.onerror = callback; Values callback is the function to be executed when the request fails. ...
XMLHttpRequestEventTarget.onload - Web APIs
tion called when an XMLHttpRequest transaction completes successfully. Syntax XMLHttpRequest.onload = callback; Values callback is the function to be executed when the request completes successfully. It receives a ProgressEvent object as its first argument. The value of this (i.e. the context) is the same XMLHttpRequest this callback is related to. ...
... callback is the function to be executed when the request completes successfully. It receives a ProgressEvent object as its first argument. The value of this (i.e. the context) is the same XMLHttpRequest this callback is related to. ...
...s a ProgressEvent object as its first argument. The value of this (i.e. the context) is the same XMLHttpRequest this callback is related to. ...
XMLHttpRequestEventTarget.onloadstart - Web APIs
The XMLHttpRequestEventTarget.onloadstart is the function called when an XMLHttpRequest transaction starts transferring data. Syntax XMLHttpRequest.onloadstart = callback; Values callback is the function to be called when the transaction begins to transfer data. ...
... is the function called when an XMLHttpRequest transaction starts transferring data. Syntax XMLHttpRequest.onloadstart = callback; Values callback is the function to be called when the transaction begins to transfer data. ...
...on starts transferring data. Syntax XMLHttpRequest.onloadstart = callback; Values callback is the function to be called when the transaction begins to transfer data. ...
XMLHttpRequestEventTarget.onprogress - Web APIs
pletely. Syntax XMLHttpRequest.onprogress = callback; Values callback is the function to be called periodically before the request is completed. Event event.loaded the amount of data currently transfered. event.total the total amount of data to be transferred. ...
... request is completed. Event event.loaded the amount of data currently transfered. event.total the total amount of data to be transferred. ...
...nt.loaded the amount of data currently transfered. event.total the total amount of data to be transferred. ...
XPathExpression - Web APIs
This interface is a compiled XPath expression that can be evaluated on a document or specific node to return information from its DOM tree. This is useful when an expression will be reused in an application, because it is just compiled once and all namespace prefixes which occur within the expression are preresolved. Objects of this type are created by calling XPathEvaluator.createExpression
(). ...
...expression that can be evaluated on a document or specific node to return information from its DOM tree. This is useful when an expression will be reused in an application, because it is just compiled once and all namespace prefixes which occur within the expression are preresolved. Objects of this type are created by calling XPathEvaluator.createExpression
(). ...
...type are created by calling XPathEvaluator.createExpression
(). Methods XPathExpression.evaluate
() Evaluates the XPath expression on the given node or document. Example The following example shows the use of the XPathExpression interface. ...
XRInputSourceEventInit.frame - Web APIs
The XRInputSourceEventInit dictionary's property frame specifies an XRFrame providing information about the timestamp at which the new input source event took place, as well as access to the XRFrame method getPose
() which can be used to map the coordinates of any XRReferenceSpace to the space in which the event took place. Of course, as a general rule, you won't need to create XRInputSourceEventInit objects yourself. These events are generated by and sent to you by the WebXR infrastructure. ...
... need to create XRInputSourceEventInit objects yourself. These events are generated by and sent to you by the WebXR infrastructure. ...
... Examples This example creates a new select event and sends it to the XRSession. ...
XRPose - Web APIs
epresenting a position and orientation in the 3D space, relative to the XRSpace within which it resides. The XRSpace--which is either an XRReferenceSpace or an XRBoundedReferenceSpace--defines the coordinate system used for the pose and, in the case of an XRViewerPose, its underlying views. ...
...rPose, its underlying views. To obtain the XRPose for the XRSpace used as the local coordinate system of an object, call XRFrame.getPose
(), specifying that local XRSpace and the space to which you wish to convert: thePose = xrFrame.getPose(localSpace, baseSpace); The pose for a viewer (or camera) is represented by the XRViewerPose subclass of XRPose. ...
...views. To obtain the XRPose for the XRSpace used as the local coordinate system of an object, call XRFrame.getPose
(), specifying that local XRSpace and the space to which you wish to convert: thePose = xrFrame.getPose(localSpace, baseSpace); The pose for a viewer (or camera) is represented by the XRViewerPose subclass of XRPose. ...
XRRigidTransform - Web APIs
The transform of an XRView. The transform of an XRPose. ...
...e reset event received by an XRReferenceSpace. The advantage to using XRRigidTransform in these places rather than bare arrays that providing the matrix data is that the XRRigidTransform automatically does things like computing the inverse of the transform. Even better, once it's been computed, it's cached so that subsequent requests are significantly faster. Constructor new XRRigidTransform
() Creates a new XRRigidTransform object which represents a transform that applies a specified position and/or orientation. Attributes XRRigidTransform.position Read only A DOMPointReadOnly specifying a 3-dimensional point, expressed in meters, describing the translation component of the transform. The w attribute is always 1.0. XRRigidTransform.orientation Read only A DOMPointReadOnl...
...RRigidTransform is interpreted, the orientation is always applied to the affected object before the position is applied. Example This code snippet creates an XRRigidTransform to specify the offset and orientation in relation to the current reference space to use when creating a new reference space. It then requests the first animation frame callback by calling the session's requestAnimationFrame
() method. xrSession.requestReferenceSpace(refSpaceType) .then((refSpace) => { xrReferenceSpace = refSpace; xrReferenceSpace = xrReferenceSpace.getOffsetReferenceSpace( new XRRigidTransform(viewerStartPosition, cubeOrientation)); animationFrameRequestID = xrSession.requestAnimationFrame(drawFrame); Specifications Specification Status Comment WebXR Device ...
XRSession.visibilityState - Web APIs
ue A DOMString containing one of the values defined in the enumerated type XRVisibilityState; this string indicates whether or not the XR content is visible to the user and if it is, whether or not it's currently the primary focus. ...
...ated by the XRSession is not currently visible to the user, so its requestAnimationFrame
() callbacks are not being executed until thevisibilityState changes. Input controllers are not being handled for the session. visible The virtual scene rendered by the XRSession is currently visible to the user and is the primary focus of the user's attention. To that end, the session's requestAnimationFrame
() callbacks are being processed at the XR device's native refresh rate and input controllers are being processed as normal. visible-blurred While the virtual scene rendered by the XRSession may currently be visible to the user, it is not the user's primary focus at the moment; it's also possible the session is not currently visible at all. In order to optimize resource utilization, the user agent...
...tive refresh rate and input controllers are being processed as normal. visible-blurred While the virtual scene rendered by the XRSession may currently be visible to the user, it is not the user's primary focus at the moment; it's also possible the session is not currently visible at all. In order to optimize resource utilization, the user agent may be handling the session's requestAnimationFrame
() callbacks at a throttled rate. Input controllers are not being processed for the session. Usage notes It's important to keep in mind that because an immersive WebXR session is potentially being shown using a different display than the HTML document in which it's running (such as when being shown on a headset), the value of a session's visibilityState may not necessarily be the same as the owni...
XRVisibilityState - Web APIs
sibilityState enumerated type defines the string values which are valid for the XRSession interface's visibilityState property, which indicates whether or not an XR session is currently visible to the user, and if it is, whether or not it's currently the primary focus. ...
...ated by the XRSession is not currently visible to the user, so its requestAnimationFrame
() callbacks are not being executed until thevisibilityState changes. Input controllers are not being handled for the session. visible The virtual scene rendered by the XRSession is currently visible to the user and is the primary focus of the user's attention. To that end, the session's requestAnimationFrame
() callbacks are being processed at the XR device's native refresh rate and input controllers are being processed as normal. visible-blurred While the virtual scene rendered by the XRSession may currently be visible to the user, it is not the user's primary focus at the moment; it's also possible the session is not currently visible at all. In order to optimize resource utilization, the user agent...
...tive refresh rate and input controllers are being processed as normal. visible-blurred While the virtual scene rendered by the XRSession may currently be visible to the user, it is not the user's primary focus at the moment; it's also possible the session is not currently visible at all. In order to optimize resource utilization, the user agent may be handling the session's requestAnimationFrame
() callbacks at a throttled rate. Input controllers are not being processed for the session. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRVisibilityState' in that specification. Working Draft Initial definition. ...
XRWebGLLayer.framebuffer - Web APIs
ehavior is different in several ways from a standard WebGL context. These differences cause the opaque framebuffer to behave more like the default WebGL framebuffer: Opaque framebuffers may support anti-aliasing, even under WebGL 1.0, which don't normally do so. Opaque framebuffers' attachments (buffers and the like) can't be inspected or changed. Calling functions such as framebufferTexture2D
(), framebufferRenderbuffer
(), deleteFramebuffer
(), or getFramebufferAttachmentParameter
() on an opaque framebuffer results in the WebGL error INVALID_OPERATION (0x0502). Opaque framebuffers are considered incomplete and are not available for rendering other than while executing the requestAnimationFrame
() callback. Attempting to clear, draw to, or read from the framebuffer results in a WebGL INVAL...
... Opaque framebuffers initialized with the depth property set to false will not have a depth buffer and will rely on the coordinates alone to determine distance. ...
...ized just like the default framebuffer for any WebGL interface: The color buffer is configured with its clear value set to the color (0, 0, 0, 0) (meaning transparent black). The depth buffer's clear value is the number 1.0. The stencil buffer is filled with 0. Examples This example gets the XRWebGLLayer for a session and then passes its framebuffer into the WebGL context's bindFramebuffer
() function. let glLayer = xrSession.renderState.baselayer; gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer); Specifications Specification Status Comment WebXR Device APIThe definition of 'XRWebGLLayer.framebuffer' in that specification. Working Draft Initial definition. ...
Alerts - Accessibility
' function, we'll use a simple WAI-ARIA widget for notification. This notifies the user of the error, but allows for them continue modifying the form without losing focus (caused by the "onblur" handler in JavaScript's default 'alert' function). ...
...caused by the "onblur" handler in JavaScript's default 'alert' function). ...
...This method takes three parameters: The ID of the input that is to be validated, the term to search for to ensure validity, and the error message to be inserted into the alert. To see if it is valid, the function checks whether the indexOf the input's value i...
:defined - CSS: Cascading Style Sheets
The :defined CSS pseudo-class represents any element that has been defined. This includes any standard element built in to the browser, and custom elements that have been successfully defined (i.e. with the CustomElementRegistry.define
() method). ...
...lects any instance of a specific custom element */ simple-custom:defined { display: block; } Syntax :defined Examples Hiding elements until they are defined The following snippets are taken from our defined-pseudo-class demo (see it live also). ...
...ce of a specific custom element */ simple-custom:defined { display: block; } Syntax :defined Examples Hiding elements until they are defined The following snippets are taken from our defined-pseudo-class demo (see it live also). ...
:scope - CSS: Cascading Style Sheets
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 (paragra...
...the layout.css.scope-pseudo.enabled preference (needs to be set to true). ...
...eudo.enabled preference (needs to be set to true). ...
src - CSS: Cascading Style Sheets
The format hint contains a comma-separated list of format strings that denote well-known font formats. If a user agent doesn't support the specified formats, it skips downloading the font resource. If no format hints are supplied, the font resource is always downloaded. <font-face-name> Specifies the name of a locally-...
... the font resource referenced by that URL. The format hint contains a comma-separated list of format strings that denote well-known font formats. If a user agent doesn't support the specified formats, it skips downloading the font resource. If no format hints are supplied, the font resource is always downloaded. <font-face-name> Specifies the name of a locally-installed font face using the local
() function, which uniquely identifies a single font face within a larger family. The name can optionally be enclosed in quotes. Description The value of this descriptor is a prioritized, comma-separated list of external references or locally-installed font face names. When a font is needed the user agent iterates over the set of references listed using the first one it can successfully activate.
...le 1-based indexing scheme (e.g., "font-collection#1" for the first font, "font-collection#2" for the second font, etc.) is used. Formal definition Related at-rule@font-faceInitial valuen/a (required)Computed valueas specified Formal syntax [ <url> [ format( <string># ) ]? | local( <family-name> ) ]#where <family-name> = <string> | <custom-ident>+ Examples Specifying font resources using url
() and local
() @font-face { font-family: examplefont; src: local(Example Font), url('examplefont.woff') format("woff"), url('examplefont.otf') format("opentype"); } Specifications Specification Status Comment CSS Fonts Module Level 3The definition of 'src' in that specification. Candidate Recommendation Initial definition ...
@font-face - CSS: Cascading Style Sheets
ur letter axis names of the features to vary, along with their variation values. src Specifies the resource containing the font data. This can be a URL to a remote font file location or the name of a font on the user's computer. ...
...n select a suitable one -- it is possible to include a format type inside a format
() function: src: url(ideal-sans-serif.woff) format("woff"), url(basic-sans-serif.ttf) format("truetype"); The available types are: "woff", "woff2", "truetype", "opentype", "embedded-opentype", and "svg". unicode-range The range of Unicode code points to be used from the font. Description If the local
() function is provided, specifying a font name to look for on the user's computer, and the user agent finds a match, that local font is used. Otherwise, the font resource specified using the url
() function is downloaded and used. By allowing authors to provide their own fonts, @font-face makes it possible to design content without being limited to the so-called "web-safe" fonts (that is, the fonts...
...ontent without being limited to the so-called "web-safe" fonts (that is, the fonts which are so common that they're considered to be universally available). The ability to specify the name of a locally-installed font to look for and use makes it possible to customize the font beyond the basics while making it possible to do so without relying on an Internet connection. It's common to use both url
() and local
() together, so that the user's installed copy of the font is used if available, falling back to downloading a copy of the font if it's not found on the user's device. The @font-face at-rule may be used not only at the top level of a CSS, but also inside any CSS conditional-group at-rule. Font MIME Types Format MIME type TrueType font/ttf OpenType ...
Testing media queries programmatically - CSS: Cascading Style Sheets
st.matches) { /* The viewport is currently in portrait orientation */ } else { /* The viewport is not currently in portrait orientation, therefore landscape */ } Receiving query notifications If you need to be aware of changes to the evaluated result of the query on an ongoing basis, it's more efficient to register a listener than to poll the query's result. To do this, call the addListener
() method on the MediaQueryList object, with a callback function to invoke when the media query status changes (e.g., the media query test goes from true to false): // Create the query list. const mediaQueryList = window.matchMedia("(orientation: portrait)"); // Define a callback function for the event listener. function handleOrientationChange(mql) { // ... } // Run the orientation change hand...
...nChange); This code creates the orientation-testing media query list, then adds an event listener to it. After adding the listener, we also call the listener directly. This makes our listener perform adjustments based on the current device orientation; otherwise, our code might assume the device is in portrait mode at startup, even if it's actually in landscape mode. The handleOrientationChange
() function would look at the result of the query and handle whatever we need to do on an orientation change: function handleOrientationChange(evt) { if (evt.matches) { /* The viewport is currently in portrait orientation */ } else { /* The viewport is currently in landscape orientation */ } } Above, we define the parameter as evt -- an event object. This makes sense because newer i...
...passing an event object of type MediaQueryListEvent as the argument to the callback function. ...
<alpha-value> - CSS: Cascading Style Sheets
orresponds to fully transparent while 100% indicates fully opaque. Interpolation When animated, values of the <alpha-value> CSS data type are interpolated as real, floating-point numbers. The speed of the interpolation is determined by the timing function associated with the animation. ...
... ...
... ...
animation - CSS: Cascading Style Sheets
adding: .5em; } @keyframes slidein { from { transform: scaleX(0); } to { transform: scaleX(1); } } .a1 { animation: 3s ease-in 1s 2 reverse both paused slidein; } .a2 { animation: 3s linear 1s slidein; } .a3 { animation: 3s slidein; } .animation { background: #3F87A6; width: 100%; height: calc(100% - 1.5em); transform-origin: left center; } window.addEventListener('load', function
() { var ANIMATION = Array.from(document.querySelectorAll('.animation')); var BUTTON = Array.from(document.querySelectorAll('button')); function toggleButton (btn, type) { btn.classList.remove('play', 'pause', 'restart'); btn.classList.add(type); btn.title = type.toUpperCase(type); } function playPause (i) { var btn = BUTTON[i]; var anim = ANIMATION[i]; if (b...
...i) { var btn = BUTTON[i]; var anim = ANIMATION[i]; if (btn.classList.contains('play')) { anim.style.animationPlayState = 'running'; toggleButton(btn, 'pause'); } else if (btn.classList.contains('pause')) { anim.style.animationPlayState = 'paused'; toggleButton(btn, 'play'); } else { anim.classList.remove('a' + (i + 1)); setTimeout(function
() { toggleButton(btn, i === 0 ? 'play' : 'pause'); anim.style.animationPlayState = ''; anim.classList.add('a' + (i + 1)); }, 100) } } ANIMATION.forEach(function (node, index) { node.addEventListener('animationstart', function
() { toggleButton(BUTTON[index], 'pause'); }); node.addEventListener('animationend', function
() { toggleButton(BUTTON[index...
...anim.classList.add('a' + (i + 1)); }, 100) } } ANIMATION.forEach(function (node, index) { node.addEventListener('animationstart', function
() { toggleButton(BUTTON[index], 'pause'); }); node.addEventListener('animationend', function
() { toggleButton(BUTTON[index], 'restart'); }); }); BUTTON.forEach(function (btn, index) { btn.addEventListener('click', function
() { playPause(index); }); }); }) A description of which properties are animatable is available; it's worth noting that this description is also valid for CSS transitions. Constituent properties This property is a shorthand for the following CSS properties: animation-delay animation-direction animation-duration animation-fill-mode animation-iteration-count animation-name animation-p...
gap (grid-gap) - CSS: Cascading Style Sheets
d not gap for grid, you will need to use the prefixed property as in the interactive example above. Syntax /* One <length> value */ gap: 20px; gap: 1em; gap: 3vmin; gap: 0.5cm; /* One <percentage> value */ gap: 16%; gap: 100%; /* Two <length> values */ gap: 20px 10px; gap: 1em 0.5em; gap: 3vmin 2vmax; gap: 0.5cm 2mm; /* One or two <percentage> values */ gap: 16% 100%; gap: 21px 82%; /* calc
() values */ gap: calc(10% + 20px); gap: calc(20px + 10%) calc(10% - 5px); /* Global values */ gap: inherit; gap: initial; gap: unset; This property is specified as a value for <'row-gap'> followed optionally by a value for <'column-gap'>. If <'column-gap'> is omitted, it's set to the same value as <'row-gap'>. <'row-gap'> and <'column-gap'> are each specified as a <length> or a <percentage>. V...
... Examples Flex layout HTML <div id="flexbox"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div> CSS #flexbox { display: flex; flex-wrap: wrap; width: 300px; gap: 20px 5px; } #flexbox > div { border: 1px solid green; background-color: lime; flex: 1 1...
... Examples Flex layout HTML <div id="flexbox"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div> CSS #flexbox { display: flex; flex-wrap: wrap; width: 300px; gap: 20px 5px; } #flexbox > div { border: 1px solid green; background-color: lime; flex: 1 1 auto; width: 100px; height: 50px; } ...
grid-auto-columns - CSS: Cascading Style Sheets
g additional columns. ...
... values */ grid-auto-columns: 100px; grid-auto-columns: 20cm; grid-auto-columns: 50vmax; /* <percentage> values */ grid-auto-columns: 10%; grid-auto-columns: 33.3%; /* <flex> values */ grid-auto-columns: 0.5fr; grid-auto-columns: 3fr; /* minmax
() values */ grid-auto-columns: minmax(100px, auto); grid-auto-columns: minmax(max-content, 2fr); grid-auto-columns: minmax(20%, 80vmax); /* fit-content
() values */ grid-auto-columns: fit-content(400px); grid-auto-columns: fit-content(5cm); grid-auto-columns: fit-content(20%); /* multiple track-size values */ grid-auto-columns: min-content max-content auto; grid-auto-columns: 100px 150px 390px; grid-auto-columns: 10% 33.3%; grid-auto-columns: 0.5fr 3fr 1fr; grid-auto-columns: minmax(100px, auto) minmax(max-content, 2fr) minmax(20%, 80vmax); grid-a...
... a non-negative <percentage> value relative to the block size of the grid container. If the block size of the grid container is indefinite, the percentage value is treated like auto. <flex> Is a non-negative dimension with the unit fr specifying the track's flex factor. Each <flex>-sized track takes a share of the remaining space in proportion to its flex factor. When appearing outside a minmax
() notation, it implies an automatic minimum (i.e. minmax(auto, <flex>)). max-content Is a keyword representing the largest maximal content contribution of the grid items occupying the grid track. min-content Is a keyword representing the largest minimal content contribution of the grid items occupying the grid track. minmax(min, max) Is a functional notation that defines a size range greate...
<length-percentage> - CSS: Cascading Style Sheets
Therefore, all of the following values are acceptable for width: width: 200px; width: 20%; width: calc(100% - 200px); Specifications Specification Status Comment CSS Values and Units Module Level 4The ...
...rder-radius: 10px 10%; font-size: 250%; line-height: 1.5em; /* length examples */ text-shadow: 1px 1px 1px red; border: 5px solid red; letter-spacing: 3px; /* percentage example */ text-size-adjust: 20%; } Result Use in calc
() Where a <length-percentage> is specified as an allowable type, this means that the percentage resolves to a length and therefore can be used in a calc
() expression. Therefore, all of the following values are acceptable for width: width: 200px; width: 20%; width: calc(100% - 200px); Specifications Specification Status Comment CSS Values and Units Module Level 4The definition of '<length-percentage>' in that specification. Editor's Draft CSS Values and Units Module Level 3The definition of '<length-pe...
...; width: calc(100% - 200px); Specifications Specification Status Comment CSS Values and Units Module Level 4The definition of '<length-percentage>' in that specification. Editor's Draft CSS Values and Units Module Level 3The definition of '<length-percentage>' in that specification. Candidate Recommendation Defines <length-percentage>. Adds calc
() ...
offset - CSS: Cascading Style Sheets
[ / <'offset-anchor'> ]? Examples Animating an element along a path HTML <div id="offsetElement"></div> CSS @keyframes move { fro...
...[ / <'offset-anchor'> ]? Examples Animating an element along a path HTML <div id="offsetElement"></div> CSS @keyframes move { from { offset-distance: 0%; } to { off...
...[ / <'offset-anchor'> ]? Examples Animating an element along a path HTML <div id="offsetElement"></div> CSS @keyframes move { from { offset-distance: 0%; } to { offset-distance: 100%; } } #offsetElement { width: 50px; height: 50px; ...
transition-timing-function - CSS: Cascading Style Sheets
nherit; transition-timing-function: initial; transition-timing-function: unset; Values <timing-function> Each <timing-function> represents the timing function to link to the corresponding property to transition, as defined in transition-property. The non-step keyword values (ease, linear, ease-in-out, etc.) each represent cubic Bezier curve with fixed four point values, with the cubic-bezier
() function value allowing for a non-predefined value. The step timing functions divides the input time into a specified number of intervals that are equal in length. It is defined by a number of steps and a step position. ease Equal to cubic-bezier(0.25, 0.1, 0.25, 1.0), the default value, increases in velocity towards the middle of the transition, slowing back down at the end. linear Eq...
...n-width: 12em; margin-bottom: 4px; background-color: black; border: 1px solid red; color: white; transition-property: all; transition-duration: 7s; } .parent > div.box1{ width: 90vw; min-width: 24em; background-color: magenta; color: yellow; border: 1px solid orange; transition-property: all; transition-duration: 2s; } function updateTransition
() { var els = document.querySelectorAll(".parent > div[class]"); for(var c = els.length, i = 0; i < c; i++) { els[i].classList.toggle("box1"); } } var intervalID = window.setInterval(updateTransition, 10000); .ease { transition-timing-function: ease; } .easein { transition-timing-function: ease-in; } .easeout { transition-timing-function: ease-out; } .easeinout { transiti...
...min-width: 12em; margin-bottom: 4px; background-color: black; border: 1px solid red; color: white; transition-property: all; transition-duration:7s; } .parent > div.box1{ width: 90vw; min-width: 24em; background-color: magenta; color: yellow; border: 1px solid orange; transition-property: all; transition-duration:2s; } function updateTransition
() { var els = document.querySelectorAll(".parent > div[class]"); for(var c = els.length, i = 0; i < c; i++) { els[i].classList.toggle("box1"); } } var intervalID = window.setInterval(updateTransition, 10000); .jump-start { transition-timing-function: steps(5, jump-start); } .jump-end { transition-timing-function: steps(5, jump-end); } .jump-none { transition-timing-function:...
<url> - CSS: Cascading Style Sheets
denotes a pointer to a resource, such as an image or a font. URLs can be used in numerous CSS properties, such as background-image, cursor, and list-style. URI or URL? There is a difference between a URI and a URL. A URI simply identifies a resource. A URL is a type of URI, and describes the location of a resource. A URI can be either a URL or a name (URN) of a resource. In CSS Level 1, the url
() functional notation described only true URLs. In CSS Level 2, the definition of url
() was extended to describe any URI, whether a URL or a URN. Confusingly, this meant that url
() could be used to create a <uri> CSS data type. This change was not only awkward but, debatably, unnecessary, since URNs are almost never used in actual CSS. To alleviate the confusion, CSS Level 3 returned to the narrowe...
...It may be written without quotes, or surrounded by single or double quotes. Relative URLs are allowed, and are relative to the URL of the stylesheet (not to the URL of the web page). ...
...It may be written without quotes, or surrounded by single or double quotes. Relative URLs are allowed, and are relative to the URL of the stylesheet (not to the URL of the web page). ...
Used value - CSS: Cascading Style Sheets
n the computed value. After the user agent has finished its calculations, every CSS property has a used value. The used values of dimensions (e.g., width, line-height) are in pixels. The used values of shorthand properties (e.g., background) are consistent with those of their component properties (e.g., background-color or background-size) and with position and float. Note: The getComputedStyle
() DOM API returns the resolved value, which may either be the computed value or the used value, depending on the property. Example This example computes and displays the used width value of three elements (updates on resize): HTML <div id="no-width"> <p>No explicit width.</p> <p class="show-used-width">..</p> <div id="width-50"> <p>Explicit width: 50%.</p> <p class="show-used-wi...
...Then, CSS 2.1 introduced the distinct definition of used value. An element could then expli...
...Then, CSS 2.1 introduced the distinct definition of used value. An element could then explicitly inherit a width/height of a parent, whose computed value is a percentage. For CSS properties that don't depend on layou...
Writing Web Audio API code that works in every browser - Developer guides
little library will "normalise" the interfaces for you and make it look as if your code is running in a standards compliant browser, by aliasing prefixed names to the unprefixed versions. And it won't do anything if the unprefixed versions are already present. Once you include it in your page, you can write in "modern Web Audio API" style, and do things such as: var audioContext = new AudioContext
(); everywhere, including Chrome/ium, Opera, Safari, and ---of course!--- Firefox. Also, if new methods such as start are not detected in some nodes, the library will also alias them to their old names. Thus, start is mapped to noteOn, stop to noteOff, and so on. If you're porting moderately "old" code (say, a year old) it's possible that it uses some methods that AudioContext-MonkeyPatch doesn't a...
...will also alias them to their old names. Thus, start is mapped to noteOn, stop to noteOff, and so on. If you're porting moderately "old" code (say, a year old) it's possible that it uses some methods that AudioContext-MonkeyPatch doesn't alias, because it helps you to write code in the new style. For example, the way to create instances of GainNode used to be var gain = audioContext.createGainNode
(); but nowadays it is just var gain = audioContext.createGain
(); Since the old method names are not present in Firefox, existing code may crash with something like createGainNode is not a function, and you now know why. There's a section in the spec that lists the old names and their updated equivalences; be sure to check it out and change your code accordingly. You can also check this article on...
... did not support the default HRTF panning model yet, and attempting to use a PannerNode with that configuration simply resulted in silence or a mono output coming out from that node, depending on the build you used. Today the support is already present in Nightly, but not quite yet in Aurora. In the meantime, you can explicitly specify 'equalpower' instead: var panner = new audioContext.PannerNode
(); panner.panningModel = 'equalpower'; Note that there's a list of projects built with the Web Audio API, specifying which ones use the standard AudioContext and which browsers do they work on. If you're a person that learns by example, it might be interesting to have a look at their source and see how they have resolved the compatibility issues. ...
User input and controls - Developer guides
t, but a pointer.js polyfill is available on Mozilla Github. Implement controls Pointer lock In some cases, typically game development, you might need to access mouse events even when the cursor goes past the boundary of the browser or screen: the Pointer_Lock_API gives you full control of the pointing device. This is the code to request pointer lock on an element: element.requestPointerLock
(); Note: For a full tutorial and reference, read our Pointer_Lock_API page. Screen Orientation When screen orientation matters for your application, you can read the screen orientation state, be informed when this state changes, and able to lock the screen orientation to a specific state (usually portrait or landscape) through the Screen Orientation API. Orientation data can be retrieved thro...
...ntation method, while the screen.unlockOrientation method removes all the previous screen locks that have been set. Note: More information about the Screen Orientation API can be found in Managing screen orientation. Fullscreen You might need to present an element of your application (such as a <video>, for example) in fullscreen mode. ...
...element of your application (such as a <video>, for example) in fullscreen mode. You can achieve this by calling Element.requestFullscreen
() on that element. Bear in mind that many browsers still implement this with a vendor prefix, so you will probably need to fork your code something like this: var elem = document.getElementById("myvideo"); if (elem.requestFullscreen) { elem.requestFullscreen
(); } else if (elem.msRequestFullscreen) { elem.msRequestFullscreen
(); } else if (elem.mozRequestFullScreen) { elem.mozRequestFullScreen
(); } else if (elem.webkitRequestFullscreen) { elem.webkitRequestFullscreen
(); } Note: To find more out about adding fullscreen functionality your application, read our documentation about using fullscreen mode. Drag & Drop Drag & Drop allows your applica...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
rce if that data has expired from the media buffer. Other audio may have a media timeline that doesn't start at 0 seconds, so setting currentTime to a time before that would fail. For example, if the audio's media timeline starts at 12 hours, setting currentTime to 3600 would be an attempt to set the current playback position well before the beginning of the media, and would fail. The getStartDate
() method can be used to determine the beginning point of the media timeline's reference frame. disableRemotePlayback A Boolean attribute used to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc). See this proposed specification for more information. In Safari, you can use x...
...gh The browser estimates it can play the media up to its end without stopping for content buffering. complete The rendering of an OfflineAudioContext is terminated. durationchange The duration attribute has been updated. emptied The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load
() method is called to reload it. ended Playback has stopped because the end of the media was reached. loadeddata The first frame of the media has finished loading. loadedmetadata The metadata has been loaded. pause Playback has been paused. play Playback has begun. playing Playback is ready to start after having been paused or...
...unction(event) { trackEditor.addTrack(event.track); }; elem.audioTrackList.onremovetrack = function(event) { trackEditor.removeTrack(event.track); }; This code watches for audio tracks to be added to and removed from the element, and calls a hypothetical function on a track editor to register and remove the track from the editor's list of available tracks. You can also use addEventListener
() to listen for the addtrack and removetrack events. Examples Basic usage The following example shows simple usage of the <audio> element to play an OGG file. It will autoplay due to the autoplay attribute--if the page has permission to do so--and also includes fallback content. <!-- Simple audio playback --> <audio src="AudioTest.ogg" autoplay> Your browser does not support the <code>aud...
<input type="password"> - HTML: Hypertext Markup Language
insecure login forms; see Insecure passwords. Value A DOMString representing a password, or empty Events change and input Supported Common Attributes autocomplete, inputmode, maxlength, minlength, pattern, placeholder, readonly, required, and size IDL attributes selectionStart, selectionEnd, selectionDirection, and value Methods select
(), setRangeText
(), and setSelectionRange
() Value The value attribute contains a DOMString whose value is the current contents of the text editing control being used to enter the password. If the user hasn't entered anything yet, this value is an empty string (""). If the required property is specified, then the password edit box must contain a value other than an empty string to be valid. ...
...evious one by specifying that the user's PIN must be at least four and no more than eight digits. The size attribute is used to ensure that the password entry control is eight characters wide. ...
...ic" minlength="4" maxlength="8" size="8"> Selecting text As with other textual entry controls, you can use the select
() method to select all the text in the password field. HTML <label for="userPassword">Password: </label> <input id="userPassword" type="password" size="12"> <button id="selectAll">Select All</button> JavaScript document.getElementById("selectAll").onclick = function
() { document.getElementById("userPassword").select
(); } Result You can also use selectionStart and selectionEnd to get (or set) what range of characters in the control are currently selected, and selectionDirection to know which direction selection occurred in (or will be extended in, depending on your platform; see its documentation for an explanation). However, given that the text is obscur...
<video>: The Video Embed element - HTML: Hypertext Markup Language
the given time and seeks the media to that position if the media is currently loaded. If the media is being streamed, it's possible that the user agent may not be able to obtain some parts of the resource if that data has expired from the media buffer. Other media may have a media timeline that doesn't start at 0 seconds, so setting currentTime to a time before that would fail. The getStartDate
() method can be used to determine the beginning point of the media timeline's reference frame. disablePictureInPicture Prevents the browser from suggesting a Picture-in-Picture context menu or to request Picture-in-Picture automatically in some cases. disableRemotePlayback A Boolean attribute used to disable the capability of remote playback in devices that are attached using wired (HDMI,...
...gh The browser estimates it can play the media up to its end without stopping for content buffering. complete The rendering of an OfflineAudioContext is terminated. durationchange The duration attribute has been updated. emptied The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load
() method is called to reload it. ended Playback has stopped because the end of the media was reached. loadeddata The first frame of the media has finished loading. loadedmetadata The metadata has been loaded. pause Playback has been paused. play Playback has begun. playing Playback is ready to start after having been paused or...
...unction(event) { trackEditor.addTrack(event.track); }; elem.audioTrackList.onremovetrack = function(event) { trackEditor.removeTrack(event.track); }; This code watches for audio tracks to be added to and removed from the element, and calls a hypothetical function on a track editor to register and remove the track from the editor's list of available tracks. You can also use addEventListener
() to listen for the addtrack and removetrack events. Examples Simple video example This example plays a video when activated, providing the user with the browser's default video controls to control playback. <!-- Simple video example --> <!-- 'Big Buck Bunny' licensed under CC 3.0 by the Blender foundation. Hosted by archive.org --> <!-- Poster from peach.blender.org --> <video controls src...
CSP: connect-src - HTTP
Note: connect-src 'self' does not resolve to websocket schemas in all browsers, more info: https://github.com/w3c/webappsec-csp/issues/7 CSP version 1 Directive type Fetch directive default-src fallback Yes. ...
...be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval
() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> e...
.... See unsafe inline script for an example. In CSP 2.0, this applied only to inline scripts. CSP 3.0 allows it in the case of script-src for external scripts. Examples Violation cases Given this CSP header: Content-Security-Policy: connect-src https://example.com/ The following connections are blocked and won't load: <a ping="https://not-example.com"> <script> var xhr = new XMLHttpRequest
(); xhr.open('GET', 'https://not-example.com/'); xhr.send
(); var ws = new WebSocket("https://not-example.com/"); var es = new EventSource("https://not-example.com/"); navigator.sendBeacon("https://not-example.com/", { ... }); </script> Specifications Specification Status Comment Content Security Policy Level 3The definition of 'connect-src' in that specific...
Date - HTTP
The Date general HTTP header contains the date and time at which the message was originated. Note that Date is listed in the forbidden header names in the fetch spec - so this code will not send Date header: fetch('https://httpbin.org/get', { 'headers': { 'Date': (new Date
()).toUTCString
() } }) Header type General header Forbidden header name yes Syntax Date: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT Directives <day-name> One of "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", or "Sun" (case-sensitive). <day> 2 digit day number, e.g. "04" or "23". <month> One of "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" (case sensitive). <year> 4 digit year number, e.g. "1990" or "2016". <...
..., "Oct", "Nov", "Dec" (case sensitive). <year> 4 digit year number, e.g. "1990" or "2016". <hour> 2 digit hour number, e.g. "09" or "23". <minute> 2 digit minute number, e.g. "04" or "59". ...
..., "Dec" (case sensitive). <year> 4 digit year number, e.g. "1990" or "2016". <hour> 2 digit hour number, e.g. "09" or "23". <minute> 2 digit minute number, e.g. "04" or "59". <second> 2 digit second number, e.g. ...
JavaScript data types and data structures - JavaScript
s, the number type has three symbolic values: +Infinity, -Infinity, and NaN ("Not a Number"). To check for the largest available value or smallest available value within +-Infinity, you can use the constants Number.MAX_VALUE or Number.MIN_VALUE. Starting with ECMAScript 2015, you are also able to check if a number is in the double-precision floating-point number range using Number.isSafeInteger
() as well as Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER. Beyond this range, integers in JavaScript are not safe anymore and will be a double-precision floating point approximation of the value. The number type has only one integer with two representations: 0 is represented as both -0 and +0. (0 is an alias for +0.) In the praxis, this has almost no impact. For example, +0 === -0 is tr...
...of a String is the number of elements in it. Unlike some programming languages (such as C), JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string. For example: A substring of the original by picking individual letters or using String.substr
(). A concatenation of two strings using the concatenation operator (+) or String.concat
(). Beware of "stringly-typing" your code! It can be tempting to use strings to represent complex data. Doing this comes with short-term benefits: It is easy to build complex strings with concatenation. Strings are easy to debug (what you see printed is always what is in the string). Strings are the comm...
...er a String or a Symbol value. There are two types of object properties which have certain attributes: The data property and the accessor property. Note: Each property has corresponding attributes. Attributes are used internally by the JavaScript engine, so you cannot directly access them. That's why attributes are listed in double square brackets, rather than single. See Object.defineProperty
() to learn more. Data property Associates a key with a value, and has the following attributes: Attributes of a data property Attribute Type Description Default value [[Value]] Any JavaScript type The value retrieved by a get access of the property. undefined [[Writable]] Boolean If false, the property's [[Value]] cannot be changed. fal...
Enumerability and ownership of properties - JavaScript
le without extra code Obtaining properties by enumerability/ownership Note that this is not the most efficient algorithm for all cases, but useful for a quick demonstration. ...
...out extra code Obtaining properties by enumerability/ownership Note that this is not the most efficient algorithm for all cases, but useful for a quick demonstration. ...
... } if (!iteratePrototypeBool) { break; } iterateSelfBool = true; } while (obj = Object.getPrototypeOf(obj)); return props; } }; Detection Table in for..in obj.hasOwnProperty obj.propertyIsEnumerable Object.keys Object.getOwnPropertyNames Object.getOwnPropertyDescriptors Reflect.ownKeys
() Enumerable true true true true true true true true Nonenumerable true false true false false true true true Symbols keys true false true true false false true true Inherited Enumerable true true false false false false false false Inherited Nonenumerable...
extends - JavaScript
ll. Examples Using extends The first example creates a class called Square from a class called Polygon. This example is extracted from this live demo (source). ...
...is live demo (source). class Square extends Polygon { constructor(length) { // Here, it calls the parent class' constructor with lengths // provided for the Polygon's width and height super(length, length); // Note: In derived classes, super
() must be called before you // can use 'this'. Leaving this out will cause a reference error. this.name = 'Square'; } get area
() { return this.height * this.width; } } Using extends with built-in objects This example extends the built-in Date object. ...
... derived classes, super
() must be called before you // can use 'this'. Leaving this out will cause a reference error. this.name = 'Square'; } get area
() { return this.height * this.width; } } Using extends with built-in objects This example extends the built-in Date object. This example is extracted from this live demo (source). class myDate extends Date { getFormattedDate
() { var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; return this.getDate
() + '-' + months[this.getMonth
()] + '-' + this.getFullYear
(); } } Specifications Specification ECMAScript (ECMA-262)The definition of 'extends' in that specification. ...
TypeError: invalid Array.prototype.sort argument - JavaScript
The JavaScript exception "invalid Array.prototype.sort argument" occurs when the argument of Array.prototype.sort
() isn't either undefined or a function which compares its operands. Message TypeError: argument is not a function object (Edge) TypeError: invalid Array.prototype.sort argument (Firefox) Error type TypeError What went wrong? ...
... The JavaScript exception "invalid Array.prototype.sort argument" occurs when the argument of Array.prototype.sort
() isn't either undefined or a function which compares its operands. Message TypeError: argument is not a function object (Edge) TypeError: invalid Array.prototype.sort argument (Firefox) Error type TypeError What went wrong? ...
...ay.prototype.sort argument (Firefox) Error type TypeError What went wrong? ...
TypeError: X.prototype.y called on incompatible type - JavaScript
e target (Firefox) TypeError: Method Set.prototype.add called on incompatible receiver undefined (Chrome) TypeError: Bind must be called on a function (Chrome) Error type TypeError What went wrong? When this error is thrown, a function (on a given object), is called with a this not corresponding to the type expected by the function. This issue can arise when using the Function.prototype.call
() or Function.prototype.apply
() methods, and providing a this argument which does not have the expected type. This issue can also happen when providing a function that is stored as a property of an object as an argument to another function. In this case, the object that stores the function won't be the this target of that function when it is called by the other function. To work-around this issue,...
... type. This issue can also happen when providing a function that is stored as a property of an object as an argument to another function. In this case, the object that stores the function won't be the this target of that function when it is called by the other function. To work-around this issue, you will either need to provide a lambda which is making the call, or use the Function.prototype.bind
() function to force the this argument to the expected object. Examples Invalid cases var mySet = new Set; ['bar', 'baz'].forEach(mySet.add); // mySet.add is a function, but "mySet" is not captured as this. var myFun = function
() { console.log(this); }; ['bar', 'baz'].forEach(myFun.bind); // myFun.bind is a function, but "myFun" is not captured as this. Valid cases var mySet = new Set; ['...
...', 'baz'].forEach(mySet.add); // mySet.add is a function, but "mySet" is not captured as this. var myFun = function
() { console.log(this); }; ['bar', 'baz'].forEach(myFun.bind); // myFun.bind is a function, but "myFun" is not captured as this. Valid cases var mySet = new Set; ['bar', 'baz'].forEach(mySet.add.bind(mySet)); // This works due to binding "mySet" as this. var myFun = function
() { console.log(this); }; ['bar', 'baz'].forEach(x => myFun.bind(x)); // This works using the "bind" function. It creates a lambda forwarding the argument. ...
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
ng methods to be applied to any object. ...
...r num = 15; String(num).replace(/5/, '2'); Shim The following is a shim to provide support to non-supporting browsers: /*globals define*/ // Assumes all supplied String instance methods already present // (one may use shims for these if not available) (function
() { 'use strict'; var i, // We could also build the array of methods with the following, but the // getOwnPropertyNames
() method is non-shimable: // Object.getOwnPropertyNames(String).filter(function(methodName) { // return typeof String[methodName] === 'function'; // }); methods = [ 'contains', 'substring', 'toLowerCase', 'toUpperCase', 'charAt', 'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith', 'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase', 'normalize', ...
...plit', 'substr', 'concat', 'localeCompare' ], methodCount = methods.length, assignStringGeneric = function(methodName) { var method = String.prototype[methodName]; String[methodName] = function(arg1) { return method.apply(arg1, Array.prototype.slice.call(arguments, 1)); }; }; for (i = 0; i < methodCount; i++) { assignStringGeneric(methods[i]); } }
()); ...
Warning: Date.prototype.toLocaleFormat is deprecated - JavaScript
Date.prototype.toLocaleFormat method is used. Message Warning: Date.prototype.toLocaleFormat is deprecated; consider using Intl.DateTimeFormat instead Error type Warning. JavaScript execution won't be halted. What went wrong? The non-standard Date.prototype.toLocaleFormat method is deprecated and shouldn't be used anymore. It uses a format string in the same format expected by the strftime
() function in C. The function is no longer available in Firefox 58+. Examples Deprecated syntax The Date.prototype.toLocaleFormat method is deprecated and will be removed (no cross-browser support, available in Firefox only). var today = new Date
(); var date = today.toLocaleFormat('%A, %e. %B %Y'); console.log(date); // In German locale // "Freitag, 10. Marz 2017" Alternative standard syntax ...
... 10. Marz 2017" Alternative standard syntax using the ECMAScript Intl API The ECMA-402 (ECMAScript Intl API) standard specifies standard objects and methods that enable language sensitive date and time formatting (available in Chrome 24+, Firefox 29+, IE11+, Safari10+). You can now either use the Date.prototype.toLocaleDateString method if you just want to format one date. var today = new Date
(); var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var date = today.toLocaleDateString('de-DE', options); console.log(date); // "Freitag, 10. Marz 2017" Or, you can make use of the Intl.DateTimeFormat object, which allows you to cache an object with most of the computations done so that formatting is fast. This is useful if you have a loop of da...
...tter = new Intl.DateTimeFormat('de-DE', options) var dates = [Date.UTC(2012, 11, 20, 3, 0, 0), Date.UTC(2014, 04, 12, 8, 0, 0)]; dates.forEach(date => console.log(dateFormatter.format(date))); // "Donnerstag, 20. Dezember 2012" // "Montag, 12. Mai 2014" Alternative standard syntax using Date methods The Date object offers several methods to build a custom date string. (new Date
()).toLocaleFormat("%Y%m%d"); // "20170310" Can be converted to: let now = new Date
(); let date = now.getFullYear
() * 10000 + (now.getMonth
() + 1) * 100 + now.getDate
(); console.log(date); // "20170310" ...
RangeError: invalid date - JavaScript
The JavaScript exception "invalid date" occurs when a string leading to an invalid date has been provided to Date or Date.parse
(). Message RangeError: invalid date (Edge) RangeError: invalid date (Firefox) RangeError: invalid time value (Chrome) RangeError: Provided date is not in valid range (Chrome) Error type RangeError What went wrong? ...
... "invalid date" occurs when a string leading to an invalid date has been provided to Date or Date.parse
(). Message RangeError: invalid date (Edge) RangeError: invalid date (Firefox) RangeError: invalid time value (Chrome) RangeError: Provided date is not in valid range (Chrome) Error type RangeError What went wrong? ...
...ate has been provided to Date or Date.parse
(). Examples Invalid cases Unrecognizable strings or dates containing illegal element values in ISO formatted strings usually return NaN. However, depending on the implementation, non-conforming ISO format strings, may also throw RangeError: invalid date, like the following cases in Firefox: new Date('foo-bar 2014'); new Date('2014-25-23').toISOString
(); new Date('foo-bar 2014').toString
(); This, however, returns NaN in Firefox: Date.parse('foo-bar 2014'); // NaN For more details, see the Date.parse
() documentation. Valid cases new Date('05 October 2011 14:48 UTC'); new Date(1317826080); // Unix Time Stamp for 05 October 2011 14:48:00 UTC ...
SyntaxError: JSON.parse: bad parsing - JavaScript
The JavaScript exceptions thrown by JSON.parse
() occur when string failed to be parsed as JSON. Message SyntaxError: JSON.parse: unterminated string literal SyntaxError: JSON.parse: bad control character in string literal SyntaxError: JSON.parse: bad character in string literal SyntaxError: JSON.parse: bad Unicode escape SyntaxError: JSON.parse: bad escape character SyntaxError: JSON.parse: unterminated string SyntaxError: JSON.parse: no number after minus sign SyntaxError: JSON.parse: unexpected non-digit SyntaxError: JSON.parse: missing digits after decimal point SyntaxError: JSON.parse: unterminated fractional number SyntaxError: JSON.parse: missing digits after exponent indicator SyntaxError: JSON.parse: missing digits after exponent sign SyntaxError: JSON.parse: exponent part is miss...
...ue pair in object literal SyntaxError: JSON.parse: property names must be double-quoted strings SyntaxError: JSON.parse: expected property name or '}' SyntaxError: JSON.parse: unexpected character SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data SyntaxError: JSON.parse Error: Invalid character at position {0} (Edge) Error type SyntaxError What went wrong? ...
...r '}' SyntaxError: JSON.parse: unexpected character SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data SyntaxError: JSON.parse Error: Invalid character at position {0} (Edge) Error type SyntaxError What went wrong? JSON.parse
() parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered. ...
TypeError: More arguments needed - JavaScript
1 argument, but only 0 were passed TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 0 were passed TypeError: Object.defineProperties requires at least 1 argument, but only 0 were passed Error type TypeError. What went wrong? There is an error with how a function is called. More arguments need to be provided. ...
...quires at least 2 arguments, but only 0 were passed TypeError: Object.defineProperties requires at least 1 argument, but only 0 were passed Error type TypeError. What went wrong? There is an error with how a function is called. More arguments need to be provided. ...
...ct.defineProperties requires at least 1 argument, but only 0 were passed Error type TypeError. What went wrong? There is an error with how a function is called. More arguments need to be provided. ...
TypeError: "x" is not a constructor - JavaScript
is. There are many global objects, like String or Array, which are constructable using new. However, some global objects are not and their properties and methods are static. The following JavaScript standard built-in objects are not a constructor: Math, JSON, Symbol, Reflect, Intl, Atomics. Generator functions cannot be used as constructors either. Examples Invalid cases var Car = 1; new Car
(); // TypeError: Car is not a constructor new Math
(); // TypeError: Math is not a constructor new Symbol
(); // TypeError: Symbol is not a constructor function* f
() {}; var obj = new f; // TypeError: f is not a constructor A car constructor Suppose you want to create an object type for cars. You want this type of object to be called car, and you want it to have properties for make, model, and ...
...mycar = new Car('Eagle', 'Talon TSi', 1993); In Promises When returning an immediately-resolved or immediately-rejected Promise, you do not need to create a new Promise(...) and act on it. ...
...le', 'Talon TSi', 1993); In Promises When returning an immediately-resolved or immediately-rejected Promise, you do not need to create a new Promise(...) and act on it. ...
Warning: unreachable code after return statement - JavaScript
on-less return statements, it can be unclear whether the developer intended to return the statement on the following line, or to stop execution and return. The warning indicates that there is ambiguity in the way the return statement is written. ...
...warning indicates that there is ambiguity in the way the return statement is written. ...
...tatements follow it: throw break var function Examples Invalid cases function f
() { var x = 3; x += 4; return x; // return exits the function immediately x -= 3; // so this line will never run; it is unreachable } function f
() { return // this is treated like `return;` 3 + 4; // so the function returns, and this line is never reached } Valid cases function f
() { var x = 3; x += 4; x -= 3; return x; // OK: return after all other statements } function f
() { return 3 + 4 // OK: semicolon-less return with expression on the same line } ...
Generator - JavaScript
The Generator object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol. Constructor This object cannot be instantiated directly. Instead, a Generator instance can be returned from a generator function: function* generator
() { yield 1; yield 2; yield 3; } const gen = generator
(); // "Generator { }" Instance methods Generator.prototype.next
() Returns a value yielded by the yield expression. ...
...e protocol and the iterator protocol. Constructor This object cannot be instantiated directly. Instead, a Generator instance can be returned from a generator function: function* generator
() { yield 1; yield 2; yield 3; } const gen = generator
(); // "Generator { }" Instance methods Generator.prototype.next
() Returns a value yielded by the yield expression. Generator.prototype.return
() Returns the given value and finishes the generator. Generator.prototype.throw
() Throws an error to a generator (also finishes the generator, unless caught from within that generator). ...
... generator
(); // "Generator { }" Instance methods Generator.prototype.next
() Returns a value yielded by the yield expression. Generator.prototype.return
() Returns the given value and finishes the generator. Generator.prototype.throw
() Throws an error to a generator (also finishes the generator, unless caught from within that generator). Examples An infinite iterator function* infinite
() { let index = 0; while (true) { yield index++; } } const generator = infinite
(); // "Generator { }" console.log(generator.next
().value); // 0 console.log(generator.next
().value); // 1 console.log(generator.next
().value); // 2 // ... Specifications Specification ECMAScript (ECMA-262)The definition of 'Generator objects' in that specification. ...
Intl.DisplayNames - JavaScript
Intl.DisplayNames object is a constructor for objects that enables the consistent translation of language, region and script display names. 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. ...
...guage, region and script display names. 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. Constructor Intl.DisplayNames
() Creates a new Intl.DisplayNames object. ...
... https://github.com/mdn/interactive-examples and send us a pull request. Constructor Intl.DisplayNames
() Creates a new Intl.DisplayNames object. Static methods Intl.DisplayNames.supportedLocalesOf
() Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. Instance methods Intl.DisplayNames.prototype.of
() This method receives a code and returns a string based on the locale and options provided when instantiating Intl.DisplayNames. Intl.DisplayNames.prototype.resolvedOptions
() Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object. Examples Region Code Display Names To create an Intl.DisplayNames for a locale and get the...
Intl.ListFormat - JavaScript
The Intl.ListFormat object is a constructor for objects that enable language-sensitive list formatting. 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. Constructor Intl.ListFormat
() Creates a new ListFormat object. ...
...ts that enable language-sensitive list formatting. 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. Constructor Intl.ListFormat
() Creates a new ListFormat object. ...
...ase clone https://github.com/mdn/interactive-examples and send us a pull request. Constructor Intl.ListFormat
() Creates a new ListFormat object. Static methods Intl.ListFormat.supportedLocalesOf
() Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. Instance methods Intl.ListFormat.prototype.format
() Returns a language-specific formatted string representing the elements of the list. Intl.ListFormat.prototype.formatToParts
() Returns an array of objects representing the different components that can be used to format a list of values in a locale-aware fashion. Examples Using format The following example shows how to create a List formatter using the English language. const list = ['Moto...
Intl.NumberFormat - JavaScript
The Intl.NumberFormat object is a constructor for objects that enable language sensitive number formatting. 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. Constructor Intl.NumberFormat
() Creates a new NumberFormat object. Static methods Intl.NumberFormat.supportedLocalesOf
() Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. Instance methods Intl.NumberFormat.prototype.format
() Getter function that formats a number according to the locale and formatting options of this NumberFormat object. Intl.NumberFormat.pro...
...ds Intl.NumberFormat.supportedLocalesOf
() Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. Instance methods Intl.NumberFormat.prototype.format
() Getter function that formats a number according to the locale and formatting options of this NumberFormat object. Intl.NumberFormat.prototype.formatToParts
() Returns an Array of objects representing the number string in parts that can be used for custom locale-aware formatting. Intl.NumberFormat.prototype.resolvedOptions
() Returns a new object with properties reflecting the locale and collation options computed during initialization of the object. Examples Basic usage In basic use without specifying a locale, a formatted string in the default l...
...locale-aware formatting. Intl.NumberFormat.prototype.resolvedOptions
() Returns a new object with properties reflecting the locale and collation options computed during initialization of the object. Examples Basic usage In basic use without specifying a locale, a formatted string in the default locale and with default options is returned. var number = 3500; console.log(new Intl.NumberFormat
().format(number)); // -> '3,500' if in US English locale Using locales This example shows some of the variations in localized number formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: var number = 123456.789; // German uses comma as decimal sepa...
Intl - JavaScript
The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. The Intl object provides access to several constructors as well as functionality common to the internationalization constructors and other language sensitive functions. ...
...ive string comparison, number formatting, and date and time formatting. The Intl object provides access to several constructors as well as functionality common to the internationalization constructors and other language sensitive functions. Constructor properties Intl.Collator
() Constructor for collators, which are objects that enable language-sensitive string comparison. Intl.DateTimeFormat
() Constructor for objects that enable language-sensitive date and time formatting. Intl.DisplayNames
() Constructor for objects that enable the consistent translation of language, region and script display names. Intl.ListFormat
() Constructor for objects that enable language-sensitive list formatting. Intl.Locale
() Constructor for objects that represents a Unicode locale identifier. Intl.Num...
...ctor for objects that enable language-sensitive date and time formatting. Intl.DisplayNames
() Constructor for objects that enable the consistent translation of language, region and script display names. Intl.ListFormat
() Constructor for objects that enable language-sensitive list formatting. Intl.Locale
() Constructor for objects that represents a Unicode locale identifier. Intl.NumberFormat
() Constructor for objects that enable language-sensitive number formatting. Intl.PluralRules
() Constructor for objects that enable plural-sensitive formatting and language-specific rules for plurals. Intl.RelativeTimeFormat
() Constructor for objects that enable language-sensitive relative time formatting. Static methods Intl.getCanonicalLocales
() Returns canonical locale names. Locale ...
Symbol.matchAll - JavaScript
The Symbol.matchAll well-known symbol returns an iterator, that yields matches of the regular expression against a string. This function is called by the String.prototype.matchAll
() method. 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 This Symbol is used for String.prototype.matchAll
() and specifically in RegExp.prototype[@@matchAll]
(). The following two examples return same result: 'abc'.matchAll(/a/); /a/[Symbol.matchAll]('abc'); This method exists for customizing match behavior within RegExp subclasses. Property attributes of Symbol.matchAll Writable ...
... Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.matchAll' in that specification. ...
... Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.matchAll' in that specification. ...
WeakMap - JavaScript
ng keys to information about the key that is valuable only if the key has not been garbage collected. Because the references are weak, WeakMap keys are not enumerable. There is no method to obtain a list of the keys. If they were, the list would depend on the state of garbage collection, introducing non-determinism. If you want to have a list of keys, you should use a Map. Constructor WeakMap
() Creates a new WeakMap object. Instance methods WeakMap.prototype.delete(key) Removes any value associated to the key. WeakMap.prototype.has(key) will return false afterwards. WeakMap.prototype.get(key) Returns the value associated to the key, or undefined if there is none. WeakMap.prototype.has(key) Returns a Boolean asserting whether a value has been associated to the key in the WeakM...
... WeakMap.prototype.get(key) Returns the value associated to the key, or undefined if there is none. WeakMap.prototype.has(key) Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not. WeakMap.prototype.set(key, value) Sets the value for the key in the WeakMap object. Returns the WeakMap object. Examples Using WeakMap const wm1 = new WeakMap
(), wm2 = new WeakMap
(), wm3 = new WeakMap
(); const o1 = {}, o2 = function
() {}, o3 = window; wm1.set(o1, 37); wm1.set(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3, undefined); wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps! wm1.get(o2); // "azerty" wm2.get(o2); // undefined, because there ...
...wm1.get(o2); // "azerty" wm2.get(o2); // undefined, because there is no key for o2 on wm2 wm2.get(o3); // undefined, because that is the set value wm1.has(o2); // true wm2.has(o2); // false wm2.has(o3); // true (even if the value itself is 'undefined') wm3.set(o1, 37); wm3.get(o1); // 37 wm1.has(o1); // true wm1.delete(o1); wm1.has(o1); // false Implementing a WeakMap-like class with a .clear
() method class ClearableWeakMap { constructor(init) { this._wm = new WeakMap(init); } clear
() { this._wm = new WeakMap
(); } delete(k) { return this._wm.delete(k); } get(k) { return this._wm.get(k); } has(k) { return this._wm.has(k); } set(k, v) { this._wm.set(k, v); return this; } } Specifications Specification ECMAScript...
WeakSet - JavaScript
le. Use case: Detecting circular references Functions that call themselves recursively need a way of guarding against circular data structures by tracking which objects have already been processed. ...
... => console.log(obj), foo); Here, a WeakSet is created on the first run, and passed along with every subsequent function call (using the internal _refs parameter). The number of objects or their traversal order is immaterial, so a WeakSet is more suitable (and performant) than a Set for tracking object references, especially if a very large number of objects is involved. Constructor WeakSet
() Creates a new WeakSet object. Instance methods WeakSet.prototype.add(value) Appends value to the WeakSet object. WeakSet.prototype.delete(value) Removes value from the WeakSet. WeakSet.prototype.has(value) will return false afterwards. WeakSet.prototype.has(value) Returns a boolean asserting whether value is present in the WeakSet object or not. Examples Using the WeakSet object c...
...et object. Instance methods WeakSet.prototype.add(value) Appends value to the WeakSet object. WeakSet.prototype.delete(value) Removes value from the WeakSet. WeakSet.prototype.has(value) will return false afterwards. WeakSet.prototype.has(value) Returns a boolean asserting whether value is present in the WeakSet object or not. Examples Using the WeakSet object const ws = new WeakSet
(); const foo = {}; const bar = {}; ws.add(foo); ws.add(bar); ws.has(foo); // true ws.has(bar); // true ws.delete(foo); // removes foo from the set ws.has(foo); // false, foo has been removed ws.has(bar); // true, bar is retained Note that foo !== bar. While they are similar objects, they are not the same object. And so they are both added to the set. Specifications Specif...
WebAssembly.CompileError - JavaScript
Instance properties WebAssembly.CompileError.prototype.message Error message. Although ECMA-262 specifies that URIError should provide its own message property, in SpiderMonkey, it inherits Error.prototype.message. WebAssembly.CompileError.prototype.name Error name. Inherited from Error. WebAssembly.CompileError.prototype.fileName Path to file that raised this error. Inherited from Error. ...
...r. Inherited from Error. WebAssembly.CompileError.prototype.lineNumber Line number in file that raised this error. Inherited from Error. WebAssembly.CompileError.prototype.columnNumber Column number in line that raised this error. Inherited from Error. WebAssembly.CompileError.prototype.stack Stack trace. Inherited from Error. Instance methods WebAssembly.CompileError.prototype.toSource
() Returns code that could eval to the same error. Inherited from Error. WebAssembly.CompileError.prototype.toString
() Returns a string representing the specified Error object.. Inherited from Error. Examples Creating a new CompileError instance The following snippet creates a new CompileError instance, and logs its details to the console: try { throw new WebAssembly.CompileError('Hello', ...
... 52Notes Notes Disabled in the Firefox 52 Extended Support Release (ESR).Opera Android Full support 43Safari iOS Full support 11Samsung Internet Android Full support 7.0nodejs Full support 8.0.0CompileError
() constructorChrome Full support 57Edge Full support 16Firefox Full support 52Notes Full support 52Notes Notes Disabled in the Firefox 52 Extended Support Release (ESR).IE No support ...
WebAssembly.LinkError - JavaScript
Instance properties WebAssembly.LinkError.prototype.message Error message. Although ECMA-262 specifies that URIError should provide its own message property, in SpiderMonkey, it inherits Error.prototype.message. WebAssembly.LinkError.prototype.name Error name. Inherited from Error. WebAssembly.LinkError.prototype.fileName Path to file that raised this error. Inherited from Error. ...
...ed this error. Inherited from Error. WebAssembly.LinkError.prototype.lineNumber Line number in file that raised this error. Inherited from Error. WebAssembly.LinkError.prototype.columnNumber Column number in line that raised this error. Inherited from Error. WebAssembly.LinkError.prototype.stack Stack trace. Inherited from Error. Instance methods WebAssembly.LinkError.prototype.toSource
() Returns code that could eval to the same error. Inherited from Error. WebAssembly.LinkError.prototype.toString
() Returns a string representing the specified Error object.. Inherited from Error. Examples Creating a new LinkError instance The following snippet creates a new LinkError instance, and logs its details to the console: try { throw new WebAssembly.LinkError('Hello', 'someFile', ...
... 52Notes Notes Disabled in the Firefox 52 Extended Support Release (ESR).Opera Android Full support 43Safari iOS Full support 11Samsung Internet Android Full support 7.0nodejs Full support 8.0.0LinkError
() constructorChrome Full support 57Edge Full support 16Firefox Full support 52Notes Full support 52Notes Notes Disabled in the Firefox 52 Extended Support Release (ESR).IE No support ...
WebAssembly.Memory - JavaScript
The WebAssembly.Memory object is a resizable ArrayBuffer or SharedArrayBuffer that holds the raw bytes of memory accessed by a WebAssembly Instance. A memory created by JavaScript or in WebAssembly code will be accessible and mutable from both JavaScript and WebAssembly. Constructor WebAssembly.Memory
() Creates a new Memory object. Instance properties Memory.prototype.buffer An accessor property that returns the buffer contained in the memory. Instance methods Memory.prototype.grow
() Increases the size of the memory instance by a specified number of WebAssembly pages (each one is 64KB in size). Examples Creating a new Memory object There are two ways to get a WebAssembly.Memory object. The first way is to construct it from JavaScript. The following example creates a ne...
...ges (6.4MiB). Its buffer property will return an ArrayBuffer. var memory = new WebAssembly.Memory({initial:10, maximum:100}); The second way to get a WebAssembly.Memory object is to have it exported by a WebAssembly module. The following example (see memory.html on GitHub, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the WebAssembly.instantiateStreaming
() method, while importing the memory created in the line above. It then stores some values in that memory, then exports a function and uses it to sum some values. WebAssembly.instantiateStreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new Uint32Array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0...
... 52Notes Notes Disabled in the Firefox 52 Extended Support Release (ESR).Opera Android Full support 43Safari iOS Full support 11Samsung Internet Android Full support 7.0nodejs Full support 8.0.0Memory
() constructorChrome Full support 57Edge Full support 16Firefox Full support 52Notes Full support 52Notes Notes Disabled in the Firefox 52 Extended Support Release (ESR).IE No support ...
WebAssembly.RuntimeError - JavaScript
Instance properties WebAssembly.RuntimeError.prototype.message Error message. Although ECMA-262 specifies that URIError should provide its own message property, in SpiderMonkey, it inherits Error.prototype.message. WebAssembly.RuntimeError.prototype.name Error name. Inherited from Error. WebAssembly.RuntimeError.prototype.fileName Path to file that raised this error. Inherited from Error. ...
...r. Inherited from Error. WebAssembly.RuntimeError.prototype.lineNumber Line number in file that raised this error. Inherited from Error. WebAssembly.RuntimeError.prototype.columnNumber Column number in line that raised this error. Inherited from Error. WebAssembly.RuntimeError.prototype.stack Stack trace. Inherited from Error. Instance methods WebAssembly.RuntimeError.prototype.toSource
() Returns code that could eval to the same error. Inherited from Error. WebAssembly.RuntimeError.prototype.toString
() Returns a string representing the specified Error object.. Inherited from Error. Examples Creating a new RuntimeError instance The following snippet creates a new RuntimeError instance, and logs its details to the console: try { throw new WebAssembly.RuntimeError('Hello', ...
... 52Notes Notes Disabled in the Firefox 52 Extended Support Release (ESR).Opera Android Full support 43Safari iOS Full support 11Samsung Internet Android Full support 7.0nodejs Full support 8.0.0RuntimeError
() constructorChrome Full support 57Edge Full support 16Firefox Full support 52Notes Full support 52Notes Notes Disabled in the Firefox 52 Extended Support Release (ESR).IE No support ...
Equality (==) - JavaScript
s, try to convert them to the same type before comparing: When comparing a number to a string, try to convert the string to a numeric value. If one of the operands is Boolean, convert the Boolean operand to 1 if it is true and +0 if it is false. If one of the operands is an object and the other is a number or a string, try to convert the object to a primitive using the object's valueOf
() and toString
() methods. If the operands have the same type, they are compared as follows: String: return true only if both operands have the same characters in the same order. Number: return true only if both operands have the same value. +0 and -0 are treated as the same value. If either operand is NaN, return false. Boolean: return true only if operands are both true or both f...
...If you compare one of these with a string literal, the String object will be converted to a string literal and the contents will be compared. However, if both operands are String objects, then they are compared as objects and must reference the same object for comparison to succeed: const string1 = "hello"; const string2 = String("hello"); const string3 = new String("hello"); const ...
... ...
Function expression - JavaScript
ch runs as soon as it is defined. See also the chapter about functions for more information. Function expression hoisting Function expressions in JavaScript are not hoisted, unlike function declarations. You can't use function expressions before you create them: console.log(notHoisted) // undefined // even though the variable name is hoisted, the definition isn't. so it's undefined. notHoisted
(); // 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'...
...ession is assigned to will have a name property. The name doesn't change if it's assigned to a different variable. If function name is omitted, it will be the variable name (implicit name). If function name is present, it will be the function name (explicit name). This also applies to arrow functions (arrows don't have a name so you can only give the variable an implicit name). var foo = function
() {} foo.name // "foo" var foo2 = foo foo2.name // "foo" var bar = function baz
() {} bar.name // "baz" console.log(foo === foo2); // true console.log(typeof baz); // undefined console.log(bar === baz); // false (errors because baz == undefined) Examples Creating an unnamed function The following example defines an unnamed function and assigns it to x. The function returns the square of its a...
...ed function and assigns it to x. The function returns the square of its argument: var x = function(y) { return y * y; }; Using a function as a callback More commonly it is used as a callback: button.addEventListener('click', function(event) { console.log('button is clicked!') }) Using an immediately executed function expression An anonymous function is created and called: (function
() { console.log('Code runs!') })
(); Specifications Specification ECMAScript (ECMA-262)The definition of 'Function definitions' in that specification. ...
typeof - JavaScript
; typeof `template literal` === 'string'; typeof '1' === 'string'; // note that a number within a string is still typeof string typeof (typeof 1) === 'string'; // typeof always returns a string typeof String(1) === 'string'; // String converts anything into a string, safer than toString // Booleans typeof true === 'boolean'; typeof false === 'boolean'; typeof Boolean(1) === 'boolean'; // Boolean
() will convert values based on if they're truthy or falsy typeof !!(1) === 'boolean'; // two calls of the ! (logical NOT) operator are equivalent to Boolean
() // Symbols typeof Symbol
() === 'symbol' typeof Symbol('foo') === 'symbol' typeof Symbol.iterator === 'symbol' // Undefined typeof undefined === 'undefined'; typeof declaredButUndefinedVariable === 'undefined'; typeof undeclaredVariable ==...
...Symbol('foo') === 'symbol' typeof Symbol.iterator === 'symbol' // Undefined typeof undefined === 'undefined'; typeof declaredButUndefinedVariable === 'undefined'; typeof undeclaredVariable === 'undefined'; // Objects typeof {a: 1} === 'object'; // use Array.isArray or Object.prototype.toString.call // to differentiate regular objects from arrays typeof [1, 2, 4] === 'object'; typeof new Date
() === 'object'; typeof /regex/ === 'object'; // See Regular expressions section for historical results // The following are confusing, dangerous, and wasteful. Avoid them. typeof new Boolean(true) === 'object'; typeof new Number(1) === 'object'; typeof new String('abc') === 'object'; // Functions typeof function
() {} === 'function'; typeof class C {} === 'function'; typeof Math.sin === 'functio...
...roposed for ECMAScript (via an opt-in), but was rejected. It would have resulted in typeof null === 'null'. Using new operator // All constructor functions, with the exception of the Function constructor, will always be typeof 'object' let str = new String('String'); let num = new Number(100); typeof str; // It will return 'object' typeof num; // It will return 'object' let func = new Function
(); typeof func; // It will return 'function' Need for parentheses in Syntax // Parentheses can be used for determining the data type of expressions. let iData = 99; typeof iData + ' Wisen'; // 'number Wisen' typeof (iData + ' Wisen'); // 'string' Regular expressions Callable regular expressions were a non-standard addition in some browsers. typeof /s/ === 'function'; // Chrome 1-12 Non-con...
export - JavaScript
declare them as such or not. The export statement cannot be used in embedded scripts. Syntax There are two types of exports: Named Exports (Zero or more exports per module) Default Exports (One per module) // Exporting individual features export let name1, name2, ..., nameN; // also var, const export let name1 = ..., name2 = ..., ..., nameN; // also var, const export function functionName
(){...} export class ClassName {...} // Export list export { name1, name2, ..., nameN }; // Renaming exports export { variable1 as name1, variable2 as name2, ..., nameN }; // Exporting destructured assignments with renaming export const { name1, name2: bar } = o; // Default exports export default expression; export default function (...) { ... } // also class, function* export default function n...
...erent types of export, named and default. You can have multiple named exports per module but only one default export. Each type corresponds to one of the above syntax: Named exports: // export features declared earlier export { myFunction, myVariable }; // export individual features (can export var, let, // const, function, class) export let myVariable = Math.sqrt(2); export function myFunction
() { ... }; Default exports: // export feature declared earlier as default export { myFunction as default }; // export individual features as default export default function
() { ... } export default class { .. } Named exports are useful to export several values. During the import, it is mandatory to use the same name of the corresponding object. But a default export can be imported with any n...
...d The correct way of doing this is to rename the export: export { default as DefaultExport } from 'bar.js'; Examples Using named exports In a module my-module.js, we could include the following code: // module "my-module.js" function cube(x) { return x * x * x; } const foo = Math.PI + Math.SQRT2; var graph = { options: { color:'white', thickness:'2px' }, draw: function
() { console.log('From graph draw function'); } } export { cube, foo, graph }; Then in the top-level module included in your HTML page, we could have: import { cube, foo, graph } from './my-module.js'; graph.options = { color:'blue', thickness:'3px' }; graph.draw
(); console.log(cube(3)); // 27 console.log(foo); // 4.555806215962888 It is important to note the following: ...
function declaration - JavaScript
nction statement can be nested within an if statement, however the results are inconsistent across implementations and therefore this pattern should not be used in production code. For conditional function creation, use function expressions instead. var hoisted = "foo" in this; console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`); if (false) { function foo
(){ return 1; } } // 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 The results are exactly the same for a condition that evaluates to true var hoisted = "foo" in this; console.log(...
... 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 The results are exactly the same for a condition that evaluates to true var hoisted = "foo" in this; console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`); if (true) { function foo
(){ return 1; } } // 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 functio...
...ined // // 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 given the number of units sold of products a, b, and c. func...
throw - JavaScript
* 12345 6789 * * If the argument passed to the ZipCode constructor does not * conform to one of these patterns, an exception is thrown. ...
...r does not * conform to one of these patterns, an exception is thrown. ...
...match(pattern)[0]; this.valueOf = function
() { return this.value }; this.toString = function
() { return String(this.value) }; } else { throw new ZipCodeFormatException(zip); } } function ZipCodeFormatException(value) { this.value = value; this.message = 'does not conform to the expected format for a zip code'; this.toString = function
() { return this.value + this.message; }; } /* * This could be in a script that validates address data * for US addresses. */ const ZIPCODE_INVALID = -1; const ZIPCODE_UNKNOWN_ERROR = -2; function verifyZipCode(z) { try { z = new ZipCode(z); } catch (e) { if (e instanceof ZipCodeFormatException) { return ZIPCODE_INVALID; } else { return ZIPCOD...
Template literals (Template strings) - JavaScript
ting templates In certain cases, nesting a template is the easiest (and perhaps more readable) way to have configurable strings. Within a backticked template, it is simple to allow inner backticks simply by using them inside a placeholder ${ } within the template. For instance, if condition a is true, then return this templated literal. ...
...e to allow inner backticks simply by using them inside a placeholder ${ } within the template. For instance, if condition a is true, then return this templated literal. In ES5: let classes = 'header'; classes += (isLargeScreen
() ? '' : item.isCollapsed ? ' icon-expander' : ' icon-collapser'); In ES2015 with template literals and without nesting: const classes = `header ${ isLargeScreen
() ? '' : (item.isCollapsed ? 'icon-expander' : 'icon-collapser') }`; In ES2015 with nested template literals: const classes = `header ${ isLargeScreen
() ? '' : `icon-${item.isCollapsed ? 'expander' : 'collapser'}` }`; Tagged templates A more advanced form of template literals are tagged templates. Tags allow you to parse template literals with a function. The first argument of a tag functi...
...cial raw property, available on the first argument to the tag function, allows you to access the raw strings as they were entered, without processing escape sequences. function tag(strings) { console.log(strings.raw[0]); } tag`string text line 1 \n string text line 2`; // logs "string text line 1 \n string text line 2" , // including the two characters '\' and 'n' In addition, the String.raw
() method exists to create raw strings--just like the default template function and string concatenation would create. let str = String.raw`Hi\n${2+3}!`; // "Hi\n5!" str.length; // 6 Array.from(str).join(','); // "H,i,\,n,5,!" Tagged templates and escape sequences ES2016 behavior As of ECMAScript 2016, tagged templates conform to the rules of the following escape sequences: Unicode escapes...
JavaScript typed arrays - JavaScript
e are times when it would be helpful for JavaScript code to be able to quickly and easily manipulate raw binary data. This is where typed arrays come in. Each entry in a JavaScript typed array is a raw binary value in one of a number of supported formats, from 8-bit integers to 64-bit floating-point numbers. However, typed arrays are not to be confused with normal arrays, as calling Array.isArray
() on a typed array returns false. Moreover, not all methods available for normal arrays are supported by typed arrays (e.g. push and pop). Buffers and views: typed array architecture To achieve maximum flexibility and efficiency, JavaScript typed arrays split the implementation into buffers and views. A buffer (implemented by the ArrayBuffer object) is an object representing a chunk of data; it h...
...re in the native byte-order (see Endianness) of your platform. With a DataView you are able to control the byte-order. It is big-endian by default and can be set to little-endian in the getter/setter methods. Web APIs using typed arrays These are some examples of APIs that make use of typed arrays; there are others, and more are being added all the time. FileReader.prototype.readAsArrayBuffer
() The FileReader.prototype.readAsArrayBuffer
() method starts reading the contents of the specified Blob or File. XMLHttpRequest.prototype.send
() XMLHttpRequest instances' send
() method now supports typed arrays and ArrayBuffer objects as argument. ImageData.data Is a Uint8ClampedArray representing a one-dimensional array containing the data in the RGBA order, with integer values between 0 and ...
...ess, for example, the amount due with amountDueView[0]. Note: The data structure alignment in a C structure is platform-dependent. Take precautions and considerations for these padding differences. Conversion to normal arrays After processing a typed array, it is sometimes useful to convert it back to a normal array in order to benefit from the Array prototype. This can be done using Array.from
(), or using the following code where Array.from
() is unsupported. let typedArray = new Uint8Array([1, 2, 3, 4]), normalArray = Array.prototype.slice.call(typedArray); normalArray.length === 4; normalArray.constructor === Array; Specifications Specification ECMAScript (ECMA-262)The definition of 'TypedArray Objects' in that specification. ...
The building blocks of responsive design - Progressive web apps (PWAs)
essentially, this means using a combination of percentages and ems/rems to size your containers and text, not fixed widths such as pixels. This has a lot of advantages in that the layout will adapt to different viewport dimensions. Let's look at an example. We've written a simple-but-fun prototype for an application called Snapshot, which takes a video stream from your webcam (using getUserMedia
()) then allows you to capture stills from that video stream (using HTML5 <canvas>), and save them to a gallery. You can then view previously-captured images and delete them. Other articles will discuss the functionality in more detail, but here we're interested in the layout. Note: You can find the Snapshot app on Github; check out the code and help improve it. You can also see Snapshot running l...
...e stills from that video stream (using HTML5 <canvas>), and save them to a gallery. You can then view previously-captured images and delete them. Other articles will discuss the functionality in more detail, but here we're interested in the layout. Note: You can find the Snapshot app on Github; check out the code and help improve it. You can also see Snapshot running live. Note that getUserMedia
() is an experimental technology, which currently only works in Google Chrome and Firefox desktop. More functionality and a clean up of the styling of Snapshot are planned for a future date. Our desktop layout for Snapshot is three columns, containing the camera viewer, image capture view, and gallery, respectively. The markup is very simple: <x-deck selected-index="0"> <x-card> ... </...
...ibute: <link href="dist/brick.css" type="text/css" rel="stylesheet" media="all and (max-width: 480px)"> This says that the whole stylesheet will not be linked to the HTML unless the viewport width is 480px or less. Moving on to the JavaScript, <script> elements don't accept media attributes, so I had to do this a different way. Fortunately there is a JavaScript construct called window.matchMedia
(), which can conditionally run JavaScript constructs depending on whether a media query returns true or not. We opened up the brick.js file and wrapped the whole lot in the following: if (window.matchMedia("(max-width: 480px)").matches) { // The whole of brick.js goes here! } This causes nothing inside the brick.js file to be run unless the viewport width is 480px or less. Problem solved. Real...
end - SVG: Scalable Vector Graphics
croll, beginEvent, endEvent, and repeatEvent . An optional offset value as defined in <offset-value> can be appended. <repeat-value> This value defines a qualified repeat event. The element animation end time is defined relative to the time that the repeat event is raised with the specified iteration value. ...
...The time syntax is based upon the syntax defined in ISO 8601. ...
...nt animation will end when the user presses the specified key. A valid accessKey-value consists of the function accessKey
() with the character to be input as parameter. An optional offset value as defined in <offset-value> can be appended. <wallclock-sync-value> This value defines the animation end time as a real-world clock time. A valid wallclock-sync-value consists of the function wallclock
() with a time value as parameter. The time syntax is based upon the syntax defined in ISO 8601. indefinite The end of the animation will be determined by an SVGAnimationElement.endElement
() method call. Examples Offset example <svg width="120" height="120" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" version="1.1"> <!-- animated rectangles --> <rect x="10" y="35" he...
current - XPath
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The current function can be used to get the context node in an XSLT instruction. Syntax current
() Returns A node-set containing only the current node. Notes This function is an XSLT-specific addition to XPath. It is not a part of the core XPath function library. For an outermost expression (an expression not occurring within another expression), the current node is always the same as the context node (which will be returned by the . or self syntax). The following two are symantically equivalent. <xsl:value-of select="current
()"/> <xsl:value-of select="."/> In an inner expression (e.g. in square brackets), the current node is still the same as it would have been in an outermost expres...
...occurs in an outermost expression. <xsl:variable name="current" select="."/> <xsl:value-of select="foo/bar[$current = X]"/> But the . ...
...ect="."/> In an inner expression (e.g. in square brackets), the current node is still the same as it would have been in an outermost expression. Thus within all of the following three expressions the current function (not the entire expressions) returns the same node. Moreover, the latter two are semantically equivalent. <xsl:value-of select="current
()"/> <xsl:value-of select="foo/bar[current
() = X]"/> <xsl:variable name="current" select="current
()"/> <xsl:value-of select="foo/bar[$current = X]"/> And the next code is also semantically equivalent to the latter two, since the . occurs in an outermost expression. <xsl:variable name="current" select="."/> <xsl:value-of select="foo/bar[$current = X]"/> But the . always relate to the narrowest context. Thus in <xsl:value-of select="f...
The Netscape XSLT/XPath Reference - XSLT: Extensible Stylesheet Language Transformations
e (supported) xsl:text (partially supported) xsl:transform (supported) xsl:value-of (partially supported) xsl:variable (supported) xsl:when (supported) xsl:with-param (supported) Axes ancestor ancestor-or-self attribute child descendant descendant-or-self following following-sibling namespace (not supported) parent preceding preceding-sibling self Functions boolean
() (supported) ceiling
() (supported) concat
() (supported) contains
() (supported) count
() (supported) current
() (supported) document
() (supported) element-available
() (supported) false
() (supported) floor
() (supported) format-number
() (supported) function-available
() (supported) generate-id
() (supported) id
() (partially supported) key
() (supported) lang
() (supported) l...
...supported) ceiling
() (supported) concat
() (supported) contains
() (supported) count
() (supported) current
() (supported) document
() (supported) element-available
() (supported) false
() (supported) floor
() (supported) format-number
() (supported) function-available
() (supported) generate-id
() (supported) id
() (partially supported) key
() (supported) lang
() (supported) last
() (supported) local-name
() (supported) name
() (supported) namespace-uri
() (supported) normalize-space
() (supported) not
() (supported) number
() (supported) position
() (supported) round
() (supported) starts-with
() (supported) string
() (supported) string-length
() (supported) substring
() (supported) substring-after
() (supported) substring-before
() (supported) sum
() (suppo...
...ame
() (supported) name
() (supported) namespace-uri
() (supported) normalize-space
() (supported) not
() (supported) number
() (supported) position
() (supported) round
() (supported) starts-with
() (supported) string
() (supported) string-length
() (supported) substring
() (supported) substring-after
() (supported) substring-before
() (supported) sum
() (supported) system-property
() (supported) translate
() (supported) true
() (supported) unparsed-entity-url
() (not supported) ...
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
Advanced example This advanced example sorts several divs based on their content. The example allows sorting the content multiple times, alternating between ascending and descending order. The JavaScript loads the .xsl file only on the first sort and sets the xslloaded variable to true once it has finished loading the file. Using the XSLTProcessor.getParameter
() method, the code can figure whether to sort in ascending or descending order. It defaults to ascending if the parameter is empty (the first time the sorting happens, as there is no value for it in the XSLT file). The sorting value is set using XSLTProcessor.setParameter
(). The XSLT file has a parameter called myOrder that JavaScript sets to change the sorting method. The xsl:sort element's order attribute can access the val...
...result is appended to the document, as shown in this example. ...
...tentview example // XHTML Fragment: <div id="example"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> <div>10</div> </div> // JavaScript var xslRef; var xslloaded = false; var xsltProcessor = new XSLTProcessor
(); var myDOM; var xmlRef = document.implementation.createDocument("", "", null); function sort
() { if (!xslloaded){ p = new XMLHttpRequest
(); p.open("GET", "example2.xsl", false); p.send(null); xslRef = p.responseXML; xsltProcessor.importStylesheet(xslRef); xslloaded = true; } // create a new XML document in memory xmlRef = document.implementation.createDocument("", "", null); // we want to move a part of the DOM from an HTML document to an XML document. ...
Module structure of the SDK - Archive of obsolete content
SDK-based add-ons. SDK Modules The modules supplied by the SDK are divided into two sorts: High-level modules like panel and page-mod provide relatively simple, stable APIs for the most common add-on development tasks. Low-level modules like heritage and namespace provide more powerful functionality, and are typically less stable and more complex. To use SDK modules, you can pass require
() a complete path, starting with "sdk", to the module you want to use. For high-level modules this is just sdk/<module_name>, and for low-level modules it is sdk/<path_to_module>/<module_name>: // load the high-level "tabs" module var tabs = require("sdk/tabs"); // load the low-level "uuid" module var uuid = require('sdk/util/uuid'); The path to specify for a low-level module is given along wit...
...to modify an existing property // will fail, or throw an exception in strict mode self.data = "foo"; Using modules from outside the Add-on SDK You can use CommonJS modules outside the Add-on SDK, in any environment where you can use Components.utils.import. Just call the following: const { require } = Cu.import("resource://gre/modules/commonjs/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://pat...
Two Types of Scripts - Archive of obsolete content
place where the main logic of your add-on is implemented. Your add-on is implemented as a collection of one or more CommonJS modules. Each module is supplied as a script stored under the lib directory under your add-on's root directory. Minimally you'll have a single module implemented by a script called "main.js", but you can include additional modules in lib, and import them using the require
() function. To learn how to implement and import your own modules, see the tutorial on Implementing Reusable Modules. Content Scripts While your add-on will always have a "main.js" module, you will only need to write content scripts if your add-on needs to manipulate web content. Content scripts are injected into web pages using APIs defined by some of the SDK's modules such as page-mod and panel...
...ripts read the Working with Content Scripts guide. API Access for Add-on Code and Content Scripts The table below summarizes the APIs that are available to each type of script. API Add-on code Content script The global objects defined in the core JavaScript language, such as Math, Array, and JSON. See the reference at MDN. ? ? The require
() and exports globals defined by version 1.0 of the CommonJS Module Specification. You use require
() to import functionality from another module, and exports to export functionality from your module. If require
() is available, then so are the modules supplied in the SDK. ? ? The console global supplied by the SDK. ? ? Globals defined by the HTML5 specification, suc...
clipboard - Archive of obsolete content
are supported: text (plain text) html (a string of HTML) image (a base-64 encoded png) If no data type is provided, then the module will detect it for you. Currently the image type doesn't support transparency on Windows. Examples Set and get the contents of the clipboard. var clipboard = require("sdk/clipboard"); clipboard.set("Lorem ipsum dolor sit amet"); var contents = clipboard.get
(); Set the clipboard contents to some HTML. var clipboard = require("sdk/clipboard"); clipboard.set("<blink>Lorem ipsum dolor sit amet</blink>", "html"); If the clipboard contains HTML content, open it in a new tab. var clipboard = require("sdk/clipboard"); if (clipboard.currentFlavors.indexOf("html") != -1) require("sdk/tabs").open("data:text/html;charset=utf-8," + clipboard.get("html")); S...
..." + "AABzenr0AAAASUlEQVRYhe3O0QkAIAwD0eyqe3Q993AQ3cBSUKpygfsNTy" + "N5ugbQpK0BAADgP0BRDWXWlwEAAAAAgPsA3rzDaAAAAHgPcGrpgAnzQ2FG" + "bWRR9AAAAABJRU5ErkJggg%3D%3D"); If the clipboard contains an image, open it in a new tab. var clipboard = require("sdk/clipboard"); if (clipboard.currentFlavors.indexOf("image") != -1) require("sdk/tabs").open(clipboard.get
()); As noted before, data type can be easily omitted for images. If the intention is set the clipboard to a data URL as string and not as image, it can be done by specifying a different flavor, like text. var clipboard = require("sdk/clipboard"); clipboard.set("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYA" + "AABzenr0AAAASUlEQVRYhe3O0QkAIAwD0eyqe3Q993AQ3cBSUKpygfsNTy"...
hotkeys - Archive of obsolete content
y combination, create a Hotkey object, passing it the combination and a function to be called when the user presses that combination. For example, this add-on defines two hotkey combinations, to show and hide a panel: // Define keyboard shortcuts for showing and hiding a custom panel. var { Hotkey } = require("sdk/hotkeys"); var showHotKey = Hotkey({ combo: "accel-shift-o", onPress: function
() { showMyPanel
(); } }); var hideHotKey = Hotkey({ combo: "accel-alt-shift-o", onPress: function
() { hideMyPanel
(); } }); Choosing Hotkeys Hotkeys should be chosen with care. It's very easy to use combinations that clash with hotkeys defined for Firefox or for other add-ons. The following commonly used hotkey combinations will not pass AMO review: accel-Z, accel-C, accel-X, acce...
...l key. accel: The key used for keyboard shortcuts on the user's platform, which is Control on Windows and Linux, and Command on Mac. Usually, this would be the value you would use. pageup: The Page Up key. pagedown: The Page Down key. onPress Function Function that is invoked when the key combination hotkey is pressed. Hotkey Methods destroy
() Stops this instance of Hotkey from reacting to the key combinations. Once destroyed a Hotkey can no longer be used. ...
selection - Archive of obsolete content
Get and set text and HTML selections in the current web page. Usage Registering for Selection Notifications To be notified when the user makes a selection, register a listener for the "select" event. Each listener will be called after a selection is made. function myListener
() { console.log("A selection has been made."); } var selection = require("sdk/selection"); selection.on('select', myListener); // You can remove listeners too. selection.removeListener('select', myListener); Iterating Over Discontiguous Selections Discontiguous selections can be accessed by iterating over the selection module itself. Each iteration yields a Selection object from which text, html, and isContiguous properties can be accessed. Private Windows If your add-on has not opted into private browsing,...
...Setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the new text. Getting the selection when there is no current selection returns null. Setting the selection when there is no current...
system - Archive of obsolete content
To exit with success, omit this argument. pathFor(id)...
...("name = " + system.name); // host application version console.log("version = " + system.version); // host application vendor console.log("vendor = " + system.vendor); // host application profile directory console.log("profile directory = " + system.pathFor("ProfD")); Quit the host application To quit the host application, use the exit
() function. var system = require("sdk/system"); system.exit
(); Globals Functions exit(code) Quits the host application with the specified code. If code is omitted, exit
() uses the success code 0. To exit with failure use 1. var system = require("sdk/system"); system.exit
(); Parameters code : integer To exit with failure, set this to 1. To exit with success, omit this argument. pathFor(id) Firefox enables you to get the path to certain "special" di...
content/loader - Archive of obsolete content
Provides one of the building blocks for those modules that use content scripts to interact with web content, such as panel and page-mod. Usage The module exports a constructor for the Loader object, which inherits on
(), once
(), and removeListener
() functions that enable its users to listen to events. Loader adds code to initialize and validate a set of properties for managing content scripts: contentURL contentScript contentScriptFile contentScriptWhen contentScriptOptions allow When certain of these properties are set, the Loader emits a propertyChange event, enabling its users to take the appropriate action. The Loader is used by modules that use content scripts but don't themselves load content, such as page-mod. Modules that load their own content, such as panel and pag...
...Content scripts specified by this prope...
event/core - Archive of obsolete content
'data', { type: 'data' }, 'second arg'); // info: [Object object] 'second arg' Registered event listeners may be removed using off function: off(target, 'message'); emit(target, 'message', 'bye'); // info: 'hello bye' Sometimes listener only cares about first event of specific type. To avoid hassles of removing such listeners there is a convenient once function: once(target, 'load', function
() { console.log('ready'); }); emit(target, 'load') // info: 'ready' emit(target, 'load') There are also convenient ways to remove registered listeners. All listeners of the specific type can be easily removed (only two argument must be passed): off(target, 'message'); Also, removing all registered listeners is possible (only one argument must be passed): off(target); Globals Functions o...
..., type, listener) Removes an event listener for the given event type on the given event target. If no listener is passed removes all listeners of the given type. If type is not passed removes all the listeners of the given event target. Parameters target : Object Event target object. type : String The type of event. listener : Function The listener function that processes the event. count
() Returns a number of event listeners registered for the given event type on the given event target. Returns number : Number of listeners ...
test/httpd - Archive of obsolete content
This module was removed in Firefox 36, please use the addon-httpd npm module instead. An HTTP server for the Mozilla platform, which can be used in unit tests. Usage The most basic usage is: var { startServerAsync } = require("sdk/test/httpd"); var srv = startServerAsync(port, basePath); require("sdk/system/unload").when(function cleanup
() { srv.stop(function
() { // you should continue execution from this point. }) }); This starts a server in background (assuming you're running this code in an application that has an event loop, such as Firefox). The server listens at http://localhost:port/ and serves files from the specified directory. You can serve static content or use SJS scripts, as described in documentation on developer.mozilla.org. You can also use nsHttpServer to start ...
...code in an application that has an event loop, such as Firefox). The server listens at http://localhost:port/ and serves files from the specified directory. You can serve static content or use SJS scripts, as described in documentation on developer.mozilla.org. You can also use nsHttpServer to start the server manually: var { nsHttpServer } = require("sdk/test/httpd"); var srv = new nsHttpServer
(); // further documentation on developer.mozilla.org See HTTP server for unit tests for general information. ...
test/utils - Archive of obsolete content
Helper methods used in the CommonJS Unit Testing suite. Usage Before and After Helper functions before
() and after
() are available for running a function before or after each test in a suite. They're useful when you need to guarantee a particular state before running a test, and to clean up after your test. let { before, after } = require('sdk/test/utils'); let { search } = require('sdk/places/bookmarks'); exports.testCountBookmarks = function (assert, done) { search
().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done
(); }); }; before(exports, function (name, assert) { removeAllBookmarks
(); }); require('sdk/test').run(exports); Both before and after may be asynchronous. To make them asynchronous, pass a third argument done, which...
...on (name, assert) { removeAllBookmarks
(); }); require('sdk/test').run(exports); Both before and after may be asynchronous. To make them asynchronous, pass a third argument done, which is a function to call when you have finished: let { before, after } = require('sdk/test/utils'); let { search } = require('sdk/places/bookmarks'); exports.testCountBookmarks = function (assert, done) { search
().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done
(); }); }; before(exports, function (name, assert, done) { removeAllBookmarksAsync(function
() { done
(); }); }); require('sdk/test').run(exports); Globals Functions before(exports, beforeFn) Runs beforeFn before each test in the file. May be asynchronous if beforeFn accepts a third argum...
Listen for Page Load - Archive of obsolete content
tab's built-in ready event and just logs the URL of each tab as the user loads it: require("sdk/tabs").on("ready", logURL); function logURL(tab) { console.log(tab.url); } You will find this console output in the Browser Console, not the Web Console. You don't get direct access to any content hosted in the tab. To access tab content you need to attach a script to the tab using tab.attach
(). This add-on attaches a script to all open tabs. The script adds a red border to the tab's document: require("sdk/tabs").on("ready", runScript); function runScript(tab) { tab.attach({ contentScript: "if (document.body) document.body.style.border = '5px solid red';" }); } (This example is only to show the idea: to implement something like this, you should instead use page-mod, and spec...
... ...
Modifying Web Pages Based on URL - Archive of obsolete content
h1>Page matches ruleset</h1>");' }); Note, though, that you can't load a script from a web site. The script must be loaded from data. Communicating With the Content Script Your add-on script and content scripts can't directly access each other's variables or call each other's functions, but they can send each other messages. To send a message from one side to the other, sender calls port.emit
() and receiver listens using port.on
(). In the content script, port is a property of the global self object. In the add-on script, you need to listen for the onAttach event to get passed a worker object that contains port. Let's rewrite the example above to pass a message from the add-on to the content script. The message will contain the new content to insert into the document. The content ...
... Injecting CSS Note that the feature described in this section is experimental at the moment. We'll most likely continue to support the feature, but API details may change. Rather than injecting JavaScript into a page, you can inject CSS by setting the page-mod's contentStyle option. var pageMod = require("sdk/page-mod").PageMod({ include: "*", contentStyle: "body {" + ...
Open a Web Page - Archive of obsolete content
To follow this tutorial you'll need to have learned the basics of jpm. To open a new web page, you can use the tabs module: var tabs = require("sdk/tabs"); tabs.open("http://www.example.com"); This function is asynchronous, so you don't immediately get back a tab object which you can examine. To do this, pass a callback function into open
(). The callback is assigned to the onReady property, and will be passed the tab as an argument: var tabs = require("sdk/tabs"); tabs.open({ url: "http://www.example.com", onReady: function onReady(tab) { console.log(tab.title); } }); Even then, you don't get direct access to any content hosted in the tab. To access tab content you need to attach a script to the tab using tab.attach
(). This add-on loads a page, then attaches a script to th...
... ...
Using third-party modules (jpm) - Archive of obsolete content
m-hosted third-party SDK modules with jpm. We'll use the menuitem package to add a new menu item to Firefox. Summary First, while in the root of your add-on, install the package that contains the modules you want to use: npm install menuitem --save Now you'll see a new directory in your add-on root called "node_modules" that contains a directory "menuitem". ...
...nuitem index.js node_modules menuitem package.json test We're interested in using the "menuitem" module, which is at "addon-pathfinder/lib/ui/menuitem". Open "index.js" and replace it with this: var menuitems = require("menuitem"); var menuitem = menuitems.Menuitem({ id: "clickme", menuid: "menu_ToolsPopup", label: "Click Me!", onCommand: function
() { console.log("clicked"); }, insertbefore: "menu_pageInfo" }); Now run the add-on: jpm run -b nightly You should see a new menu item in the Tools menu labeled "Click Me!". Click the button, and the message "clicked" is logged. Note: In more recent versions of Firefox, the Menu Bar may not be visible by default. To show the Menu Bar, click on the Open Menu icon and select "Customize". ...
Drag & Drop - Archive of obsolete content
Over, true); elem.addEventListener("dragdrop", _dragDrop, true); Here, elem could be a window or an XUL element. ...
...vorSupported("text/x-moz-url"); if (!supported) supported = dragSession.isDataFlavorSupported("application/x-moz-file"); if (supported) dragSession.canDrop = true; } function _dragDrop(aEvent) { var dragService = Components.classes["@mozilla.org/widget/dragservice;1"].getService(Components.interfaces.nsIDragService); var dragSession = dragService.getCurrentSession
(); var _ios = Components.classes['@mozilla.org/network/io-service;1'].getService(Components.interfaces.nsIIOService); var uris = new Array
(); // If sourceNode is not null, then the drop was from inside the application if (dragSession.sourceNode) return; // Setup a transfer item to retrieve the file data var trans = Components.classes["@mozilla.org/widget/transferabl...
JavaScript Debugger Service - Archive of obsolete content
of JavaScript while it was being executed in the browser. However, JSD has been removed in favor of the Debugger API. See the tracking bug bug 800200 for more details. Snippets Acquiring the service We acquire the service by calling the XPCOM object. var jsd = Components.classes["@mozilla.org/js/jsd/debugger-service;1"] .getService(Components.interfaces.jsdIDebuggerService); jsd.on
(); // enables the service till firefox 3.6, for 4.x use asyncOn if (jsd.isOn) jsd.off
(); // disables the service Hooks JSD operates using the events hook mechanism. Next, we add code to the various hooks. jsd.scriptHook = { onScriptCreated: function(script) { // your function here }, onScriptDestroyed: function(script) { // your function here } }; jsd.errorHook = { onError: function(m...
...lter function that acts as a jsdIFilter factory. function createFilter(pattern, pass) { var jsdIFilter = Components.interfaces.jsdIFilter; var filter = { globalObject: null, flags: pass ? (jsdIFilter.FLAG_ENABLED | jsdIFilter.FLAG_PASS) : jsdIFilter.FLAG_ENABLED, urlPattern: pattern, startLine: 0, endLine: 0 }; return filter; }, We then add the filters we want. ...
LookupNamespaceURI - Archive of obsolete content
ing Firefox) support Node.lookupNamespaceURI. This function is not necessary for Gecko-based browsers (though the function will quickly return the standard value for Mozilla browsers) when used to reflect on static documents. However, due to bug 312019, this method does not work with dynamically assigned namespaces (e.g., those set with Node.prefix). ...
...T_NODE (3), CDATA_SECTION_NODE (4), ENTITY_REFERENCE_NODE (5), // PROCESSING_INSTRUCTION_NODE (7), COMMENT_NODE (8) if (node.parentNode) { // EntityReferences may have to be skipped to get to it return lookupNamespaceURIHelper(node.parentNode, prefix); } return null; // unknown } }; } }
()); ...
Modules - Archive of obsolete content
function importModule (thatObj) { thatObj = thatObj || window; var EXPORTED_SYMBOLS = [ // Put the symbols here ]; // Your code here... ...
...i]);} } or for one-time-only usage of a module: (function (thatObj) { thatObj = thatObj || window; var EXPORTED_SYMBOLS = [ // Put the symbols here ]; // Your code here... // At the end of your code: (assuming neither 'i' nor 'thatObj' is being exported!) for (var i=0; i < EXPORTED_SYMBOLS.length; i++) {thatObj[EXPORTED_SYMBOLS[i]] = eval(EXPORTED_SYMBOLS[i]);} })
(); // Can put an object argument here ...
Running applications - Archive of obsolete content
This page describes how to run other programs from your chrome JavaScript code, using Mozilla XPCOM interfaces. There are two ways to run programs. Using nsIProcess The recommended way is to use the nsIProcess interface because it is crossplatform. Using nsILocalFile.launch
() This method is not implemented on all platforms, especially not on Unix/Linux! See nsILocalFile.launch
() for details and make sure that all your target platforms support this method! This method has the same effect as if you double-clicked the file, so for executable files--it will just run the file without any parameters. For more information on nsIFile/nsILocalFile, see File I/O. var file = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile);...
...t this method! This method has the same effect as if you double-clicked the file, so for executable files--it will just run the file without any parameters. For more information on nsIFile/nsILocalFile, see File I/O. var file = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); file.initWithPath("c:\\myapp.exe"); file.launch
(); References nsIProcess nsILocalFile If you need to launch an executable bundled in your XPI, see Code snippets:File I/O#Getting your extension's folder. Launching an executable process from a web page ...
Default Preferences - Archive of obsolete content
ction A key part of any extension is the default settings that come with it. Mozilla provides a simple way of shipping default settings by allowing default preferences. Remember that preferences are held in two separate trees. One with user supplied prefs, another with default prefs. User supplied prefs are set using the GUI and also by modifying a profile's prefs.js file (which uses the user_pref
() function). Default preferences are set similarly but inside an extension and use the pref
() function. Setting default preferences While most of an extension's directories can be named arbitrarily and mapped using a chrome manifest, default preferences must be in very particular spot: | Extension Root +--|content +--|skin +--|defaults +--|preferences To add preferences simply drop a .js file ...
...le. You may not set variables inside of it, nor may do any kind of program flow control (ifs, loops etc.) nor even calculated values (i.e. 3600 * 24 * 5). Doing so will cause Mozilla to stop processing your preferences file without any notification, warning, error, or exception. Think of it more as an .ini file. Comments are perfectly acceptable. Inside your file you set preferences using the pref
() function: pref("name", "value") example: pref('extensions.defaultPrefs.example.int', 1); pref('extensions.defaultPrefs.example.float', 0.1); pref('extensions.defaultPrefs.example.string', 'fadf'); pref('extensions.defaultPrefs.example.bool', true); Notice that unlike when you're reading preferences, writing default preferences uses the same function no matter the data type of the preference. Y...
Hiding browser chrome - Archive of obsolete content
There are times in which an extension may find it useful to hide browser chrome (that is, toolbars, the location bar, and so forth), in order to reduce clutter when presenting a particular user interface. This is done, for example, by the about:addons page. This can be accomplished by augmenting the behavior of the XULBrowserWindow object's hideChromeForLocation
() method. Note: Don't simply replace the hideChromeForLocation
() method; this will likely hurt the functionality of Firefox itself as well as other extensions. Use the technique demonstrated here. var prevFunc = XULBrowserWindow.hideChromeForLocation; XULBrowserWindow.hideChromeForLocation = function(aLocation) { return (/* your test goes here */) || prevFunc.apply(XULBrowserWindow, [aLocation]); } This works by saving a referenc...
...he functionality of Firefox itself as well as other extensions. Use the technique demonstrated here. var prevFunc = XULBrowserWindow.hideChromeForLocation; XULBrowserWindow.hideChromeForLocation = function(aLocation) { return (/* your test goes here */) || prevFunc.apply(XULBrowserWindow, [aLocation]); } This works by saving a reference to the current implementation of the hideChromeForLocation
() method, then replacing it with a new method that calls through to the previous implementation. By chaining multiple implementations of the method together in this way, everyone that wants to hide chrome can do so when appropriate. ...
Inline options - Archive of obsolete content
owses and picks a file, when it updates the label it will trigger the oninputchanged attribute. So if you would like to do some changes to the XUL on the inline options page you can do so. The this value is the setting XUL element. See MXR for what all this holds: http://mxr.mozilla.org/mozilla-release/source/toolkit/mozapps/extensions/content/setting.xml for example you can fire this.inputChanged
() etc etc. <setting pref="extensions.ThrobberRestored.showTxtOnToolbar" title="Show Text on Toolbar Button" type="bool" oninputchanged="alert('New value is = ' + this.value); this.style.backgroundColor='red';"> If labels on other toolbar buttons are visible (like by using add-on "Classic Theme Restorer") then show label on throbber toolbar button </setting> NOTE In order for the ...
...ic == "addon-options-displayed" && aData == "MY_ADDON@MY_DOMAIN") { var doc = aSubject; var control = doc.getElementById("myaddon-pref-control"); control.value = "test"; } } }; Services.obs.addObserver(observer, "addon-options-displayed", false); // Don't forget to remove your observer when your add-on is shut down. This code should be in bootstrap.js (within the startup
() function) for restartless extensions or in an XPCOM component or a JavaScript code module (not an overlay!) for traditional extensions. Note: Starting in Gecko 13.0, you can also listen for the addon-options-hidden notification, which has the same subject and data as above, to find out when the UI is about to be removed. Use this notification to remove event listeners, or any other references t...
Offering a context menu for form controls - Archive of obsolete content
y id="formcontrolcontextmenu-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://formcontrolcontextmenu/content/overlay.js"/> </overlay> Change the right-click behavior The overlaid code is responsible for adjusting the behavior of right-clicking on form controls. ...
... As a result, all controls in the window will support a context menu when right-clicked, since we've changed the core behavior of context menus to override their default behavior of doing nothing on form controls. ...
Adding Events and Commands - Archive of obsolete content
<< PreviousNext >> Event handlers Just like with HTML, most JavaScript code execution is triggered by event handlers attached to DOM elements. The most commonly used event is the onload event, which is used in overlays and other windows to detect when the window has loaded and then run initialization code: // rest of overlay code goes here. window.addEventListener( "load", function
() { XulSchoolChrome.BrowserOverlay.init
(); }, false); You can do something similar with the onunload event, to do any cleanup you may need. Please read Appendix A for recommendations on how to use the load event to initialize your add-on without having a negative performance impact on Firefox. Another way to attach event handlers, just like HTML, is to place the handler in the XUL code: <overlay id=...
...with the onunload event, to do any cleanup you may need. Please read Appendix A for recommendations on how to use the load event to initialize your add-on without having a negative performance impact on Firefox. Another way to attach event handlers, just like HTML, is to place the handler in the XUL code: <overlay id="xulschoolhello-browser-overlay" onload="XulSchoolChrome.BrowserOverlay.init
();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> We prefer the first method because it keeps a better separation of content and behavior. Also, note that the addEventListener method receives the event name without the "on" prefix, while element attributes do have the prefix. There's a long list of events you can listen to, and which you use depend on the situation. Ele...
Performance best practices in extensions - Archive of obsolete content
that you can Most extensions have a load event listener in the main overlay that runs their startup functions. Do as little as possible here. The browser window is blocked while your add-on's load handler runs, so the more it does, the slower Firefox will appear to the user. If there is anything that can be done even a fraction of a second later, you can use an nsITimer or the window.setTimeout
() method to schedule that work for later. Even a short delay can have a big impact. General Performance Tips Avoid Creating Memory Leaks Memory leaks require the garbage collector and the cycle collector to work harder, which can significantly degrade performance. Zombie compartments are a particular kind of memory leak that you can detect with minimal effort. See the Zombie compartments page...
...M mutation event listeners DOM mutation event listeners are extremely expensive and, once added to a document even briefly, significantly harm its performance. As mutation events are officially deprecated, and there are many alternatives, they should be avoided at all costs. Lazily load services The XPCOMUtils JavaScript module provides two methods for lazily loading things: defineLazyGetter
() defines a function on a specified object that acts as a getter which will be created the first time it's used. See examples. defineLazyServiceGetter
() defines a function on a specified object which acts as a getter for a service. The service isn't obtained until the first time it's used. Look through the source for examples. Many common services are already cached for you in Services.jsm. Use...
chargingchange - Archive of obsolete content
from the navigator.getBattery method. Property Type Description BatteryManager.charging boolean The system's battery charging status. Returns true if the battery is charging, if the state of the system's battery is not determinable, or if no battery is attached to the system. Returns false if the battery is discharging. ...
... status. Returns true if the battery is charging, if the state of the system's battery is not determinable, or if no battery is attached to the system. Returns false if the battery is discharging. Read only. ...
chargingtimechange - Archive of obsolete content
od. Property Type Description BatteryManager.chargingTime double (float) The remaining time in seconds until the system's battery is fully charged. Returns 0 if the battery is fully charged. Returns positive infinity, if the battery is discharging or if the implementation is unable to report the remaining charging time. Read only. ...
...ully charged. Returns 0 if the battery is fully charged. Returns positive infinity, if the battery is discharging or if the implementation is unable to report the remaining charging time. Read only. ...
dischargingtimechange - Archive of obsolete content
BatteryManager.dischargingTime double (float) the remaining time in seconds until the system's battery is completely discharged and the system is about to be suspended. Returns positive infinity if the battery is charging, if the implementation is unable to report the remaining discharging time, or if there is no battery attached to the system. Read only. ...
... Returns positive infinity if the battery is charging, if the implementation is unable to report the remaining discharging time, or if there is no battery attached to the system. Read only. ...
levelchange - Archive of obsolete content
y Type Description BatteryManager.level double (float) The system's battery charging level scaled from 0 to 1.0. Returns 0 if the battery is empty and the system is about to suspend. ...
... if the battery is empty and the system is about to suspend. Returns 1.0 if the battery is full, if the implementation is unable to report the battery's level, or if there is no battery attached to the system. Read only. ...
Creating a Microsummary - Archive of obsolete content
g regular expressions for a microsummary generator for a tutorial on writing them. Making the Generator Available for Download Now that the generator applies to the Spread Firefox home page, the only thing left to do is to make it downloadable. To do so, we need to put it up on the web and then create a JavaScript link on some web page that calls Firefox's window.sidebar.addMicrosummaryGenerator
() method to download and install the generator. For example, if we put the generator file on the web at http://people.mozilla.com/~myk/micro...-generator.xml, and we wanted users to be able to install it from http://people.mozilla.com/~myk/micro...ial/index.html, we might add the following code to the index.html page: <button onclick="window.sidebar.addMicrosummaryGenerator('http://people.mozilla...
... Conclusion You should now have a microsummary generator that displays the current Firefox download count when you install it, bookmark the Spread Firefox home page, and select the microsummary from the Summary drop-down menu in the Add Bookmark dialog. For more information about Microsummaries, see the Microsummaries home page. ...
Embedding FAQ - Archive of obsolete content
rt org.eclipse.swt.SWT; import org.eclipse.swt.browser.MozillaBrowser; import org.eclipse.swt.browser.ProgressEvent; import org.eclipse.swt.browser.ProgressListener; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.mozilla.xpcom.nsIDOMDocument; public class Test { public static void main(String args[]) { Display display = new Display
(); Shell shell = new Shell(display); final MozillaBrowser browser = new MozillaBrowser(shell,WT.BORDER); browser.setUrl("http://www.google.com"); browser.addProgressListener(new ProgressListener
() { public void changed(ProgressEvent event) { } public void complet...
...ser = new MozillaBrowser(shell,WT.BORDER); browser.setUrl("http://www.google.com"); browser.addProgressListener(new ProgressListener
() { public void changed(ProgressEvent event) { } public void completed(ProgressEvent event) { nsIDOMDocument doc = browser.getDocument
(); System.out.println(doc); } }); while (!shell.isDisposed
()) { if (!display.readAndDispatch
()) { display.sleep
(); } } } How to map a Javascript function to a C++ function Define an XPCOM class defining the ...
Helper Apps (and a bit of Save As) - Archive of obsolete content
at a given location if the user decides to do so. nsExternalAppHandler::OnStartRequest Creates a temporary file with a salted name to hold the data. Decides on a suggested filename for the data in case it will be saved. Decides whether the data should be content-decoded (based on some not-so-great heuristics). Decides whether the user should be prompted (based on a preference). Calls Show
() on the nsIHelperAppLauncherDialog, which asynchronously puts up the helper app dialog. nsExternalAppHandler::OnDataAvailable Here we just copy the newly arrived data over into our temporary file. If any read or write errors occur, abort the whole process: Cancel the channel. Pull down the helper app dialog (if any). Remove the temp file. nsExternalAppHandler::OnStopRequest Set a flag ...
...disk", we just move/copy the temporary file over to the chosen location once the download completes. If an error occurs while we do this we delete the temp file and put up an error dialog. Launching a helper application This is delegated to the nsPIExternalAppLauncher (also implemented by the nsExternalHelperAppHandler): Windows: launch either directly via nsIProcess or via the ::ShellExecute
() method depending on where the MIMEInfo came from. Last-ditch check for executable files here. Mac: use the LaunchWithDoc
() method on nsILocalFileMac. Unix: launch directly via nsIProcess. Security considerations Multiple checks for whether a file is executable (on Windows) to keep from launching such files via ::ShellExecute
(). Checks happen in OnStartRequest, in the helper app dialog, and a...
Basics - Archive of obsolete content
Note: This page documents the Jetpack Prototype, which is no longer under active development. Read the experiment report for what we learned from it and the blog post announcing the first SDK release for what we're up to next! Class Console Writes some information to the Error Console. You can find the console in the Extra Menu of Firefox. The namespace for this API is console. Methods info
()This method does stuff. log(stringstring)This method writes a notification message to the console. stringThe message to add to the consolestring console.log("hello world!"); arn
()This method does stuff. error
()This method does stuff. exception
()This method does stuff. logFromCaller
()This method does stuff. Class Notifications The Notification Box appears at the bottom right corner of the browse...
...ss is jetpack.tabs. blah(lengthstringfocusedstringtoStringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengthThe number of open tabsstring focusedthe current tab in your browserstring toStringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onReady
()when the inherited document is fully loaded. onFocus
()changing the focus of a tab. Methods open(urlstring)Opens a new tab in your browser with a defined url. urlURL to be openedstring jetpack.tabs.open("http://www.example.com/"); ...
Enabling Experimental Jetpack Features - Archive of obsolete content
erimental feature into the script. stringMountPathString that enumerates where, starting from the jetpack base, the feature will be mounted. To get a list of mount paths that are available, see the method below. string Here is an example of how to import a feature (the clipboard) from the future. jetpack.future.import("clipboard"); The goal here is to be able to remove the jetpack.future.import
() call when the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration). list
() arrayReturns an array of the set of potential stringMountPath as used in jetpack.future.import
(). This is an example of how to get this array. A quick way of displaying the list is to write it to the console.log. var list = jetpack.fut...
...en the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration). list
() arrayReturns an array of the set of potential stringMountPath as used in jetpack.future.import
(). This is an example of how to get this array. A quick way of displaying the list is to write it to the console.log. var list = jetpack.future.list
();console.log(list); Open the firebug console to view. ...
Enabling - Archive of obsolete content
erimental feature into the script. stringMountPathString that enumerates where, starting from the jetpack base, the feature will be mounted. To get a list of mount paths that are available, see the method below. string Here is an example of how to import a feature (the clipboard) from the future. jetpack.future.import("clipboard"); The goal here is to be able to remove the jetpack.future.import
() call when the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration). list
()Returns an array of the set of potential stringMountPath as used in jetpack.future.import
(). This is an example of how to get this array. A quick way of displaying the list is to write it to the console.log. var list = jetpack.future.li...
...all when the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration). list
()Returns an array of the set of potential stringMountPath as used in jetpack.future.import
(). This is an example of how to get this array. A quick way of displaying the list is to write it to the console.log. var list = jetpack.future.list
(); console.log(list); Open the firebug console to view. ...
Jetpack Snippets - Archive of obsolete content
debug</p> <a href="javascript:console.log('hello!')">test</a> <script><![CDATA[ //firebug lite bookmarklet code: var firebug=document.createElement('script'); firebug.setAttribute('src','http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'); document.body.appendChild(firebug); (function
(){if(window.firebug.version){firebug.init
();}else{setTimeout(arguments.callee);}})
();void(firebug); ]]></script> </body></html>, width: 800, //wide enough to use firebug onSelect: function(slide) { slide.slide(800, true); }}); Calling into a slidebar from the global jetpack scope jetpack.slideBar.append({ onReady: function (slide) { // call out to a...
... onReady: function (slide) { // call out to a global function, passing the slidebar object exInitSlidebar(slide); }, ...});function exInitSlidebar(aSlidebar) { // This variable will now be global slider = aSlidebar;} // then, accessing the slidebar HTMLvar tl = slider.contentDocument.getElementById("thumbList"); // or calling slidebar API methods or accessing propertiesslider.notify
(); ...
Clipboard - Archive of obsolete content
Returns data to Jetpack from the clipboard. If flavor is provided, the data is returned in that format. string Here's an example of how to use the method to get the data on the clipboard. Remember to import clipboard from the future before calling it. ...
..."clipboard");var myContent = "<i>This is some italic text</i>";jetpack.clipboard.set( myContent, "html" ); getCurrentFlavors
()Returns an array of available Jetpack clipboard flavors, for the current system clipboard state. ...
Clipboard Test - Archive of obsolete content
Returns data to Jetpack from the clipboard. If flavor is provided, the data is returned in that format. string Here's an example of how to use the method to get the data on the clipboard. Remember to import clipboard from the future before calling it. ...
..."clipboard");var myContent = "<i>This is some italic text</i>";jetpack.clipboard.set( myContent, "html" ); getCurrentFlavors
()Returns an array of available Jetpack clipboard flavors, for the current system clipboard state. ...
Clipboard - Archive of obsolete content
urns data to Jetpack from the clipboard. If flavor is provided, the data is returned in that format. string Here's an example of how to use the method to get the data on the clipboard. Remember to import clipboard from the future before calling it. ...
...rd"); var myContent = "<i>This is some italic text</i>"; jetpack.clipboard.set( myContent, "html" ); getCurrentFlavors
()Returns an array of available Jetpack clipboard flavors, for the current system clipboard state. ...
Enabling Experimental Jetpack Features - Archive of obsolete content
erimental feature into the script. stringMountPathString that enumerates where, starting from the jetpack base, the feature will be mounted. To get a list of mount paths that are available, see the method below. string Here is an example of how to import a feature (the clipboard) from the future. jetpack.future.import("clipboard"); The goal here is to be able to remove the jetpack.future.import
() call when the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration). list
() arrayReturns an array of the set of potential stringMountPath as used in jetpack.future.import
(). This is an example of how to get this array. A quick way of displaying the list is to write it to the console.log. var list = jetpack.fut...
...en the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration). list
() arrayReturns an array of the set of potential stringMountPath as used in jetpack.future.import
(). This is an example of how to get this array. A quick way of displaying the list is to write it to the console.log. var list = jetpack.future.list
(); console.log(list); Open the firebug console to view. ...
Clipboard - Archive of obsolete content
urns data to Jetpack from the clipboard. If flavor is provided, the data is returned in that format. string Here's an example of how to use the method to get the data on the clipboard. Remember to import clipboard from the future before calling it. ...
...rd"); var myContent = "<i>This is some italic text</i>"; jetpack.clipboard.set( myContent, "html" ); getCurrentFlavors
()Returns an array of available Jetpack clipboard flavors, for the current system clipboard state. ...
Microsummary topics - Archive of obsolete content
For example, the following code snippet installs the microsummary generator from the Creating a Microsummary tutorial: var generatorText = ' \ <?xml version="1.0" encoding="UTF-8"?> \ <generator xmlns="http://www.mozilla.org/microsummaries/0.1" \ name="Firefox Download Count" \ uri="urn:{835daeb3-6760-47fa-...
...ecify an arbitrary identifier using a URN, for example: urn:{835daeb3-6760-47fa-8f4f-8e4fdea1fb16} To guarantee uniqueness, use URNs containing UUIDs generated by the nsUUIDGenerator component. See Generating a UUID in the nsIUUIDGenerator documentation. You may also use another form appropriate to your extension. Note: When web sites install generators via window.sidebar.addMicrosummaryGenerator
(), Firefox sets their uri attribute to urn:source:sourceURL, where sourceURL is the URL from which the generator was downloaded. In the future, Firefox may access source URLs to download updated versions of generators, so unless you are installing generators which are available from URLs, you should not use this form for your programmatically-installed generators. Differentiating between user-initi...
Tamarin Acceptance Test Template - Archive of obsolete content
t may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ var SECTION = "test"; // provide a document reference (ie, Actionscript section) var VERSION = "AS3"; // Version of ECMAScript or ActionScript var TITLE = "test"; // Provide ECMA section title or a description var BUGNUMBER = ""; startTest
(); // leave this alone /** * Calls to AddTestCase here. AddTestCase is a function that is defined * in shell.as and takes three arguments: * - a string representation of what is being tested * - the expected result * - the actual result * * For example, a test might look like this: * * var helloWorld = "Hello World"; * * AddTestCase( * "var helloWorld = 'Hello World'", ...
... this executes the test cases and // displays results. ...
Venkman Internals - Archive of obsolete content
ll set breakpoints, but they will be future breakpoints, which will be "real" breakpoints when/if the file is loaded (note that this may never happen!). Note also that this is just my knowledge of Venkman, which is quite limited. You would be better off asking Silver (James Ross). GijsKruitbosch 05:41, 7 March 2007 (PST) venkman-debugger.js Sets hooks in to the jsdIDebuggerService. initDebugger
(). ScriptManager In initDebugger
() the previous loaded scripts are passed to an onScriptCreated
() method which binds them to a ScriptManager. There is one ScriptManager per url (web page). This method is set into jsdIScriptHook.onScriptCreated venkman-views.js Views are the panels shown within the venkman window. For example, the "Open Windows" view shows the browser's windows. venkman-reco...
... breakpoint object. You can see the prototype for this object at http://lxr.mozilla.org/mozilla/sourc...ebugger.js#914 scriptWrapper.jsdScript is the reference to the jsdIScript object for the function. sourceContext is the 5 lines of source text before the last instance of the word "function" on the line where this function starts. (not in 2006, seems to be computed on the fly in getSourceContext
()). The full text of the file can be found in an array located at scriptWrapper.scriptInstance.sourceText.lines. This array is 0 based, of course. The starting line of the function is scriptWrapper.jsdScript.baseLineNumber (one based). The total length of the function is scriptWrapper.jsdScript.lineExtent. If you want to get at the pretty printed source text, instead of the actual source text, use ...
Writing textual data - Archive of obsolete content
ng name that Mozilla supports var os = Components.classes["@mozilla.org/intl/converter-output-stream;1"] .createInstance(Components.interfaces.nsIConverterOutputStream); // This assumes that fos is the nsIOutputStream you want to write to os.init(fos, charset, 0, 0x0000); os.writeString("Umlaute: \u00FC \u00E4\n"); os.writeString("Hebrew: \u05D0 \u05D1\n"); // etc. os.close
(); You can also write character arrays using the write function, although using writeString is simpler from JavaScript code. The example above passes 0 as the third argument, which disables buffering (Note: the implementation of the converter stream might not support buffering). Passing 0 ensures that data will be immediately written to the underlying stream; however, for better perfomance you s...
...tream // your_string here is the string you want to write. var chunk = converter.ConvertFromUnicode(your_string); os.write(chunk, chunk.length); // Repeat as needed for further strings At the end, you need to call Finish and write its data to the stream. Note that not many character encodings need it, but for those that do calling this is important for proper output. var fin = converter.Finish
(); if (fin.length > 0) os.write(fin, fin.length); os.close
(); Converting a string into a stream Sometimes, it is useful to convert a string into a stream, for example for uploading it using nsIUploadChannel. The example here requires Gecko 1.8 (Firefox 1.5, SeaMonkey 1.0). nsIScriptableUnicodeConverter has a simple method to do that: // First, get and initialize the converter var convert...
Binding Implementations - Archive of obsolete content
cify that it must be possible to access base bindings' methods and properties? For example, given a binding with an implementation ColorPickerGrid that derives from an implementation ColorPicker where the two implementations both specify the setColor method, a caller could invoke ColorPicker's method with the following syntax: ... // myElement is a ColorPickerGrid myElement.ColorPicker.setColor
(); // Calls the ColorPicker method. myElement.setColor
(); // Calls the ColorPickerGrid method. ... In addition to being able to specifically name a base class, the name baseBinding can be used to specify the method or property on the base binding without necessarily knowing what the base class is. This situation can occur when bindings implicitly inherit, e.g., through the use of addBinding. myE...
...method. myElement.setColor
(); // Calls the ColorPickerGrid method. ... In addition to being able to specifically name a base class, the name baseBinding can be used to specify the method or property on the base binding without necessarily knowing what the base class is. This situation can occur when bindings implicitly inherit, e.g., through the use of addBinding. myElement.baseBinding.setColor
(); // Calls the ColorPicker method. ...
Creating XPI Installer Modules - Archive of obsolete content
http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul" width="175" height="375" x="20" y="20" persist="width height x y" orient="vertical" autostretch="always"> <script src="barley.js"/> <image src="barley.gif" /> <box orient="horizontal" autostretch="never"> <button label="barley corn" /> <button label="show aphids" oncommand="bar
();" /> </box> </window> The other files that the window imports are defined in dark blue. Note that the stylesheet processing instruction at the top of the XUL file does not refer to any new skin, but imports communicator.css to make use of that skin's basic widget styles. The JavaScript file barley.js contains a single function, bar
(), defined as follows: function bar
() { alert("aphids");...
...Note also the use of resource attributes specified in the contents.rdf file in the JAR. It is the correspondence of this installation script, the resources themselves, and the contents.rdf file that registers the package and makes it available. Creating...
Using XPInstall to Install Plugins - Archive of obsolete content
pt runs the setup executable, and that "-s" is some // invocation parameter defined by the setup.exe file, perhaps to force // the installer to run silently. We are passing "-s" to the setup file. // By passing 'true' we are telling the Install Script to block // on the execution of the installable, and do it synchronously // Must call performInstall to make it all happen... err = getLastError
(); if (!err) performInstall
(); else cancelInstall(err); Installing Plugin Files To the Current Browser Installing to the current browser is the task that is the most important for the XPI Package to succeed in. Here is a code snippet that accomplishes this: // Name of the files to be installed var PLUGIN_FILE = "NPMyPlugin.dll"; var COMPONENT_FILE = "NPMyPluginScriptablePeer.xpt"; // i...
... secondary location on the user's desktop. In particular, like many OCX files (ActiveX controls) it installs to a special directory within C:\WINNT\System32\, called C:\WINNT\System32\MyPlugin. XPInstall is able to determine what directory this is by the getFolder API call. We have written our own JavaScript function to contain all the secondary installation code -- function createSecondaryInstall
() And finally, it writes the required registry keys to Windows. This is done via the created function, called function registerPLID
(). Certainly, this script is Windows-centric, but it is easy to port it to any other platform. Easier, perhaps, since the lengthy Win32 Registry manipulation need not occur on Linux or Mac OSX. The getFolder API provides you with enough "syntactic sugar" to determine...
Adding Event Handlers - Archive of obsolete content
d Cancel buttons in the find files dialog. Pressing the Find button should start the search. Because we aren't going to implement this part yet, we'll leave it out for now. However, pressing the Cancel button should close the window. The code below shows how to do this. While we're at it, let's add the same code to the Close menu item. <menuitem label="Close" accesskey="c" oncommand="window.close
();"/> ... <button id="cancel-button" label="Cancel" oncommand="window.close
();"/> Two handlers have been added here. The oncommand attribute was added to the Close menu item. By using this handler, the user will be able to close the window by clicking the menu item with the mouse or by selecting it with the keyboard. The oncommand handler was also added to the Cancel button. DOM Event Lis...
...llows you to attach an event listener dynamically and listen for events during the capturing phase. The syntax is as follows: Example 3 : Source View <button id="okbutton" label="OK"/> <script> function buttonPressed(event){ alert('Button was pressed!'); } var button = document.getElementById("okbutton"); button.addEventListener('command', buttonPressed, true); </script> The getElementById
() function returns the element with a given id, in this case the button. The addEventListener
() function is called to add a new capturing event listener. The first argument is the name of the event to listen to. The second argument is the event listener function which will be called when the event occurs. Finally, the last argument should be true for capturing listeners. You can also listen during ...
Adding Properties to XBL-defined Elements - Archive of obsolete content
on which generates and stores a random number. You can retrieve this same number multiple times by getting the number property from the button. Most of the work here is done in the oncommand handlers. Later, we'll find out how to move this to XBL. XUL: <box id="random-box" class="randomizer"/> <button label="Generate" oncommand="document.getElementById('random-box').number=Math.random
();"/> <button label="Show" oncommand="alert(document.getElementById('random-box').number)"/> XBL: <binding id="randomizer"> <implementation> <field name="number"/> </implementation> </binding> A number field has been defined in the binding, which stores the random number. The two extra buttons set and get the value of this field. The syntax is very similar to getting and setti...
...r example: <field name="number"> 25 </field> This will assign the value 25 as the default value of the number field. Actually, you can instead place a script inside the field tag that evaluates to the default value. That might be necessary if the value needs to be computed. For example, the following field is given a default value equal to the current time: <field name="currentTime"> new Date
().getTime
(); </field> Properties Sometimes you will want to validate the data that is assigned to a property. Or, you may want the value to be calculated dynamically as it's asked for. For example, if you want a property that holds the current time, you would want to have its value generated as needed. In these cases, you need to use a property tag instead of a field tag. Its syntax is similar but...
Box Objects - Archive of obsolete content
the size of the element to 0. This means that while both hidden and collapsed elements have 0 width and height, hidden elements have a x and y position of 0, while collapsed elements will retain their position in the window. To retrive or modify the hidden or collapsed state use the corresponding properties as in the following example. ...
...You will then have to unhide and uncollapse the label for it to appear again. XUL Element Ordering The box object may also be used to determine the display order of elements, which may not be the same as the order in the source. Recall that DOM properties such as childNodes...
Commands - Archive of obsolete content
g items from the list. You'll notice that the Delete command on the browser's Edit menu is enabled and that selecting it will delete a row. (See Discussion about opening this example). The example below isn't completely polished. Really, we should ensure that the selection and focus is adjusted appropriately after a deletion. ...
... selecting it will delete a row. (See Discussion about opening this example). The example below isn't completely polished. Really, we should ensure that the selection and focus is adjusted appropriately after a deletion. ...
Features of a Window - Archive of obsolete content
<< PreviousNext >> We've already seen some features of windows. We'll look at some more in this section. Creating Another Window You can create a second window for your application in the same manner as you would create the first one. Just create a second XUL file with the window code in it. As in HTML, you can use the Window interface's open
() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. If the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">Window.open
() function to open the second window. This function will return a reference to the newly opened window. You can use this reference to call functions of the other window. The open function takes three a...
...ative to the window that opened it. If the window that opened the new window is moved, the new window is moved relative to it. dialog The window is a dialog box, which may appear differently. modal The dialog is modal. The window that opened the modal window can't be interacted with until the modal window is closed. resizable The user can resize the window. See also Window interface's open
() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. If the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">Window.open
() Next, we'll look at how to open secondary dialogs. << PreviousNext >> ...
More Event Handlers - Archive of obsolete content
r receive notification about the events. To manually stop event propagation, call the event object's stopPropagation method, as in the following example. Example 2 : Source View <hbox id="outerbox"> <button id="okbutton" label="OK"/> </hbox> <script> function buttonPressed(event){ alert('Button was pressed!'); } function boxPressed(event){ alert('Box was pressed!'); event.stopPropagation
(); } var button = document.getElementById("okbutton"); button.addEventListener('command',buttonPressed,true); var outerbox = document.getElementById("outerbox"); outerbox.addEventListener('command',boxPressed,true); </script> Here, an event listener has been added to the button and another event listener has been added to the box. The stopPropagation method has been called in the box's listener,...
...e 'popupshowing' event is sent to a popup just before it is displayed. The default action is to display the popup. If the default action is prevented, the popup will not be displayed. The default action can be prevented with the event object's preventDefault method, as in the example below. Example 3 : Source View <button label="Types" type="menu"> <menupopup onpopupshowing="event.preventDefault
();"> <menuitem label="Glass"/> <menuitem label="Plastic"/> </menupopup> </button> Alternatively, for attribute event listeners, you can just return false from the code. Note that preventing the default action is not the same as stopping event propagation with the stopPropagation method. Even if the default action has been prevented, the event will still continue to propagate. Similarly, ...
Property Files - Archive of obsolete content
has a number of properties. The first is getString which can be used in a script to read a string from the bundle. var strbundle = document.getElementById("strings"); var nofilesfound=strbundle.getString("notFoundAlert"); alert(nofilesfound); This example first gets a reference to the bundle using its id Then, it looks up the string 'notFoundAlert' in the property file. The function getString
() returns the value of the string or null if the string does not exist. Finally, the string is displayed in an alert box. Text Formatting The next method is getFormattedString
(). This method also gets a string with the given key name from the bundle. In addition, each occurrence of formatting code (e.g. %S) is replaced by each successive element in the supplied array. var dir = "/usr/local/docume...
...(result); This example will display following message in an alert box. 10 files found in the /usr/local/document directory. You will notice the formatting codes %1$S and %2$S is used, and replaced different order in the array. Formatting code %n$S is specify the position of corresponding parameter directly. Although the word order is not the same in all the languages, by using getFormattedString
() the specification of the order can be put out the property files. In case you need to format a string that already contains the percentage character in it (to get something like "50% Off" returned), escape the percentage character with another percentage character, like this: my.percentage.string = %S%% Off Not escaping the percentage character will generate an incorrect string that strips the s...
Updating Commands - Archive of obsolete content
e contents of the clipboard changes. The following example shows the command updaters used in the Mozilla browser to update the edit menu commands. The functions used can be found in the 'chrome://communicator/content/utilityOverlay.js' script. ...
...s used can be found in the 'chrome://communicator/content/utilityOverlay.js' script. <commandset id="globalEditMenuItems" commandupdater="true" events="focus" oncommandupdate="goUpdateGlobalEditMenuItems
()"/> <commandset id="selectEditMenuItems" commandupdater="true" events="select" oncommandupdate="goUpdateSelectEditMenuItems
()"/> <commandset id="undoEditMenuItems" commandupdater="true" events="undo" oncommandupdate="goUpdateUndoEditMenuItems
()"/> <commandset id="clipboardEditMenuItems" commandupdater="true" events="clipboard" oncommandupdate="goUpdatePasteMenuItems
()"/> Next, we'll find out how to use observers. << PreviousNext >> ...
Using spell checking in XUL - Archive of obsolete content
es how to use the mozISpellCheckingEngine component to add spell checking capabilities to your Firefox extension. See Controlling spell checking in HTML forms for details on adding spell check support to HTML forms for your website. Checking the spelling of a word To check the spelling of a word, you must first create an interface to the mozISpellCheckingEngine component and then call the check
() method on the string you wish to test. This method returns true if the word is correctly spelled, or false if it's not. You may also want to check to see if the word is in the user's personal dictionary, since sometimes a word might be correctly spelled but in the dictionary. // Different versions of Firefox have different contract IDs var spellclass = "@mozilla.org/spellchecker/myspell;1"; if ...
... var suggestions = {}; gSpellCheckEngine.suggest("kat", suggestions, {}); if (suggestions.value) { // suggestions.value is a JavaScript Array of strings // there were suggestions.value.length suggestions found } ...
action - Archive of obsolete content
nts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
assign - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
bbox - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
binding - Archive of obsolete content
ents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
bindings - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
box - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
broadcaster - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
broadcasterset - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
column - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
columns - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
command - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
commandset - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
conditions - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
deck - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
dialogheader - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
dropmarker - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
grid - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
grippy - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
groupbox - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
hbox - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
image - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
key - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
keyset - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
listcell - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
listcol - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
listcols - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
listhead - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
listheader - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
member - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
menubar - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
observes - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
page - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
param - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
popupset - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
progressmeter - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
promptBox - Archive of obsolete content
dal prompts (or alerts) on a given tab. It's returned by the tabbrowser method getTabModalPromptBox method. A tab may have multiple prompts on it; the tabmodalPromptShowing attribute on the tabbrowser will tell you how many prompts a given tab has. Note: This is largely an implementation detail; if you're developing an add-on, you shouldn't need to tinker with this. You should use the window.alert
() method or the nsIPrompt interface instead. See Using tab-modal prompts for details. Method overview nsIDOMElement appendPrompt(args, onCloseCallback); void removePrompt(nsIDOMElement aPrompt); NodeList listPrompts(nsIDOMElement aPrompt); Methods appendPrompt
() Creates a new prompt, adding it to the tab. nsIDOMElement appendPrompt( args, onCloseCallback ); Parameters args Argument...
...(nsIDOMElement aPrompt); NodeList listPrompts(nsIDOMElement aPrompt); Methods appendPrompt
() Creates a new prompt, adding it to the tab. nsIDOMElement appendPrompt( args, onCloseCallback ); Parameters args Arguments for the prompt. onCloseCallback The callback routine to be called when the prompt is closed. Return value An nsIDOMElement object representing the new prompt. removePrompt
() Removes an existing prompt. void removePrompt( nsIDOMElement aPrompt ); Parameters aPrompt The prompt to dispose of. listPrompts
() Returns a list of all the prompts on the tabbrowser. NodeList listPrompts( nsIDOMElement aPrompt ); Parameters aPrompt This parameter isn't used; I don't know why it's even there. Return value A NodeList containing all of the prompt elements on the tabbrows...
query - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
queryset - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
resizer - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
row - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
rows - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
rule - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
scrollbar - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
scrollcorner - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
separator - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
spacer - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
spinbuttons - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
splitter - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
stack - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
statusbar - Archive of obsolete content
ents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
<statusbarpanel> - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
stringbundleset - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
tabpanel - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
template - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
textnode - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
toolbargrippy - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
toolbaritem - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
toolbarseparator - Archive of obsolete content
ents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
toolbarset - Archive of obsolete content
ents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
toolbarspacer - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
toolbarspring - Archive of obsolete content
ents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
treechildren - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
treecol - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
treecols - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
treeitem - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
treerow - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
treeseparator - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
triple - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
vbox - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
where - Archive of obsolete content
ts, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
wizardpage - Archive of obsolete content
, , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods addEventListener
(), appendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttribut...
...ppendChild
(), blur, click, cloneNode
(), compareDocumentPosition, dispatchEvent
(), doCommand, focus, getAttribute
(), getAttributeNode
(), getAttributeNodeNS
(), getAttributeNS
(), getBoundingClientRect
(), getClientRects
(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName
(), getElementsByTagName
(), getElementsByTagNameNS
(), getFeature, getUserData, hasAttribute
(), hasAttributeNS
(), hasAttributes
(), hasChildNodes
(), insertBefore
(), isDefaultNamespace
(), isEqualNode, isSameNode, isSupported
(), lookupNamespaceURI, lookupPrefix, normalize
(), querySelector
(), querySelectorAll
(), removeAttribute
(), removeAttributeNode
(), removeAttributeNS
(), removeChild
(), removeEventListener
(), replaceChild
(), setAttribute
(), setAttributeNode
(), setAttributeNodeNS
(), setAttributeNS
(), setUserDa...
CommandLine - Archive of obsolete content
r;1"] .getService(nsICategoryManager); catMan.deleteCategoryEntry("command-line-handler", CLD_CATEGORY); }, canUnload : function (aCompMgr) { return true; } }; function NSGetModule(aCompMgr, aFileSpec) { return appHandlerModule; } Create an observer that will get notified when arguments change: chrome/content/cmdline.js function CommandLineObserver
() { this.register
(); } CommandLineObserver.prototype = { observe: function(aSubject, aTopic, aData) { var cmdLine = aSubject.QueryInterface(Components.interfaces.nsICommandLine); var test = cmdLine.handleFlagWithParam("test", false); alert("test = " + test); }, register: function
() { var observerService = Components.classes["@mozilla.org/observer-service;1"] ...
...ine); var test = cmdLine.handleFlagWithParam("test", false); alert("test = " + test); }, register: function
() { var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); observerService.addObserver(this, "commandline-args-changed", false); }, unregister: function
() { var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); observerService.removeObserver(this, "commandline-args-changed"); } } var observer = new CommandLineObserver
(); // Because we haven't yet registered a CommandLineObserver when the application is // launched the first ...
MacFAQ - Archive of obsolete content
pplication/javascript" src="chrome://global/content/nsUserSettings.js" /> <script><![CDATA[ function debug(aLogString) { var mConsoleService = Components.classes["@mozilla.org/consoleservice;1"] .getService(Components.interfaces.nsIConsoleService) mConsoleService.logStringMessage("myXUL: " + aLogString + "\n"); } function checkOtherWindows
() { var singletonWindowType = nsPreferences.copyUnicharPref("toolkit.singletonWindowType"); var windowMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = windowMediator.getMostRecentWindow(singletonWindowType); if (win) { window.close
(); win.foc...
... var singletonWindowType = nsPreferences.copyUnicharPref("toolkit.singletonWindowType"); var windowMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = windowMediator.getMostRecentWindow(singletonWindowType); if (win) { window.close
(); win.focus
(); } } if (window.arguments && window.arguments[0]){ try { var cmdLine = window.arguments[0] .QueryInterface(Components.interfaces.nsICommandLine); for (var i = 0; i < cmdLine.length; ++i) { debug(cmdLine.getArgument(i)) } } catch(ex) { debug(window.arguments[0]) // Do something with window.argume...
Using SOAP in XULRunner 1.9 - Archive of obsolete content
DL. Though jQuery is listed as a dependency, it can be worked around easily. ...
....ContentType + "; charset=\"" + SOAPClient.CharSet + "\"", < beforeSend: function(req) { < req.setRequestHeader("Method", "POST"); < req.setRequestHeader("Content-Length", SOAPClient.ContentLength); < req.setRequestHeader("SOAPServer", SOAPClient.SOAPServer); < req.setRequestHeader("SOAPAction", soapReq.Action); < } < }); --- > var xhr = new XMLHttpRequest
(); > xhr.mozBackgroundRequest = true; > xhr.open('POST', SOAPClient.Proxy, true); > xhr.onreadystatechange = function
() { > if (4 != xhr.readyState) { return; } > getResponse(xhr); > }; > var headers = { > 'Method': 'POST', > 'Content-Type': SOAPClient.ContentType + '; charset="' + > SOAPClient.CharSet + '"', > 'Content-Length': SOAPClient.ContentLength, > ...
2006-12-01 - Archive of obsolete content
This implementation was removed in 2002 to fight against popups. XML in Firefox is a Major Problem A major debate surrounding the use of xml for customizing RSS feeds. ...
...the DDE Shell Integration. How do allow an internal web site to have UniversalBrowserWrite? A question regarding having an internal website use UniversalBrowserWrite on a local intranet. Developping microsummary generator Questions and discussion surrounding microsummaries in FF 2.0. Applying extensions Question regarding the proper application of FF extensions. Finding out how blur
() works... Question regarding how to access the functionality that arises when window.blur
() is called. FF2 not responding to click on link Concerns regarding FF 2.0 not responding to button or link clicks until the button or link is clicked a second time. Dual Screen browsing Discussion regarding browsing across dual screens and simplifying the process. Suggestion for Status Bar Sugge...
NPN_Invoke - Archive of obsolete content
the method. argCount The number of arguments in the args array. result A pointer to an NPVariant to receive the result returned by the method. Returns true if the method was successfully invoked, otherwise false. If the method was invoked successfully, any return value is stored in the NPVariant specified by result. ...
...rn value is stored in the NPVariant specified by result. When the caller no longer needs the result, it must call NPN_ReleaseVariantValue
() to release it. Description The method arguments are passed as an array of NPVariants, and the number of arguments is passed in. The result of the method invocation is returned through an NPVariant result parameter. If the method invocation succeeds, NPN_Invoke
() returns true, else false. Note: Early on in the development of the scriptability API this method used to be called NPN_Call
() but was renamed for consistency. ...
NPN_PluginThreadAsyncCall - Archive of obsolete content
function pointer on the "plug-in thread", passing in the specified user data pointer when it is called. The "plug-in thread" is the thread hosting the plug-in, which may be either the browser's main thread or the plug-in process if the plug-in is being executed out-of-process. It is the application's responsibility to perform any synchronization between the thread calling NPN_PluginThreadAsyncCall
() and the thread on which the call is eventually executed. In particular, the user must ensure that the function pointer remains callable and the user data is not deallocated until the browser executes the call. There are inherent race conditions between calling this function and termination of the plug-in instance. The browser might not execute calls successfully registered with this API call duri...
...n pointer remains callable and the user data is not deallocated until the browser executes the call. There are inherent race conditions between calling this function and termination of the plug-in instance. The browser might not execute calls successfully registered with this API call during plug-in termination. Plug-ins should perform appropriate synchronization with the code in their NPP_Destroy
() routine to ensure correct execution and avoid memory leaks. Calling NPN_PluginThreadAsyncCall
() on the "browser main thread" or the "plug-in thread" is legal; the call to NPN_PluginThreadAsyncCall
() returns immediately. After control returns to the browser, it is free to call the function with its argument from this thread. See Also NPP Out-of-process plugins ...
NPN_ReleaseVariantValue - Archive of obsolete content
<< Gecko Plugin API Reference << Scripting plugins Summary NPN_ReleaseVariantValue
() releases the value in the given variant. Syntax #include <npruntime.h> void NPN_ReleaseVariantValue(NPVariant *variant); Parameters The function has the following parameters: <tt>variant</tt> The variant whose value is to be released. Returns Nothing. Description NPN_ReleaseVariantValue
() releases the value in the given variant. This must always be called on result variants and such in this API, i.e. any NPVariant whose value comes from a call that passes back an NPVariant must be released using this function. ...
... Returns Nothing. Description NPN_ReleaseVariantValue
() releases the value in the given variant. This must always be called on result variants and such in this API, i.e. any NPVariant whose value comes from a call that passes back an NPVariant must be released using this function. Access to the value in an NPVariant that has been released will result in undefined behavior. NPN_ReleaseVariantValue
() will call NPN_ReleaseObject
() on NPVariants of type NPVARIANTTYPE_OBJECT, and NPN_MemFree
() on NPVariants of type NPVARIANTTYPE_STRING. ...
NPN_ReloadPlugins - Archive of obsolete content
<< Gecko Plugin API Reference << Browser Side Plug-in API Summary Reloads all of the installed plugins. Syntax #include <npapi.h> void NPN_ReloadPlugins(NPBool reloadPages);code Parameters The function has the following parameter: reloadPages Whether to reload pages. If true, all pages are reloaded once the plugins are reloaded; otherwise, they aren't. Description NPN_ReloadPlugins
() reads the Plugins directory for the current platform and reinstalls all of the plug-ins it finds there. Normally, if you add or remove any plug-ins, the browser does not see them until you restart Gecko. NPN_ReloadPlugins
() lets you install a new plug-in and load it, or to remove a plug-in, without having to restart the browser. You could use this function as part of the plug-in's installation pr...
...for the current platform and reinstalls all of the plug-ins it finds there. Normally, if you add or remove any plug-ins, the browser does not see them until you restart Gecko. ...
NPN_Status - Archive of obsolete content
rs: instance Pointer to the current plug-in instance. message Pointer the buffer that contains the status message string to display. Description You can use this function to make your plug-in display status information in the browser window, in the same place the browser does. ...
...ect that acts as a link when clicked, you can call NPN_Status
() to display a description or URL when the user moves the cursor over it. The browser always displays the last status line message it receives, regardless of the message source. Your message is always displayed, but you have no control over how long it stays in the status line before another message replaces it. ...
NPN_Version - Archive of obsolete content
f 4 and a point release number of 3. This function gets the values from the plug-in rather than from the browser. A plug-in can use this function to check that the version of the plug-in API it is using is compatible with the version in use by the browser. This could be part of the initialization process. For more information and an example, see Getting the Current Version. You can use NPN_Version
() to inquire on version constants (NPVERS constants), which represent particular browser features. Once the plug-in obtains a version number, it can inquire on a version constant to find out if the feature it represents exists in this version. For example, the plug-in could inquire on the constant NPVERS_HAS_WINDOWLESS to see if it is running in a browser that supports windowless functionality. For...
...ormation and an example, see Finding Out if a Feature Exists. For a listing of version constants defined in the plug-in API, see Version Feature Constants. Note: Platform-specific code in the plug-in API files npwin.cpp, npmac.cpp, or npunix.c checks version numbers automatically. A plug-in whose major version is less than the major version of the browser is not loaded. See also NPN_UserAgent
() NP_Initialize
() ...
NPN_Write - Archive of obsolete content
integer representing the number of bytes written (consumed by the browser). This number depends on the size of the browser's memory buffers, the number of active streams, and other factors. If unsuccessful, the plug-in returns a negative integer. This indicates that the browser encountered an error while processing the data, so the plug-in should terminate the stream by calling NPN_DestroyStream
(). Description NPN_Write
() delivers a buffer from the stream to the instance. A plug-in can call this function multiple times after creating a stream with NPN_NewStream
(). The browser makes a copy of the buffer if necessary, so the plug-in can free the buffer as the method returns, if desired. See "Example of Sending a Stream" for an example that includes NPN_Write
(). Example This example pushes a...
... myData = "<HTML><B>This is a message from my plug-in!</B></HTML>"; int32 myLength = strlen(myData) + 1; /* Create the stream. */ err = NPN_NewStream(instance, "text/html", "_blank", &stream) /* Push data into the stream. */ err = NPN_Write(instance, stream, myLength, myData); /* Delete the stream. */ err = NPN_DestroyStream(instance, stream, NPRES_DONE); See also NPP_NewStream
() NPP_DestroyStream
() NPP_Read
() NPStream NPP ...
NPSetWindowCallbackStruct - Archive of obsolete content
map Standard X Toolkit attribute. Colormap for the plug-in window or drawable. depth Standard X Toolkit attribute. Depth of the plug-in window or drawable. Description Callback structures are used to pass platform-specific information. The NPSetWindowCallbackStruct object, allocated by the browser, contains information required for the ws_info field of an NPWindow. The NPP_SetWindow
() function passes a pointer to this structure to the plug-in. The structure is valid for the lifetime of the NPWindow, that is, until NPP_SetWindow
() is called again or the instance is destroyed. The type field of this structure always contains NP_SetWindow. The remaining fields are Standard X Toolkit attributes of the top-level shell window in the browser window hierarchy. See also NPP_SetWindow...
... function passes a pointer to this structure to the plug-in. The structure is valid for the lifetime of the NPWindow, that is, until NPP_SetWindow
() is called again or the instance is destroyed. The type field of this structure always contains NP_SetWindow. ...
SAX - Archive of obsolete content
Handler Receive notification of errors in the input stream. nsISAXLexicalHandler SAX2 extension handler for lexical events (e.g. comment and CDATA nodes, DTD declarations, and entities). ...
... nsISAXLexicalHandler SAX2 extension handler for lexical events (e.g. comment and CDATA nodes, DTD declarations, and entities). ...
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
on after the call to Debug.msTraceAsyncOperationCompleted. Note: Some debugging tools do not display the information sent to the debugger. asyncOperationId must correspond to the operation name previously returned from Debug.msTraceAsyncOperationStarting. Example The following code provides an example of tracing an asynchronous call for a Windows 8.x Store app. function asyncWrapperFunction
() { var opID = Debug.msTraceAsyncOperationStarting('async trace'); doSomethingAsync
().then(function (result) { Debug.msTraceAsyncOperationCompleted(opID, Debug.MS_ASYNC_OP_STATUS_SUCCESS); Debug.msTraceAsyncCallbackStarting(opID); // Process result of async operation. }, function (error) { Debug.msTraceAsyncOperationCompleted(opID, Debug.MS_ASYNC_OP_STATU...
...result) { Debug.msTraceAsyncOperationCompleted(opID, Debug.MS_ASYNC_OP_STATUS_SUCCESS); Debug.msTraceAsyncCallbackStarting(opID); // Process result of async operation. }, function (error) { Debug.msTraceAsyncOperationCompleted(opID, Debug.MS_ASYNC_OP_STATUS_ERROR); Debug.msTraceAsyncCallbackStarting(opID); }); Debug.msTraceAsyncCallbackCompleted
(); } function doSomethingAsync
() { return WinJS.Promise.as(true); } asyncWrapperFunction
(); Requirements Supported in the Internet Explorer 11 standards document mode. Also supported in Store apps (Windows 8.1 and Windows Phone 8.1). Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet ...
ScriptEngineBuildVersion - Archive of obsolete content
Non-standard. Do not use! ...
...the scripting engine in use. Syntax ScriptEngineBuildVersion
() Remarks The return value corresponds directly to the version information contained in the dynamic-link library (DLL) for the scripting language in use. Example The following example illustrates the use of the ScriptEngineBuildVersion function: if(window.ScriptEngineBuildVersion) { console.log(window.ScriptEngineBuildVersion
()); } // Output: <current build version> Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). ScriptEngine Function ScriptEngineMaj...
ScriptEngineMajorVersion - Archive of obsolete content
Non-standard. Do not use! ...
...n number of the scripting engine in use. Syntax ScriptEngineMajorVersion
() Remarks The return value corresponds directly to the version information contained in the dynamic-link library (DLL) for the scripting language in use. Example The following example illustrates the use of the ScriptEngineMajorVersion function: if (window.ScriptEngineMajorVersion) { console.log(window.ScriptEngine
()); } Output: <current major version> Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). ...
ScriptEngineMinorVersion - Archive of obsolete content
Non-standard. Do not use! ...
...he scripting engine in use. Syntax ScriptEngineMinorVersion
() Remarks The return value corresponds directly to the version information contained in the dynamic-link library (DLL) for the scripting language in use. Example The following example illustrates the use of the ScriptEngineMinorVersion function. if (window.ScriptEngineMinorVersion) { console.log(window.ScriptEngineMinorVersion
()); } //Output: <current minor version> Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). ...
VBArray.dimensions - Archive of obsolete content
de to create a Visual Basic safe array. The second part is JavaScript code that determines the number of dimensions in the safe array and the upper bound of each dimension. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JavaScript code that goes in the <BODY> section to run the other two parts. ...
...d> <script type="text/vbscript"> <!-- Function CreateVBArray
() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For j = 0 To 2 a(j, i) = k k = k + 1 Next Next CreateVBArray = a End Function --> </script> <script type="text/javascript"> <!-- function VBArrayTest(vba) { var i; var a = new VBArray(vba); var s = ""; for (i = 1; i <= a.dimensions
(); i++) { s += "The upper bound of dimension "; s += i + " is "; s += a.ubound(i); s += ".<br />"; } return(s); } --> </script> </head> <body> <script type="text/javascript"> document.write(VBArrayTest(CreateVBArray
())); </script> </body> Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standard...
VBArray.getItem - Archive of obsolete content
VBScript code to create a Visual Basic safe array. The second part is JavaScript code that iterates the Visual Basic safe array and prints out the contents of each element. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JavaScript code that goes in the <BODY> section to run the other two parts. ...
...Not supported in Windows 8.x Store apps. See Version Information. Applies To: VBArray Object ...
VBArray.lbound - Archive of obsolete content
mensions in the safe array and the lower bound of each dimension. Since the safe array is created in VBScript rather than Visual Basic, the lower bound will always be zero. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JavaScript code that goes in the <BODY> section to run the other two parts. ...
...ad> <script type="text/vbscript"> <!-- Function CreateVBArray
() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For j = 0 To 2 a(j, i) = k k = k + 1 Next Next CreateVBArray = a End Function --> </script> <script type="text/javascript"> <!-- function VBArrayTest(vba){ var i; var a = new VBArray(vba); var s = ""; for (i = 1; i <= a.dimensions
(); i++) { s += "The lower bound of dimension "; s += i + " is "; s += a.lbound(i); s += ".<br />"; } return (s); } --> </script> </head> <body> <script type="text/javascript"> document.write(VBArrayTest(CreateVBArray
())); </script> </body> Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standa...
VBArray.toArray - Archive of obsolete content
ts. The first part is VBScript code to create a Visual Basic safe array. The second part is JavaScript code that converts the Visual Basic safe array to a JavaScript array. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JavaScript code that goes in the <BODY> section to run the other two parts. ...
...> <!-- Function CreateVBArray
() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For j = 0 To 2 a(j, i) = k document.writeln(k) k = k + 1 Next document.writeln("<BR>") Next CreateVBArray = a End Function --> </script> <script type="text/javascript"> <!-- function VBArrayTest(vbarray) { var a = new VBArray(vbarray); var b = a.toArray
(); var i; for (i = 0; i < 9; i++) { document.writeln(b[i]); } } --> </script> </head> <body> <script type="text/javascript"> <!-- VBArrayTest(CreateVBArray
()); --> </script> </body> Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, and In...
VBArray.ubound - Archive of obsolete content
de to create a Visual Basic safe array. The second part is JavaScript code that determines the number of dimensions in the safe array and the upper bound of each dimension. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JavaScript code that goes in the <BODY> section to run the other two parts. ...
...d> <script type="text/vbscript"> <!-- Function CreateVBArray
() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For j = 0 To 2 a(j, i) = k k = k + 1 Next Next CreateVBArray = a End Function --> </script> <script type="text/javascript"> <!-- function VBArrayTest(vba) { var i; var a = new VBArray(vba); var s = ""; for (i = 1; i <= a.dimensions
(); i++) { s += "The upper bound of dimension "; s += i + " is "; s += a.ubound(i); s += ".<br />"; } return (s); } --> </script> </head> <body> <script type="text/javascript"> document.write(VBArrayTest(CreateVBArray
())); </script> </body> Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standa...
JavaArray - Archive of obsolete content
representing the type of the array or class object, such as one returned by java.lang.Class.forName. In JavaScript 1.3 and earlier, componentType must be a class object. Use zero-based indexes to access the elements in a JavaArray object, just as you do to access elements in an array in Java. For example: var javaString = new java.lang.String("Hello world!"); var byteArray = javaString.getBytes
(); byteArray[0] // returns 72 byteArray[1] // returns 101 Any Java data brought into JavaScript is converted to JavaScript data types. When the JavaArray is passed back to Java, the array is unwrapped and can be used by Java code. See the Core JavaScript 1.5 Guide for more information about data type conversions. In JavaScript 1.4 and later, the methods of java.lang.Object are inherited by JavaA...
...ct as a JavaArray. In JavaScript 1.4 and later, JavaArray also inherits methods from the Java array superclass, java.lang.Object. Examples Example: Instantiating a JavaArray in JavaScript In this example, the JavaArray byteArray is created by the java.lang.String.getBytes method, which returns an array. ...
Using XForms and PHP - Archive of obsolete content
Introduction A few tips on using XForms and PHP together. Returning XML data To either serve a page (with XForms in it) or to generate data used as instance data for XForms, the page needs to be served as XML, for example application/xhtml+xml. To do that, you need to use the header
() PHP function: <?php header("Content-Type: application/xhtml+xml; charset=UTF-8"); ... ?> But remember this (quote from PHP documentation): Remember that header
() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include
(), or require
(), functions, or another file access function, and have spaces or empty lines that are output before header
() is called. The same problem exists when using a sing...
...he power of XForms (/XML) you would probably submit XML. There is some help in getting to the raw XML on the PHP Documentation site. How to actually parse and use the XML data depends heavily on what you want to achieve and on the PHP version. To get a DOM Document on PHP 4 I usually do something like this: $data = $HTTP_RAW_POST_DATA; $dom = domxml_open_mem($data); $root = $dom->document_element
(); ... $newnode = $dom->create_element("boo"); $root->append_child($newnode); ... ...
Describing microformats in JavaScript - Archive of obsolete content
s structure is specified by its name, and may include additional attributes if the property so requires. Standard attributes are: plural A boolean value indicating that, if true indicates that the property can have multiple values. If a property is plural, it is returned as an array. virtual A boolean value indicating whether or not the property is virtual. If it's virtual, the virtualGetter
() method will be called to attempt to create the property if it doesn't exist. virtualGetter A function that is called to get a virtual property's value. This is only used if virtual is true. value The property's default value. subproperties It's possible for a property to itself include more properties; to do so, include them in a subproperties structure within the property. dataType The t...
... forth). Since the plural property is true, multiple types can be specified. This allows an address to be marked as being, for example, a work address for receiving parcels. The street-address property is plural as well. This allows multiple lines of address information to be contained in the street-address array. The microformat is registered with the microformat API by calling Microformats.add
(), like this: Microformats.add("adr", adr_definition); Note: To be clear: since the adr microformat is included by default in Firefox 3 and later, you don't need to add it yourself if you wish to make use of it. See also Using microformats, Parsing microformats in JavaScript ...
Using the DOM File API in chrome code - Extensions
oss platform note: However using hard-coded paths raises cross platform issues since it uses a platform-dependent path separator (here "/"). In the XUL/Mozilla platform there isn't sadly an equivalent to Java File.pathSeparator (the system-dependent path-separator character). So the good practice is to avoid trying to determine and to use the path separator at all. Instead, use the nsIFile::append
() method as explained in the next section. Accessing files in a special directory You can also use the directory service to obtain and build the path to a file to access. For example, let's say your add-on needs to access a file in the user's profile. You can do so like this: var dsFile = Components.classes["@mozilla.org/file/directory_service;1"] .getService(Components.inter...
...Finally, we instantiate the File object by calling File.createFromNsIFile. Other such keys as the "ProfD" key are available, check the known locations. Notes Starting in Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5), you can also do this in component code. ...
Bounce off the walls - Game development
liding with) the wall, and if so, we will change the direction of its movement accordingly. To make the calculations easier let's define a variable called ballRadius that will hold the radius of the drawn circle and be used for calculations. Add this to your code, somewhere below the existing variable declarations: var ballRadius = 10; Now update the line that draws the ball inside the drawBall
() function to this: ctx.arc(x, y, ballRadius, 0, Math.PI*2); Bouncing off the top and bottom There are four walls to bounce the ball off -- let's focus on the top one first. We need to check, on every frame, whether the ball is touching the top edge of the Canvas -- if yes, we'll reverse the ball movement so it will start to move in the opposite direction and stay within the visible boundaries. ...
...uncing off the left and right We have the top and bottom edge covered, so let's think about the left and right ones. It is very similar actually, all you have to do is to repeat the statements for x instead of y: if(x + dx > canvas.width || x + dx < 0) { dx = -dx; } if(y + dy > canvas.height || y + dy < 0) { dy = -dy; } At this point you should insert the above code block into the draw
() function, just before the closing curly brace. The ball keeps disappearing into the wall! Test your code at this point, and you will be impressed -- now we have a ball that bounced off all four edges of the canvas! We have another problem however -- when the ball hits each wall it sinks into it slightly before changing direction: This is because we're calculating the collision point of the w...
Game over - Game development
ompleting this lesson at Gamedev-Phaser-Content-Kit/demos/lesson08.html. To make the game more interesting we can introduce the ability to lose -- if you don't hit the ball before it reaches the bottom edge of the screen it will be game over. How to lose To provide the ability to lose, we will disable the ball's collision with the bottom edge of the screen. Add the code below inside the create
() function; just after you define the ball's attributes is fine: game.physics.arcade.checkCollision.down = false; This will make the three walls (top, left and right) bounce the ball back, but the fourth (bottom) will disappear, letting the ball fall off the screen if the paddle misses it. We need a way to detect this and act accordingly. Add the following lines just below the previous new one: ...
....physics.arcade.checkCollision.down = false; This will make the three walls (top, left and right) bounce the ball back, but the fourth (bottom) will disappear, letting the ball fall off the screen if the paddle misses it. We need a way to detect this and act accordingly. Add the following lines just below the previous new one: ball.checkWorldBounds = true; ball.events.onOutOfBounds.add(function
(){ alert('Game over!'); location.reload
(); }, this); Adding those lines will make the ball check the world (in our case canvas) bounds and execute the function bound to the onOutOfBounds event. When you click on the resulting alert, the page will be reloaded so you can play again. Compare your code You can check the finished code for this lesson in the live demo below, and play with it ...
Move the ball - Game development
s the 4th step out of 16 of the Gamedev Phaser tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Phaser-Content-Kit/demos/lesson04.html. We have our blue ball printed on screen, but it's doing nothing -- It would be cool to make it move somehow. This article covers how to do just that. ...
...creen, but it's doing nothing -- It would be cool to make it move somehow. This article covers how to do just that. Updating the ball's position on each frame Remember the update
() function and its definition? The code inside it is executed on every frame, so it's a perfect place to put the code that will update the ball's position on screen. Add the following new lines of the code inside update
(), as shown: function update
() { ball.x += 1; ball.y += 1; } The code above adds 1 to the x and y properties representing the the ball coordinates on the canvas, on each frame. Reload index.html and you should see the ball rolling across the screen. Compare your code You can check the finished code for this lesson in the live demo below, and play with it to understand better how it wor...
Scaling - Game development
ntent-Kit/demos/lesson02.html. Scaling refers to how the game canvas will scale on different screen sizes. We can make the game scale to fit on any screen size automatically during the preload stage, so we don't have to worry about it later. The Phaser scale object There's a special scale object available in Phaser with a few handy methods and properties available. Update your existing preload
() function as follows: function preload
() { game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; game.scale.pageAlignHorizontally = true; game.scale.pageAlignVertically = true; } scaleMode has a few different options available for how the Canvas can be scaled: NO_SCALE -- nothing is scaled. EXACT_FIT -- scale the canvas to fill all the available space both vertically and horizont...
...ut we can live with that. RESIZE -- creates the canvas with the same size as the available width and height, so you have to place the objects inside your game dynamically; this is more of an advanced mode. USER_SCALE -- allows you to have custom dynamic scaling, calculating the size, scale and ratio on your own; again, this is more of an advanced mode The other two lines of code in the preload
() function are responsible for aligning the canvas element horizontally and vertically, so it is always centered on screen regardless of size. Adding a custom canvas background colour We can also add a custom background color to our canvas, so it won't stay black. The stage object has a backgroundColor property for this purpose, which we can set using CSS color definition syntax. Add the followin...
Base64 - MDN Web Docs Glossary: Definitions of Web-related terms
re that the data remain intact without modification during transport. Base64 is commonly used in a number of applications including email via MIME, and storing complex data in XML. One common application of base64 encoding on the web is to encode binary data so it can be included in a data: URL. ...
...luding email via MIME, and storing complex data in XML. One common application of base64 encoding on the web is to encode binary data so it can be included in a data: URL. In JavaScript there are two functions respectively for decoding and encoding base64 strings: btoa
(): creates a base-64 encoded ASCII string from a "string" of binary data ("btoa" should be read as "binary to ASCII"). atob
(): decodes a base64 encoded string("atob" should be read as "ASCII to binary"). The algorithm used by atob
() and btoa
() is specified in RFC 4648, section 4. Note that btoa
() expects to be passed binary data, and will throw an exception if the given string contains any characters whose UTF-16 representation occupies more than one byte. For more details, see the documentation for btoa
(). Encoded ...
Global object - MDN Web Docs Glossary: Definitions of Web-related terms
ess Global Variables var foo = "foobar"; foo === window.foo; // Returns: true After defining a Global Variable foo, we can access its value directly from the window object, by using the variable name foo as a property name of the Global Object window.foo. Explanation: The global variable foo was stored in the window object, like this: foo: "foobar" Access Global Functions function greeting
() { console.log("Hi!"); } window.greeting
(); // It is the same as the normal invoking: greeting
(); The example above explains how Global Functions are stored as properties in the window object. We created a Global Function called greeting, then invoked it using the window object. Explanation: The global function greeting was stored in the window object, like this: greeting: function greeti...
... console.log("Hi!"); } window.greeting
(); // It is the same as the normal invoking: greeting
(); The example above explains how Global Functions are stored as properties in the window object. We created a Global Function called greeting, then invoked it using the window object. ...
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
e assigned a primitive value. The variable may be reassigned a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered. Example This example will help you understand that primitive values are immutable. JavaScript // Using a string method doesn't mutate the string var bar = "baz"; console.log(bar); // baz bar.toUpperCase
(); console.log(bar); // baz // Using an array method mutates the array var foo = []; console.log(foo); // [] foo.push("plugh"); console.log(foo); // ["plugh"] // Assignment gives the primitive a new (not a mutated) value bar = bar.toUpperCase
(); // BAZ A primitive can be replaced, but it can't be directly altered. Another Example [ Step-by-step ]...
...fying a copy, without affecting the original. Primitive wrapper objects in JavaScript Except for null and undefined, all primitive values have object equivalents that wrap around the primitive values: String for the string primitive. Number for the number primitive. BigInt for the bigint primitive. Boolean for the boolean primitive. Symbol for the symbol primitive. The wrapper's valueOf
() method returns the primitive value. Learn more General knowledge Introduction to JavaScript data types Primitive data type on Wikipedia ...
Scope - MDN Web Docs Glossary: Definitions of Web-related terms
e. 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. ...
...e, 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, 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 ...
WAI-ARIA basics - Learn web development
ed to as live regions. Let's look at a quick example -- see aria-no-live.html (also see it running live). In this example we have a simple random quote box: <section> <h1>Random quote</h1> <blockquote> <p></p> </blockquote> </section> Our JavaScript loads a JSON file via XMLHttpRequest containing a series of random quotes and their authors. Once that is done, we start up a setInterval
() loop that loads a new random quote into the quote box every 10 seconds: let intervalID = window.setInterval(showQuote, 10000); This works OK, but it is not good for accessibility -- the content update is not detected by screenreaders, so their users would not know what is going on. This is a fairly trivial example, but just imagine if you were creating a complex UI with lots of constantly updat...
... An aria-relevant value of all instructs the screenreader to read out the contents of the error list when any changes are made to it -- i.e. when errors are added or removed. This is useful because the user will want to know what errors are left, not just what has been added or removed from the list. We could go furthe...
How CSS is structured - Learn web development
's CSS engine. Important: In CSS (and other web standards), it has been agreed that US spelling is the standard where there is language variation or uncertainty. For example, color should be spelled color, as colour will not work. Functions While most values are relatively simple keywords or numeric values, there are some values which take the form of a function. An example would be the calc
() function, which can do simple math within CSS: <div class="outer"><div class="box">The inner box is 90% - 30px.</div></div> .outer { border: 5px solid black; } .box { padding: 10px; width: calc(90% - 30px); background-color: rebeccapurple; color: white; } This renders as: A function consists of the function name, and parentheses to enclose the values for the function. In the ca...
...ch can do simple math within CSS: <div class="outer"><div class="box">The inner box is 90% - 30px.</div></div> .outer { border: 5px solid black; } .box { padding: 10px; width: calc(90% - 30px); background-color: rebeccapurple; color: white; } This renders as: A function consists of the function name, and parentheses to enclose the values for the function. In the case of the calc
() example above, the values define the width of this box to be 90% of the containing block width, minus 30 pixels. The result of the calculation isn't something that can be computed in advance and entered as a static value. Another example would be the various values for transform, such as rotate
(). <div class="box"></div> .box { margin: 30px; width: 100px; height: 100px; background-col...
Styling lists - Learn web development
t = document.querySelector(".css-input"); var reset = document.getElementById("reset"); var htmlCode = htmlInput.value; var cssCode = cssInput.value; var output = document.querySelector(".output"); var solution = document.getElementById("solution"); var styleElem = document.createElement('style'); var headElem = document.querySelector('head'); headElem.appendChild(styleElem); function drawOutput
() { output.innerHTML = htmlInput.value; styleElem.textContent = cssInput.value; } reset.addEventListener("click", function
() { htmlInput.value = htmlCode; cssInput.value = cssCode; drawOutput
(); }); solution.addEventListener("click", function
() { htmlInput.value = htmlCode; cssInput.value = 'ul {\n list-style-type: square;\n}\n\nul li, ol li {\n line-height: 1.5;\n}\n\nol {\n lis...
...styleElem.textContent = cssInput.value; } reset.addEventListener("click", function
() { htmlInput.value = htmlCode; cssInput.value = cssCode; drawOutput
(); }); solution.addEventListener("click", function
() { htmlInput.value = htmlCode; cssInput.value = 'ul {\n list-style-type: square;\n}\n\nul li, ol li {\n line-height: 1.5;\n}\n\nol {\n list-style-type: lower-alpha\n}'; drawOutput
(); }); htmlInput.addEventListener("input", drawOutput); cssInput.addEventListener("input", drawOutput); window.addEventListener("load", drawOutput); ...
Example 3 - Learn web development
.querySelector('.optList'); optList.classList.toggle('hidden'); } function highlightOption(select, option) { var optionList = select.querySelectorAll('.option'); optionList.forEach(function (other) { other.classList.remove('highlight'); }); option.classList.add('highlight'); }; // ------------- // // Event binding // // ------------- // window.addEventListener("load", function
() { var form = document.querySelector('form'); form.classList.remove("no-widget"); form.classList.add("widget"); }); window.addEventListener('load', function
() { var selectList = document.querySelectorAll('.select'); selectList.forEach(function (select) { var optionList = select.querySelectorAll('.option'); optionList.forEach(function (option) { option.addEventListener(...
...nt.querySelector('form'); form.classList.remove("no-widget"); form.classList.add("widget"); }); window.addEventListener('load', function
() { var selectList = document.querySelectorAll('.select'); selectList.forEach(function (select) { var optionList = select.querySelectorAll('.option'); optionList.forEach(function (option) { option.addEventListener('mouseover', function
() { highlightOption(select, option); }); }); select.addEventListener('click', function (event) { toggleOptList(select); }, false); select.addEventListener('focus', function (event) { activeSelect(select, selectList); }); select.addEventListener('blur', function (event) { deactivateSelect(select); }); select.addEventListener('keyup...
Example 5 - Learn web development
etAttribute('aria-selected', 'true'); nativeWidget.selectedIndex = index; value.innerHTML = optionList[index].innerHTML; highlightOption(select, optionList[index]); }; function getIndex(select) { var nativeWidget = select.previousElementSibling; return nativeWidget.selectedIndex; }; // ------------- // // Event binding // // ------------- // window.addEventListener("load", function
() { var form = document.querySelector('form'); form.classList.remove("no-widget"); form.classList.add("widget"); }); window.addEventListener('load', function
() { var selectList = document.querySelectorAll('.select'); selectList.forEach(function (select) { var optionList = select.querySelectorAll('.option'), selectedIndex = getIndex(select); select.tabIndex = 0; se...
...= document.querySelectorAll('.select'); selectList.forEach(function (select) { var optionList = select.querySelectorAll('.option'), selectedIndex = getIndex(select); select.tabIndex = 0; select.previousElementSibling.tabIndex = -1; updateValue(select, selectedIndex); optionList.forEach(function (option, index) { option.addEventListener('mouseover', function
() { highlightOption(select, option); }); option.addEventListener('click', function (event) { updateValue(select, index); }); }); select.addEventListener('click', function (event) { toggleOptList(select); }); select.addEventListener('focus', function (event) { activeSelect(select, selectList); }); select.addEventListener('blur...
UI pseudo-classes - Learn web development
want to disable using input[type="text"]:disabled, but we also wanted to gray out the corresponding text labels. These weren't quite as easy to select, so we've used a class to provide them with that styling. ...
...provide them with that styling. ...
Index - Learn web development
d fun writing your own real world random bouncing balls example, using various object and object-oriented techniques from throughout the module! This should have given you some useful practice in using objects, and good real world context. 69 Object prototypes Article, Beginner, CodingScripting, Constructor, JavaScript, Learn, OOJS, OOP, Object, Prototype, Prototype Chaining, create
(), l10n:priority This article has covered JavaScript object prototypes, including how prototype object chains allow objects to inherit features from one another, the prototype property and how it can be used to add methods to constructors, and other related topics. 70 Object-oriented JavaScript for beginners Article, Beginner, CodingScripting, Constructor, Create, JavaScript, L...
... Custom Data Attributes, Example, Guide, HTML, HTML5, Web HTML5 is designed with extensibility in mind for data that should be associated with a particular element but need not have any defined meaning. data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, extra properties on DOM, or Node.setUserData
(). 258 Tools and testing Accessibility, Automation, Beginner, CSS, CodingScripting, HTML, JavaScript, Landing, Learn, Testing, Tools, Topic, cross browser, user testing Once you've started to become comfortable programming with core web technologies (like HTML, CSS, and JavaScript), and you start to get more experience, read more resources, and learn more tips and tricks, you'l...
Test your skills: Functions - Learn web development
ents on the page -- all via JavaScript. We haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into what DOM APIs you need to successfully answer the questions. A good starting place is our Manipulating documents tutorial. Functions 1 For the first task, you have to create a simple function -- chooseName
() -- that prints a random name from the provided array (names) to the provided paragraph (para), and then run it once. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Functions 2 For our second functions-related task, you need to create a function that draws a rectangle on the pro...
...dating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Functions 3 In this task, you return to the problem posed in Task 1, with the aim of improving it. The three improvements we want you to make are: Refactor the code that generates the random number into a separate function called random
(), which takes as parameters two generic bounds that the random number should be between, and returns the result. Update the chooseName
() function so that it makes use of the random number function, takes the array to choose from as a parameter (making it more flexible), and returns the result. Print the returned result into the paragraph (para)'s textContent. Try updating the live code below ...
Storing the information you need — Variables - Learn web development
ion on how to access this tool). What is a variable? A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence. But one special thing about variables is that their contained values can change. Let's look at a simple example: <button>Press me</button> const button = document.querySelector('button'); button.onclick = function
() { let name = prompt('What is your name?'); alert('Hello ' + name + ', nice to see you!'); } In this example pressing the button runs a couple of lines of code. The first line pops a box up on the screen that asks the reader to enter their name, and then stores the value in a variable. The second line displays a welcome message that includes their name, taken from the variable value. To un...
... you'll start to discover them as you learn more about JavaScript (if you really want to read about them now, feel free to check out our let reference page). For a start, if you write a multiline JavaScript program that declares and initializes a variable, you can actually declare a variable with var after you initialize it and it will still work. For example: myName = 'Chris'; function logName
() { console.log(myName); } logName
(); var myName; Note: This won't work when typing individual lines into a JavaScript console, just when running multiple lines of JavaScript in a web document. This works because of hoisting -- read var hoisting for more detail on the subject. Hoisting no longer works with let. If we changed var to let in the above example, it would fail with an error. Thi...
Server-side web frameworks - Learn web development
URL patterns to specific handler functions. This approach also has benefits in terms of maintenance, because you can change the URL used to deliver a particular feature without having to change the underlying code. Different frameworks use different mechanisms for the mapping. For example, the Flask (Python) web framework adds routes to view functions using a decorator. @app.route("/") def hello
(): return "Hello World!" While Django expects developers to define a list of URL mappings between a URL pattern and a view function. urlpatterns = [ url(r'^$', views.index), # example: /best/myteamname/5/ url(r'^best/(?P<team_name>\w.+?)/(?P<team_number>[0-9]+)/$', views.best), ] Make it easy to access data in the request Data can be encoded in an HTTP request in a number of wa...
...tatements (for example, you can specify a search on U11 teams that have a team name that starts with "Fr" or ends with "al"). The second code snippet shows a view function (resource handler) for displaying all of our U09 teams. In this case we specify that we want to filter for all records where the team_level field has exactly the text 'U09' (note below how this criteria is passed to the filter
() function as an argument with field name and match type separated by double underscores: team_level__exact). #best/views.py from django.shortcuts import render from .models import Team def youngest(request): list_teams = Team.objects.filter(team_level__exact="U09") context = {'youngest_teams': list_teams} return render(request, 'best/index.html', context) Rendering data Web fr...
Beginning our React todo list - Learn web development
Worker.js setupTests.js # Move back up to the root of the project cd .. Notes: Two of the files we're deleting are for testing the application. We will not cover testing here. If you stopped your server to do the terminal tasks mentioned above, you'll have to start it again using npm start. ...
... your server to do the terminal tasks mentioned above, you'll have to start it again using npm start. Project starter code As a starting point for this project, we're going to provide two things: An App
() function to replace the one you have now, and some CSS to style your app. ...
Deployment and next steps - Learn web development
A particularly useful plugin which is also maintain...
...rver in development mode: // In dev mode, call `npm run start` once // the bundle has been generated !production && serve
(), // Watch the `public` directory and refresh the // browser on changes when not in production !production && livereload('public'), // If we're building for production (npm run build // instead of npm run dev), minify production && terser
() ], There are many plugins for rollup that allow you to customize its behavior. A particularly useful plugin which is also maintained by the Svelte team is svelte-preprocess, which pre-processes many different languages in Svelte files such as PostCSS, SCSS, Less, CoffeeScript, SASS, and TypeScript. Deploying your Svelte application From the point of view of a web server, a Svelte application...
Using Vue computed properties - Learn web development
s array changes. To create a computed property, we need to add a computed property to our component object, much like the methods property we've used previously. Adding a summary counter Add the following code to your App component object, below the methods property. The list summary method will get the number of finished ToDoItems, and return a string reporting this. computed: { listSummary
() { const numberFinishedItems = this.ToDoItems.filter(item =>item.done).length return `${numberFinishedItems} out of ${this.ToDoItems.length} items completed` } } Now we can add {{listSummary}} directly to our template; we'll add this inside an <h2> element, just above our <ul>. We'll also add an id and an aria-labelledby attribute to assign the <h2> contents to be a label for the <ul> e...
... not relying on a button press to trigger the change, we can attach a @change event handler to each checkbox instead of using v-model. Update the <input> element in ToDoItem.vue to look like this. <input type="checkbox" class="checkbox" :id="id" :checked="isDone" @change="$emit('checkbox-changed')" /> Since all we need to do is emit that the checkbox was checked, we can include the $emit
() inline. In App.vue, add a new method called updateDoneStatus
(), below your addToDo
() method. This method should take one parameter: the todo item id. We want to find the item with the matching id and update its done status to be the opposite of its current status: updateDoneStatus(toDoId) { const toDoToUpdate = this.ToDoItems.find(item => item.id === toDoId) toDoToUpdate.done = !toDoToUpdat...
Command line crash course - Learn web development
s that contain the word "location"). Try running the following, and you'll see that in fact there are three redirects happening before we reach the final page: curl /docs/Web/API/fetch -L -I | grep location Your output should look something like this (curl will first output some download counters and suchlike): location: /docs/Web/API/fetch location: /docs/Web/API/GlobalFetch/GlobalFetch.fetch
() location: /docs/Web/API/GlobalFetch/fetch location: /docs/Web/API/WindowOrWorkerGlobalScope/fetch Although contrived, we could take this result a little further and transform the location: line contents, adding the base origin to the start of each one so that we get complete URLs printed out. For that, we'll add awk to the mix (which is a programming language akin to JavaScript or Ruby or Python...
...hat we get complete URLs printed out. 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 | 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 arse...
Package management basics - Learn web development
Go there now and you'll not see anything for now, but what is cool is that when you do make changes to your app, Parcel will rebuild it and refresh the server automatically so you can instantly see the effect your update had. Now for some page content. Let's say we want to show human-readable relative dates, such as "2 hours ago", "4 days ago" and so on. The date-fns package's formatDistanceToNow
() method is useful for this (there's other packages that do the same thing too). In the index.js file, add the following code and save it: import { formatDistanceToNow } from 'date-fns' const date = '1996-09-13 10:00:00'; document.body.textContent = formatDistanceToNow(new Date(date)) + ' ago'; Go back to http://localhost:1234 and you'll see how long ago it is since the author turned 18. What'...
... index.js file, add the following code and save it: import { formatDistanceToNow } from 'date-fns' const date = '1996-09-13 10:00:00'; document.body.textContent = formatDistanceToNow(new Date(date)) + ' ago'; Go back to http://localhost:1234 and you'll see how long ago it is since the author turned 18. What's particularly special about the code above is that it is using the formatDistanceToNow
() function from the date-fns package, which we didn't install! Parcel has spotted that you need the module, searched for it in the npmjs.com package registry, and installed it locally for us, automatically. You can prove this by looking in our package.json file again -- you'll see that the dependencies field have been updated for us: "dependencies": { "date-fns": "^2.12.0", "parcel-bundler": "...
Theme concepts
rammatic control. And, obviously, you can combine the two and bundle a programmatically controlled theme with your extension. Using the theme API is straightforward. First, request "theme" permission in the extension's manifest.json file. Next, you build a JSON object containing the same information you would use in a static theme's manifest.json, Finally, pass the JSON object in a theme.update
() call. For example, the following code, from the dynamic theme example defines the content for the day and night elements of the dynamic theme: const themes = { 'day': { images: { theme_frame: 'sun.jpg', }, colors: { frame: '#CF723F', tab_background_text: '#111', } }, 'night': { images: { theme_frame: 'moon.jpg', }, colors: { frame: '#00...
... return; } currentTheme = theme; browser.theme.update(themes[theme]); } Learn more about dynamic themes and see an additional example in the following video: If you have not built a b...
Adding a new CSS property
AND macro. When writing the custom parsing code for a shorthand, you'll need to ensure that any successful parse sets all of the subproperties of the shorthand (since that's the way shorthands work in CSS). Some common mistakes to watch out for when writing custom parsing code (which might go away if we redesign the parser along the lines described in css3-syntax): make sure to call SkipUntil
() to look for the matching close parentheses, braces, or brackets whenever you hit an error inside of them. make sure to call UngetToken
() if you have called GetToken
() but the result is unexpected. This is particularly important in case the unexpected token is a parenthesis or something else that requires matching the other half of a pair. if you're adding a preference-controlled property to a ...
... Computed Style When adding a new longhand property, you also need to implement the computed style side of things. (None of this applies to shorthand properties.) Start by reading and understanding the "Computed Value:" l...
Creating Custom Events That Can Pass Data
_MAP_END Remember, {truncated name} is the same as above. mozilla/content/events/src/nsEventDispatcher.cpp Note: In the mozilla 1.8.x branch this code is actually in mozilla/content/events/src/nsEventListenerManager.cpp This is quite an important file since this holds the CreateEvent method which acts as a factory method DOM events. The change you want to make is in nsEventDispatcher::CreateEvent
(). ...
...ts as a factory method DOM events. The change you want to make is in nsEventDispatcher::CreateEvent
(). You will find that there is a bunch of code like: if (aEventType.LowerCaseEqualsLiteral("{somethingsomething}event")) return NS_{somethingSomething}Event(aDOMEvent, aPresContext, nsnull); You can either have a function like this or write the code straight in nsEventListenerManager::CreateEvent
() like this: if (aEventType.LowerCaseEqualsLiteral("nsmyevent")){ //note: the lowercase is important! nsDOMEvent* it = new nsDOMMyEvent(aPresContext, aEvent); if (nsnull == it) { return NS_ERROR_OUT_OF_MEMORY; } return CallQueryInterface(it, aDOMEvent); } In general though I'd strongly recommend using a function the way that everyone else does. You can find the prototypes for the funct...
Reviewer Checklist
ing user input, network input, or files on disk. Assume that inputs will be too big, too short, empty, malformed, or malicious. Tag for sec review if unsure. If you're writing code that uses JSAPI, chances are you got it wrong. Try hard to avoid doing that. Privacy issues There should be no logging of URLs or content from which URLs may be inferred. [Fennec: Android Services has Logger.pii
() for this purpose (e.g., logging profile dir)]. Tag for privacy review if needed. Resource leaks In Java, memory leaks are largely due to singletons holding on to caches and collections, or observers sticking around, or runnables sitting in a queue. In C++, cycle-collect as needed. If JavaScript can see your object, it probably needs to be cycle-collected. [Fennec: If your custom view does...
...iew if needed. Resource leaks In Java, memory leaks are largely due to singletons holding on to caches and collections, or observers sticking around, or runnables sitting in a queue. In C++, cycle-collect as needed. If JavaScript can see your object, it probably needs to be cycle-collected. [Fennec: If your custom view does animations, it's better to clean up runnables in onDetachFromWindow
().] Ensure all file handles and other closeable resources are closed appropriately. [Fennec: When writing tests that use PaintedSurface, ensure the PaintedSurface is closed when you're done with it.] Performance impact Check for main-thread IO [Fennec: Android may warn about this with strictmode]. Remove debug logging that is not needed in production. Threading issues Enormous: correct...
Limitations of chrome scripts
servers in the chrome process Depending on the topic, you need to register observers in either the chrome process or in a frame script. For most topics you need to register observers in the chrome process. However, you must listen to content-document-global-created and document-element-inserted in a frame script. Observers for these topics get content objects as the aSubject argument to observe
(), so notifications are not sent to the chrome process. There is a shim that will forward these two topics to the chrome process, sending CPOWs as the aSubject argument. HTTP requests You can't observe HTTP requests in the content process. If you do, you'll get an error. If you do so in the chrome process, it will mostly work. The subject for the observer notification will be an nsIHttpChanne...
... ...
Security best practices for Firefox front-end engineers
ing benevolent developers. ...
...evelopers are able to avoid tripping the rule by using escaping functions in combination with template strings, for example: bar.innerHTML = escapeHTML`<a href='${url}'>About</a>`; In system-privileged chrome code, any kind of remaining scripts will still be removed by our sanitizer. Appendix List of disallowed DOM APIs innerHTML outerHTML insertAdjacentHTML
() createContextualFragment
() document.write
() document.writeln
() Please take a look at the repository for an updated list ...
mozbrowserclose
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The mozbrowserclose event is fired when the content of a browser <iframe> calls the window.close
() method. General info Specification Non standard Interface CustomEvent Bubbles Yes Cancelable Yes Target <iframe> Default Action None Properties Property Type Description target Read only EventTarget The event target (the topmost target in the DOM tree). type Read only DOMString The type of event. bubbles Read only Boolean...
... event target (the topmost target in the DOM tree). type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. ...
mozbrowserloadstart
ubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. Example In this example the mozbrowserloadend and mozbrowserloadstart events are used to change the icon shown on the stop/reload button between stop (x) and reload (R), as appropriate. ...
... not. Example In this example the mozbrowserloadend and mozbrowserloadstart events are used to change the icon shown on the stop/reload button between stop (x) and reload (R), as appropriate. ...
mozbrowseropenwindow
non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The mozbrowseropenwindow event is fired when a new window is required -- usually when the content of a browser <iframe> successfully calls the window.open
() method, or the user clicks on a link with an unknown target. The embedder must use the <iframe> passed in the event.details.frameElement property as the new window content. General info Specification Non standard Interface CustomEvent Bubbles Yes Cancelable Yes Target <iframe> Default Action None Properties Property Type Description target Read only ...
... returns an anonymous JavaScript object with the following properties: url A DOMString representing the URL of the document loaded within the frameElement property. name A DOMString representing the name of the new browser window. features A DOMString containing features represented by a list of names and values separated by commas. For a complete list of possible features, see window.open
(). frameElement An object representing the new browser <iframe> that will embed the new content. Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowseropenwindow", function( event ) { console.log("A new window has opened containing the content at " + event.details.url + "."); }); Related Events mozbrowserasyncscroll mozbrowserclose mozbrowserconte...
mozbrowserusernameandpasswordrequired
re may also be large incompatibilities between implementations and the behavior may change in the future. The mozbrowserusernameandpasswordrequired event is fired when the content within a browser <iframe> requires an HTTP authentification. The embedder is supposed to retrieve the necessary credentials, usually using a dialog or a database of username/passwords, and then call authenticate
() or cancel
() as appropriate. General info Specification Non standard Interface CustomEvent Bubbles Yes Cancelable Yes Target <iframe> Default Action None Properties Property Type Description target Read only EventTarget The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whethe...
...m object. details The details property returns an anonymous JavaScript object with the following members: host A DOMString representing the host requesting the HTTP authentification. realm A DOMString representing the value of the realm HTTP header. isProxy A Boolean indicating whether the server dealing with the authentication is a proxy server (true) or not (false). authenticate
() A function that is called to enable the authentication to go ahead. It needs to take two parameters -- the username and password to authenticate. cancel
() A function that is called to cancel the authentication. Example var browser = document.querySelector("iframe[mozbrowser]"); browser.addEventListener("mozbrowserusernameandpasswordrequired", function( event ) { console.log("The auth rea...
Overview of Mozilla embedding APIs
alls GetInterface(...) to retrieve the requested interface. do_QueryReferent This function is the equivilent of do_QueryInterface except that it performs the QI through a weak reference. do_GetService This function simplifies accessing services from the Service Manager. do_CreateInstance This function simplifies creating new component instances. nsCOMTypeInfo<interface-type>::GetIID
() This template helper class allows easy access to an interface's nsIID. Typically the NS_GET_IID(...) macro is used instead of using the nsCOMTypeInfo template directly. NS_GetWeakReference This function creates a weak reference to a component which implements the nsIWeakReference interface. Global Services nsServiceManager The Service Manager is the central repository for accessing instances...
...Window' with a // reference to an appropriate native resource... rv = baseWindow->InitWindow(nativeWindow, // Native window nsnull, // Always nsnull. 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 WebBrows...
IPDL Best Practices
er::AllocPProtocol - allocation Manager::RecvPProtocolConstructor - initialization, protocol deletion (the TypeAheadFind protocol uses one-shot protocols like this) Actor::Recv__delete__ - cleanup, IPDL calls still valid but ill-advised Actor::ActorDestroy - non-IPDL cleanup Manager::DeallocPProtocol - deallocation One construct to avoid: class ProtocolParent { public: ~ProtocolParent
() { Send__delete__(this); } }; class ProtocolManagerParent { public: PProtocolParent* AllocPProtocol
() { return new ProtocolParent
(); } bool DeallocPProtocol
() { return true; } }; nsAutoPtr<PProtocolParent> parent = manager->SendPProtocolConstructor
(); While this may look appealing as the IPDL logic is stuffed away in a sensible place, it breaks unde...
...ion a second time. While this can be worked around with ActorDestroy, being explicit about deleting the protocol with Send__delete__ is easier to maintain, with symmetric Alloc/DeallocPProtocol functions also being easier to reason about. Minimize overall use of messages Reducing IPC traffic is a righteous goal. Consider the following protocol: async protocol PAsyncQuerier { child: PAsyncQuery
(); } async protocol PAsyncQuery { child: KickOffQuery(nsString query); parent: ReturnResult(nsString result); __delete__
(); } In this situation, there is a guaranteed sequence of messages that will be sent. Following actor construction, the parent will send a KickOffQuery message and presumably ignore the actor until it receives ReturnResult, at which point it will be deleted. It makes s...
JavaScript Tips
XUL Tips When inserting code with an XUL overlay, wrap functions and variables inside an object with a unique name to avoid conflicting with existing or future function and variable names. var UniqueName = { _privateMember: 3, publicMember: "A string", init: function
() { this.doSomething(this.anotherMember); }, doSomething: function(aParam) { alert(aParam); } }; XPConnect Don't use object methods and properties more than you have to. It is often faster to store the result in a temporary variable. Don't call methods that you don't have to. For instance, windowManager.getEnumerator(aType).hasMoreElements
() may be replaced with windowManager.getMostRecentWindow(aType) != null for a single window. Don't query interfaces unless you need to access methods ...
...XPCOM methods, try to use the same names for method parameters as are used in the interface definition. DOM elements DOM elements are just XPCOM objects with some of the interfaces precached. Don't call getAttribute to see if an attribute exists, call hasAttribute instead. Prefer to loop through childNodes rather than using first/lastChild with next/previousSibling. But prefer hasChildNodes
() to childNodes.length > 0. Similarly prefer document.getElementsByTagName(aTag).item(0) != null to document.getElementsByTagName(aTag).length > 0. Prefer to use localName rather than tagName. XUL elements have many of the attributes mapped to properties. This was done for a reason, so use them! The properties are: align allowEvents contextMenu datasources dir flex height ...
OS.File.Info
Instances of OS.File.Info represent file metadata, such as the size of the file, its last modification date, etc. Due to differences between operating systems, the information available depends on the platform. Instances of OS.File.Info may be obtained by: calling global method OS.File.stat
() either from the main thread or from a worker thread; calling instance method stat
() of OS.File either from the main thread or from a worker thread. Using OS.File.Info Example: Determining if a file is a regular file The following snippet uses the main thread API to determine (asynchronously) whether some path is a regular file, or a directory, or a symbolic link: let promise = OS.File.stat(somePath); promise.then( function onSuccess(info) { // |info| is an instance of |OS.File.Info| ...
... ...
SourceMap.jsm
source map being created. The mapping object should have the following properties: generated: An object with the generated line and column positions. original: An object with the original line and column positions. source: The original source file (relative to the sourceRoot). name: An optional original token name for this mapping. SourceMapGenerator.prototype.toString
() Renders the source map being generated to a string. SourceNode SourceNodes provide a way to abstract over interpolating and/or concatenating snippets of generated JavaScript source code, while maintaining the line and column information associated between those snippets and the original source code. This is useful as the final intermediate representation a compiler might use before outputting ...
...parator between each of this source node's children. sep: The separator. SourceNode.prototype.replaceRight(pattern, replacement) Call String.prototype.replace on the very rightmost source snippet. Useful for trimming whitespace from the end of a source node, etc. pattern: The pattern to replace. replacement: The thing to replace the pattern with. SourceNode.prototype.toString
() Return the string representation of this source node. Walks over the tree and concatenates all the various snippets together to one string. SourceNode.prototype.toStringWithSourceMap(startOfSourceMap) Returns the string representation of this tree of source nodes, plus a SourceMapGenerator which contains all the mappings between the generated and original sources. The arguments are the same a...
Timer.jsm
compatible with the DOM window functions, but that can be used by code that does not have access to a DOM window (for example, JavaScript code modules or content frame scripts). ...
...me scripts). ...
WebChannel.jsm
that should be part of requests for this channel. WebChannel(String webChannelId, string originOrPermission); 2nd argument is a permission for which the permission manager will be checked to determine if the request is allowed. Note that in addition to the permission manager check, the request must be made over https. Method overview listen(Function callback); stopListening
(); send(Object message, EventTarget target); Attributes id String WebChannel id Methods listen
() Registers the callback for messages on this channel. Registers the channel itself with the WebChannelBroker. Parameters callback Callback function containing function(id, message, senderContext) parameters. id - WebChannel id of the incoming me...
...ack for messages on this channel. Registers the channel itself with the WebChannelBroker. Parameters callback Callback function containing function(id, message, senderContext) parameters. id - WebChannel id of the incoming messages message - incoming message object senderContext - incoming message context - this should be treated as an opaque object and passed to the .send
() method stopListening
() Resets the callback for messages on this channel. Removes the channel from the WebChannelBroker. Parameters None send
() Sends messages over the WebChannel id using the "WebChannelMessageToContent" event. Parameters message The message object that will be sent senderContext The senderContext parameter passed to the .listen method. Ex...
Basics
ease input">-</a> <br/> (click these control buttons to see their effects.) </div> <p> Each entry of the following matrix represents <math> <msup><mrow><mo>(</mo><mi>x</mi><mo>+</mo><mi>y</mi><mo>)</mo></mrow><mi>n</mi></msup> </math> for some <i>n</i>. When you left-click any individual entry, it should toggle between its expanded and unexpanded forms. You can also <a href="javascript:unexpand
();">unexpand all</a> or <a href="javascript:expand
();">expand all</a>. </p> <div> <math display="block"> <mtable> <mtr> <mtd> <mtable align="axis" columnalign="left left left"> <mtr> <mtd> <maction id="a11" actiontype="toggle" selection="2"> <msup> <mrow> <mo>(</mo> <mrow> <mi>x</mi> <mo>+</mo> <mi>y</mi> </mrow> <mo>)</mo> </mrow> <mn>0</mn> </msup> <mn>1</mn> </maction> </mtd> <mtd> <maction id=...
...y</mi> <mn>5</mn> </msup> </mrow> </maction> </mtd> </mtr> </mtable> </mtd> </mtr> </mtable> </math> </div> CSS Content .control { text-decoration: none; font-weight: bold; font-size: 200%; } input { color: red; } [class="inputmath"] { border: 1px dotted; } JavaScript Content function setSelection(id,value) { document.getElementById(id).setAttribute("selection",value); } function expand
() { setSelection("a11","2"); setSelection("a12","2"); setSelection("a13","2"); setSelection("a21","2"); setSelection("a22","2"); setSelection("a23","2"); setSelection("a31","2"); setSelection("a32","2"); setSelection("a33","2"); setSelection("a41","2"); setSelection("a42","2"); setSelection("a43","2"); } function unexpand
() { setSelection("a11","1"); setSelection("a12","1"); set...
MathML Torture Test
addEventListener("change", updateMathFont, false) } window.addEventListener("load", load, false); The following test ...
...eX Gyre Schola Math; } .TeXGyreTermes math { font-family: TeX Gyre Termes Math; } .XITS math { font-family: XITS Math; } JavaScript Content function updateMathFont
() { var mathFont = document.getElementById("MathFont").value; if (mathFont == "Default") { document.body.removeAttribute("class"); } else { document.body.setAttribute("class", mathFont); } } function load
() { document.getElementById("MathFont"). addEventListener("change", updateMathFont, false) } window.addEventListener("load", load, false); The following test contains sample TeX formulas from Knuth's TeX book and equivalent MathML representations. It compares the rendering by the XeTeX engine using the default Latin Modern Math font against the MathML rendering by your browser using ...
MathML In Action
addEventListener("click", zoomToggle, false); } window.addEventListener("load", load, false); Consider an interesting markup like thi...
...ow> <mn>2</mn> <mi>a</mi> </mrow> </mfrac> </mrow> </mstyle> </math> </p> JavaScript Content function zoomToggle
() { if (this.hasAttribute("mathsize")) { this.removeAttribute("mathsize"); } else { this.setAttribute("mathsize", "200%"); } } function load
() { document.getElementById("zoomableMath"). addEventListener("click", zoomToggle, false); } window.addEventListener("load", load, false); Consider an interesting markup like this { u t + f ( u ) x = 0 u ( 0 , x ) = { u - if x < 0 u + if x > 0 or other complex markups like these Ell ^ Y ( Z ; z , ? ) := ? ...
mozilla::CondVar
mozilla::CondVar is a bare wrapper around PRCondVar. Please see Introduction_to_NSPR for a high-level summary of its semantics. #include "CondVar.h" Methods Constructor CondVar(Mutex& aMutex, const char* aName) Initialize the CondVar with its associated mutex and a name to reference it by. Wait
() nsresult Wait( in PRIntervalTime interval = PR_INTERVAL_NO_TIMEOUT ); Wait on this CondVar until it is Notifyed. Notify
() nsresult Notify(void); Notify one thread waiting on this CondVar. NotifyAll
() nsresult NotifyAll(void); Notify all threads waiting on this CondVar. AssertCurrentThreadOwnsMutex
() Assert that the current thread has successfully Locked the mutex undergirding this CondVar. Does not incur a runtime penalty in optimized builds. AssertNotCurrentThreadOw...
...Does not incur a runtime penalty in optimized builds. ...
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. ...
... 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( in PRIntervalTime interval = PR_INTERVAL_NO_TIMEOUT ); Wait on the underlying monitor until it is Notifyed. Notify
() nsresult Notify(void); Notify one thread waiting on the underlying monitor. NotifyAll
() nsresult NotifyAll(void); Notify all threads waiting on the underlying monitor. See also mozilla::Monitor ...
browser.dom.window.dump.file
C:\dump.txt . It will be created if it doesn't exist yet. ...
... is set to true. Changes require an application restart. Type:string Default value:none Exists by default: no Application support: Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Status: Active; last updated 2012-03-18 Introduction: Pushed to Nightly on 2009-04-24 Bugs: bug 489938 Values The value holds the file system path for the file in which the content of the window.dump
() calls get written, e.g. C:\dump.txt . It will be created if it doesn't exist yet. The line breaks have to be in the argument of the dump function, else successive dump calls will get logged into the same line. Related browser.dom.window.dump.enabled ...
Introduction to NSPR
ation, and exit. In this case the thread would resume from the wait only to find that there's nothing to do. For example, suppose the defined rule of a function is that it should wait until there is an object available and that it should return a reference to that object. ...
...om the wait only to find that there's nothing to do. For example, suppose the defined rule of a function is that it should wait until there is an object available and that it should return a reference to that object. Writing the code as follows could potentially return a null reference, violating the invariant of the function: void *dequeue
() { void *db; enter(monitor); if ((db = delink
()) == null) { wait(condition); db = delink
(); } exit(monitor); return db; } The same function would be more appropriately written as follows: void *dequeue
() { void *db; enter(monitor); while ((db = delink
()) == null) wait(condition); exit(monitor); return db; } Caution: The semantics of PR_WaitCondVar assume that the monitor is about to be exited. ...
Logging
NSPR uses this facility itself for its own development debugging purposes. You can select events to be logged by module or level. A module is a user-defined class of log events. A level is a numeric value that indicates the seriousness of the event to be logged. You can combine module and level criteria to get highly selective logging. NSPR also provides "assert"-style macros and functions to aid in application debugging. ...
... PR_STATIC_ASSERT(5 > 4); /* NSPR 4.6.6 or newer */ myLM = PR_NewLogModule( "userStuff" ); PR_ASSERT( myLM ); PR_LOG( myLM, PR_LOG_NOTICE, ("Log a Notice %d\n", 999 )); for (i = 0; i < 10 ; i++ ) { PR_LOG( myLM, PR_LOG_DEBUG, ("Log Debug number: %d\n", i)); PR_Sleep( 500 ); } PR_LOG( myLM, PR_LOG_NOTICE, "That's all folks\n"); } /* end UserLogStuff
() */ See also NSPR Logging reference ...
Memory Management Operations
This chapter describes the global functions and macros you use to perform memory management. NSPR provides heap-based memory management functions that map to the familiar malloc
(), calloc
(), realloc
(), and free
(). Memory Allocation Functions Memory Allocation Macros Memory Allocation Functions NSPR has its own heap, and these functions act on that heap. Libraries built on top of NSPR, such as the Netscape security libraries, use these functions to allocate and free memory. ...
...at heap. Libraries built on top of NSPR, such as the Netscape security libraries, use these functions to allocate and free memory. If you are allocating memory for use by such libraries or freeing memory that was allocated by such libraries, you must use these NSPR functions rather than the libc equivalents. Memory allocation functions are: PR_Malloc PR_Calloc PR_Realloc PR_Free PR_Malloc
(), PR_Calloc
(), PR_Realloc
(), and PR_Free
() have the same signatures as their libc equivalents malloc
(), calloc
(), realloc
(), and free
(), and have the same semantics. (Note that the argument type size_t is replaced by PRUint32.) Memory allocated by PR_Malloc
(), PR_Calloc
(), or PR_Realloc
() must be freed by PR_Free
(). Memory Allocation Macros Macro versions of the memory allocation functions are a...
PR_ConnectContinue
Syntax #include <prio.h> PRStatus PR_ConnectContinue( PRFileDesc *fd, PRInt16 out_flags); Parameters The function has the following parameters: fd A pointer to a PRFileDesc object representing a socket. out_flags The out_flags field of the poll descriptor returned by PR_Poll
(). Returns If the nonblocking connect has successfully completed, PR_ConnectContinue returns PR_SUCCESS. If PR_ConnectContinue
() returns PR_FAILURE, call PR_GetError
(): - PR_IN_PROGRESS_ERROR: the nonblocking connect is still in progress and has not completed yet. The caller should poll the file descriptor for the in_flags PR_POLL_WRITE|PR_POLL_EXCEPT and retry PR_ConnectContinue later when PR_Poll
() returns. - Other errors: the nonblocking connect has failed with this error code. ...
... nonblocking connect is still in progress and has not completed yet. The caller should poll the file descriptor for the in_flags PR_POLL_WRITE|PR_POLL_EXCEPT and retry PR_ConnectContinue later when PR_Poll
() returns. - Other errors: the nonblocking connect has failed with this error code. Description Continue a nonblocking connect. After a nonblocking connect is initiated with PR_Connect
() (which fails with PR_IN_PROGRESS_ERROR), one should call PR_Poll
() on the socket, with the in_flags PR_POLL_WRITE | PR_POLL_EXCEPT. When PR_Poll
() returns, one calls PR_ConnectContinue
() on the socket to determine whether the nonblocking connect has completed or is still in progress. Repeat the PR_Poll
(), PR_ConnectContinue
() sequence until the nonblocking connect has completed. ...
PR_NormalizeTime
, so that they are in the proper range. Call this function in these situations: To normalize a time after performing arithmetic operations directly on the field values of the calendar time object. For example, if you have a ] object that represents the date 3 March 1998 and you want to say "forty days from 3 March 1998", you can simply add 40 to the tm_mday field and then call PR_NormalizeTime
(). To calculate the optional field values tm_wday and tm_yday. For example, suppose you want to compute the day of week for 3 March 1998. You can set tm_mday to 3, tm_month to 2, and tm_year to 1998, and all the other fields to 0, then call PR_NormalizeTime
() with PR_GMTParameters. On return, tm_wday (and tm_yday) are set for you. To convert from one time zone to another. For example, if th...
...of week for 3 March 1998. You can set tm_mday to 3, tm_month to 2, and tm_year to 1998, and all the other fields to 0, then call PR_NormalizeTime
() with PR_GMTParameters. On return, tm_wday (and tm_yday) are set for you. To convert from one time zone to another. For example, if the input argument time is in time zone A and the input argument params represents time zone B, when PR_NormalizeTime
() returns, time will be in time zone B. ...
NSS_3.12.1_release_notes.html
ons to get the NSPR 4.7.1 header files and shared libraries, which NSS 3.12.1 requires. NSPR 4.7.1 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.7.1/. New in NSS 3.12.1 New functions in the nss shared library: CERT_NameToAsciiInvertible (see cert.h) Convert an CERTName into its RFC1485 encoded equivalent. Returns a string that must be freed with PORT_Free
(). Caller chooses encoding rules. CERT_EncodeSubjectKeyID (see cert.h) Encode Certificate SKID (Subject Key ID) extension. PK11_GetAllSlotsForCert (see pk11pub.h) PK11_GetAllSlotsForCert returns all the slots that a given certificate exists on, since it's possible for a cert to exist on more than one PKCS#11 token. Levels of standards conformance strictness for CERT_NameToAsciiInvertible (see c...
...-pp crashes Bug 430405: Error log is not produced by CERT_PKIXVerifyCert Bug 430743: Update ssltap to understand the TLS session ticket extension Bug 430859: PKIX: Policy mapping fails verification with error invalid arguments Bug 430875: Document the policy for the order of cipher suites in SSL_ImplementedCiphers. ...
NSS 3.12.4 release notes
Bug...
...405: pkix_pl_CrlDp_Create will fail on alloc success because of a missing ! Bug 504408: pkix_pl_CrlDp_Create will always fail if dp->distPointType != generalName Bug 504456: Exploitable heap overflow in NSS shell expression (filename globbing) parsing Bug 505559: Need function to identify the one and only default internal private key slot. Bug 505561: Need a generic function a la SECMOD_OpenUserDB
() that can be used on non-softoken modules. Bug 505858: NSS_RegisterShutdown can return without unlocking nssShutdownList.lock Bug 507041: Invalid build options for VC6 Bug 507228: coreconf.dep doesn't need to contain the NSS version number Bug 507422: crash [[@ PORT_FreeArena - lg_mkSecretKeyRep] when PORT_NewArena fails Bug 507482: NSS 3.12.3 (and later) doesn't build on AIX 5.1 Bug 507937: pwdec...
NSS 3.12.5 release_notes
Parameters for these functions are used to initialize softoken. These are mostly strings used to internationalize softoken. Memory for the strings are owned by the caller, who is free to free them once NSS_ContextInit returns. If the string parameter is NULL (as opposed to empty, zero length), then the softoken default is used. These are equivalent to the parameters for PK11_ConfigurePKCS11
(). See the following struct in nss.h for details: NSSInitParametersStr Other new functions In secmod.h: SECMOD_GetSkipFirstFlag SECMOD_GetDefaultModDBFlag In prlink.h NSS_SecureMemcmp PORT_LoadLibraryFromOrigin Modified functions SGN_Update (see cryptohi.h) The parameter "input" of this function is changed from unsigned char * to const...
...ortAndReturnPrivateKey leaks an arena Bug 518446: PK11_DEREncodePublicKey leaks a CERTSubjectPublicKeyInfo Bug 518457: SECKEY_EncodeDERSubjectPublicKeyInfo and PK11_DEREncodePublicKey are duplicate Bug 522510: Add deprecated comments to key.h and pk11func.h Bug 522580: NSS uses PORT_Memcmp for comparing secret data. Bug 525056: Timing attack against ssl3ext.c:ssl3_ServerHandleSessionTicketXtn
() Bug 526689: SSL3 & TLS Renegotiation Vulnerability Documentation For a list of the primary NSS documentation pages on mozilla.org, see NSS Documentation. New and revised documents available since the release of NSS 3.11 include the following: Build Instructions NSS Shared DB Compatibility NSS 3.12.5 shared libraries are backward compatible with all older NSS 3.x shared librarie...
NSS 3.22 release notes
ation The HG tag is NSS_3_22_RTM. NSS 3.22 requires NSPR 4.11 or newer. NSS 3.22 source distributions are available on ftp.mozilla.org for secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_22_RTM/src/ New in NSS 3.22 New Functionality RSA-PSS signatures are now supported (bug 1215295) New functions PK11_SignWithMechanism
() and PK11_SignWithMechanism
() are provided to allow RSA keys to be used with PSS. Pseudorandom functions based on hashes other than SHA-1 are now supported with PBKDF (bug 554827). PK11_CreatePBEV2AlgorithmID
() now supports SEC_OID_PKCS5_PBKDF2 with cipherAlgTag and prfAlgTag set to SEC_OID_HMAC_SHA256, SEC_OID_HMAC_SHA224, SEC_OID_HMAC_SHA384, or SEC_OID_HMAC_SHA512. Enforce an ...
...y on NSS from a config file (bug 1009429) you can now add a config= line to pkcs11.txt (assuming you are using sql databases), which will force NSS to restrict the application to certain cryptographic algorithms and protocols. A complete list can be found in NSS Config Options. New Functions in pk11pub.h PK11_SignWithMechanism - This function is an extended version PK11_Sign
(). PK11_VerifyWithMechanism - This function is an extended version of PK11_Verify
(). These functions take an explicit mechanism and parameters as arguments rather than inferring it from the key type using PK11_MapSignKeyType
(). The mechanism type CKM_RSA_PKCS_PSS is now supported for RSA in addition to CKM_RSA_PKCS. The CK_RSA_PKCS_PSS mechanism takes a parameter of type CK_RSA_PKCS_...
NSS 3.27.2 Release Notes
3.27.2 requires NSPR 4.13 or newer. NSS 3.27.2 source distributions are available on ftp.mozilla.org for secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_27_2_RTM/src/ New in NSS 3.27.2 New Functionality No new functionality is introduced in this release. This is a patch release to address a memory leak in the SSL_SetTrustAnchors
() function. Notable Changes in NSS 3.27.2 The SSL_SetTrustAnchors
() function is used to set the distinguished names that an NSS server includes in its TLS CertificateRequest message. If this function is not used, NSS will include the distinguished names for all trust anchors installed in the database. This can be a lengthy list. Previous versions of NSS leaked the memory used to store disti...
... This release fixes that error. Bugs fixed in NSS 3.27.2 The following bug has been fixed in NSS 3.27.2: Bug 1318561 - SSL_SetTrustAnchors leaks Compatibility NSS 3.27.2 shared libraries are backward compatible with all older NSS 3.x shared libraries. ...
NSS Developer Tutorial
atting Line length should not exceed 80 characters. Indentation level is 4. Tabs are used heavily in many NSS source files. Try to stay consistent when you modify existing code. The proper use of tabs has often been confusing for new NSS developers, so in nss/lib/ssl, we're gradually removing the use of tabs. Curly braces: both of the following styles are allowed: if (condition) { action1
(); } else { action2
(); } Or: if (condition) { action1
(); } else { action2
(); } The former style is more common. When modifying existing code, try to stay consistent. In new code, prefer the former style, as it conserves vertical space. When a block of code consists of a single statement, NSS doesn't require curly braces, so both of these examples are fine: if (condition) { acti...
...} else { action2
(); } Or: if (condition) { action1
(); } else { action2
(); } The former style is more common. When modifying existing code, try to stay consistent. In new code, prefer the former style, as it conserves vertical space. When a block of code consists of a single statement, NSS doesn't require curly braces, so both of these examples are fine: if (condition) { action
(); } Or: if (condition) action
(); although the use of curly braces is more common. Multiple-line comments should be formatted as follows: /* * Line1 * Line2 */ or /* ** Line 1 ** Line 2 */ The following styles are also common, because they conserve vertical space: /* Line1 * Line2 */ or /* Line1 ** Line2 */ or /* Line1 * Line2 */ Naming Public functions are named...
NSS Sample Code Utilities_1
e, &stbuf); return stbuf.st_size; } /* * ReadDERFromFile */ SECStatus ReadDERFromFile(SECItem *der, const char *inFileName, PRBool ascii) { SECStatus rv = SECSuccess; PRFileDesc *inFile = NULL; inFile = PR_Open(inFileName, PR_RDONLY, 0); if (!inFile) { PR_fprintf(PR_STDERR, "Failed to open file \"%s\" (%ld, %ld).\n", inFileName, PR_GetError
(), PR_GetOSError
()); rv = SECFailure; goto cleanup; } if (ascii) { /* First convert ascii to binary */ SECItem filedata; char *asc, *body; /* Read in ascii data */ rv = FileToItem(&filedata, inFile); asc = (char *)filedata.data; if (!asc) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); ...
...t no trailer\n"); PORT_Free(filedata.data); rv = SECFailure; goto cleanup; } } else { body = asc; } /* Convert to binary */ rv = ATOB_ConvertAsciiToItem(der, body); if (rv) { PR_fprintf(PR_STDERR, "error converting ascii to binary %s\n", PORT_GetError
()); PORT_Free(filedata.data); rv = SECFailure; goto cleanup; } PORT_Free(filedata.data); } else { /* Read in binary der */ rv = FileToItem(der, inFile); if (rv) { PR_fprintf(PR_STDERR, "error converting der \n"); rv = SECFailure; } } cleanup: if (inFile) { PR_Close(inFile...
Utilities for nss samples
e, &stbuf); return stbuf.st_size; } /* * ReadDERFromFile */ SECStatus ReadDERFromFile(SECItem *der, const char *inFileName, PRBool ascii) { SECStatus rv = SECSuccess; PRFileDesc *inFile = NULL; inFile = PR_Open(inFileName, PR_RDONLY, 0); if (!inFile) { PR_fprintf(PR_STDERR, "Failed to open file \"%s\" (%ld, %ld).\n", inFileName, PR_GetError
(), PR_GetOSError
()); rv = SECFailure; goto cleanup; } if (ascii) { /* First convert ascii to binary */ SECItem filedata; char *asc, *body; /* Read in ascii data */ rv = FileToItem(&filedata, inFile); asc = (char *)filedata.data; if (!asc) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); ...
...t no trailer\n"); PORT_Free(filedata.data); rv = SECFailure; goto cleanup; } } else { body = asc; } /* Convert to binary */ rv = ATOB_ConvertAsciiToItem(der, body); if (rv) { PR_fprintf(PR_STDERR, "error converting ascii to binary %s\n", PORT_GetError
()); PORT_Free(filedata.data); rv = SECFailure; goto cleanup; } PORT_Free(filedata.data); } else { /* Read in binary der */ rv = FileToItem(der, inFile); if (rv) { PR_fprintf(PR_STDERR, "error converting der \n"); rv = SECFailure; } } cleanup: if (inFile) { PR_Close(inFile...
Necko Architecture
If you want to move data asynchronously you need to be able to receive callbacks using an implementation of nsIStreamListener. An nsIStreamListener is told when the URI transaction has "started," when data is available (in the case of reading data), and when it has "stopped." It is up to the nsIStreamListener implementation to decide what to do with these various notifications. The OnDataAvailable
() notification provides a chance for the nsIStreamListener to actually retrieve data that the channel has acquired. One of the arguments to the OnDataAvailable
() notification is an nsIInputStream (which can be considered the underlying data). Streams Necko represents data in the form of streams (nsIBaseStream is the root interface. nsIInputStream is read from. nsIOutputStream is written to). Str...
... be located somewhere else. The point is that streams provide a loose interface for data access. If you initiate a synchronous transfer on a channel, you are handed back a stream that you can read or write from or to. If you initiate an asynchronous transfer, you receive callbacks that notify you when things are happening. In the case of an asynchronous read... when you receive the OnDataAvailable
() callback, you are handed an nsIInputSteam which you can read the data from (you will more than likely need to be able to handle multiple OnDataAvailable
() callbacks, buffering the data you receive as necessary). The transaction is not complete until you receive an "stopped" notification. Transports Underlying I/O functionality has been consolidated into "transports." There is a transport for e...
Rhino overview
ring with the URL of the server that supplied the script, or an object that contains a representation of the signers of a piece of code for certificate-based security policies. When JavaScript code attempts a restricted action, the security domain can be retrieved in the following manner. The class context should be obtained from the security manager (see java.lang.SecurityManager.getClassContext
()). Then, the class of the code that called to request the restricted action can be obtained by looking an appropriate index into the class context array. If the caller is JavaScript the class obtained may be one of two types. First, it may be the class of the interpreter if interpretive mode is in effect. Second, it may be a generated class if classfile generation is supported. An embedding can di...
... the restricted action can be obtained by looking an appropriate index into the class context array. If the caller is JavaScript the class obtained may be one of two types. First, it may be the class of the interpreter if interpretive mode is in effect. Second, it may be a generated class if classfile generation is supported. An embedding can distinguish the two cases by calling isInterpreterClass
() in the Context class. If it is the interpreter class, call the getInterpreterSecurityDomain
() method of Context to obtain the security domain of the currently executing interpreted script or function. Otherwise, it must be a generated class, and an embedding can call getSecurityDomain
() in the class implementing SecuritySupport. When the class was defined and loaded, the appropriate security doma...
Performance Hints
n does not modify global variables result and i. However, if you don't intend for any other function to access these variables, then storing them globally is probably wrong anyway (what if you called another function that had a loop like the one in sum!). Arrays Use the forms of the Array constructor that specify a size or take a list of initial elements. For example, the code var a = new Array
(); for (var i=0; i < n; i++) a[i] = i; could be sped up by changing the constructor call to new Array(n). A constructor call like that indicates to the runtime that a JavaScript array should be used for the first n entries of the array. Similarly, new Array("a", "b", "c") or ["a", "b", "c"] will cause a 3-element array to be allocated to hold the contents of the JavaScript array. eva...
...ecuted must be compiled. Constructing a new function object can be slow for the same reason, while function expressions are more efficient because the function can be compiled. For example, the code function MyObject(a) { this.s = a; this.toString = new Function("return this.s"); } could be written more efficiently as function MyObject(a) { this.s = a; this.toString = function
() { return this.s } } Beginning with Rhino 1.4 Release 2, code passed to eval and new Function will be interpreted rather than compiled to class files. with Using the with statement prevents the compiler from generating code for fast access to local variables. You're probably better off explicitly accessing any properties of the object. ...
The JavaScript Runtime
f JavaScript source to class files is supported. It is possible to specify the class files as well as the packages to generate into. Types and Values There are six fundamental types in JavaScript. These types are implemented with the following Java types and values: JavaScript fundamental type Java type Undefined A singleton object defined by Context.getUndefinedType
() Null null Boolean java.lang.Boolean Number java.lang.Number, that is, any of java.lang.Byte, java.lang.Short, java.lang.Integer, java.lang.Float, or java.lang.Double. Not java.lang.Long, since a double representation of a long may lose precision. String java.lang.CharSequence (java.lang.String or org.mozilla.javascript.ConsString) Object ...
...Similarly, values of numbers that do not fix in integers (like 1.1 and 0x100000000) must be converted to strings. Defining Host Objects Host objects are JavaScript objects that provide special access to the host environment. For example, in a browser environment, the Window and Document objects are host objects. The easiest way to define new host objects is by using ScriptableObject.defineClass
(). This method defines a set of JavaScript objects using a Java class. Several of the examples define host objects this way. If the services provided by defineClass are insufficient, try other methods of ScriptableObject and FunctionObject, such as defineProperty and defineFunctionProperties. Contexts and Threads Every thread that executes JavaScript must have an associated Context. Multiple thr...
Garbage collection
removal will mark it (it's not being removed, just read). So we barrier the read instead; if you ever read a weak reference in the middle of an ongoing incremental GC, then the target of the weak ref will be marked. Implementation details Write barriers have a runtime cost, so SpiderMonkey tries to skip them when an incremental GC cycle is not active. Each Zone has a flag needsIncrementalBarrier
() that indicates whether barriers are required. For each type T such that fields of type T* need a write barrier, there is a functionT::writeBarrierPre(old). For example, fields of type JSObject* need a write barrier, so there is a function JSObject::writeBarrierPre(JSObject* old). If zone->needsIncrementalBarrier
(), then writeBarrierPre
() marks old. That's it. The class Heap<T> is provided to ma...
... GC thing (it is essentially a Cell** that the GC knows about.) root A starting point to the GC graph traversal, a root is known to be alive for some external reason (one other than being reachable by some other part of the GC heap.) weak pointer In common CS terminology, a weak pointer is one that doesn't keep the pointed-to value live for GC purposes. Typically, a weak pointer value has a get
() method that returns a null pointer if the object has been GC'd. In Gecko/SpiderMonkey, a weak pointer is a pointer to an object that can be GC'd that is not marked through. Thus, there is no get
() method and no protection against the pointed-to value getting GC'd--the programmer must ensure that the lifetime of the pointed-to object contains the lifetime of the weak pointer. TODO make sure this i...
JS::AutoIdArray
yntax AutoIdArray(JSContext *cx, JSIdArray *ida); Name Type Description cx JSContext * The context in which to add the root. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. ida JSIdArray * A pointer to JSIdArray to take the ownership. Methods Method Description bool operator!
() const Return true if this has no owned array. jsid operator[](size_t i) const Return a jsid in specified index of the owned array. size_t length
() const Return the length of the owned array. JSIdArray *steal
() Return the owned array and release the ownership. Description JS::AutoIdArray takes the ownership of JSIdArray, and frees it in destructor by ...
... owned array. JSIdArray *steal
() Return the owned array and release 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::HandleValueArray
values JS::AutoValueVector & Elements of newly created array. values JS::AutoValueArray & Elements of newly created array. args JS::CallArgs & Elements of newly created array. len size_t (fromMarkedLo...
...of sub array of values. elements JS::Value * (fromMarkedLocation only) A pointer to the first element of an array of JS::Value. values JS::HandleValueArray (subarray only) An array to get sub array. startIndex size_t (subarray only) An index of the first element of subarray of values. Methods Method Description size_t length
() const Returns the length of the array. const Value *begin
() const Returns the pointer to the first element of the array. JS::HandleValue operator[](size_t i) const Returns i-th element of the array. Description JS::HandleValueArray is a handle to an array of rooted values. This is useful as a parameter type, or a temporal local variable for it. See Also MXR ...
JS::MutableHandle
ticle covers features introduced in SpiderMonkey 17 Reference to a T that has been rooted elsewhere. The underlying storage can be changed. This is useful for outparams. Syntax bool someFunction(JSContext *cx, JS::MutableHandle<T> outParam) { ... } Methods Here, ptr represents the private member of JS::MutableHandle<T>, typed with T *. Method Description const T &get
() const Returns *ptr. operator const T&
() const T operator->
() const T *address
() Returns ptr. void set(T v) Sets the value of *ptr to v. Description JS::MutableHandle<T> is a non-const reference to JS::Rooted<T>. It is used in the same way as JS::Handle<T> and includes a |set(const T &v)| method to allow updating the value of the ref...
... void set(T v) Sets the value of *ptr to v. Description JS::MutableHandle<T> is a non-const reference to JS::Rooted<T>. It is used in the same way as JS::Handle<T> and includes a |set(const T &v)| method to allow updating the value of the referenced JS::Rooted<T>. A JS::MutableHandle<T> can be created from a JS::Rooted<T> by using |JS::Rooted<T>::operator&
()|. If you want to add additional methods to JS::MutableHandle for a specific specialization, define a js::MutableHandleBase<T> specialization containing them. There are typedefs available for the main types: namespace JS { typedef MutableHandle<JSFunction*> MutableHandleFunction; typedef MutableHandle<jsid> MutableHandleId; typedef MutableHandle<JSObject*> MutableHandleObject; typedef ...
JSClass
ed with the object. If objects of this class do not need finalization, use NULL. checkAccess JSCheckAccessOp Optional method for access checks. Implements JS_CheckAccess. If your application does not use the JSAPI's security features, use NULL. Obsolete since JSAPI 29 call JSNative This is called when a script calls an object as though it were a function: obj
(). If objects of your class shouldn't be callable, use NULL. Most objects are not callable. hasInstance JSHasInstanceOp Pointer to an optional hasInstance method for this object. If you do not provide a method for hasInstance, set this pointer to NULL. construct JSNative This is called when a script uses an object as though it were a constructor: new obj
(). If objects...
...(argc, vp); JSObject *obj = JS_NewObjectForConstructor(cx, &printer_class, args); /* SpiderMonkey 31 or older * JSObject *obj = JS_NewObjectForConstructor(cx, &printer_class, vp); */ if (!obj) return false; MyPrinter *p = new MyPrinter; if (p == NULL) { JS_ReportOutOfMemory(cx); return false; } JS_SetPrivate(cx, obj, p); args.rval
().setObject(*obj); /* SpiderMonkey 31 or older * JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj)); */ return true; } { JS_InitClass(cx, global, JS::NULL
(), &printer_class, printer_construct, 1, NULL, NULL, NULL, NULL); } See also MXR ID Search for JSClass JSClass.flags JS_GetClass JS_InitClass JS_NewObject JS_NewObjectForConstructor JS_InstanceOf bug 638291 ...
JSNative
Script code. Syntax typedef bool (* JSNative)(JSContext *cx, unsigned argc, JS::Value *vp); Name Type Description cx JSContext * The context in which the native function is being called. Provides request. In JS_THREADSAFE builds, the JavaScript engine calls this callback only from within an active request on cx. The callback does not need to call JS_BeginRequest
()). argc unsigned The number of arguments supplied to the function by the caller (as opposed to, say, the number of arguments the function is specified to take in its JSFunctionSpec). vp JS::Value * The arguments, the this argument, the return-value slot, and the callee Function object are accessible through this pointer using macros described below. Description...
... deprecated. The behavior of a JSNative is implemented using a JS::CallArgs structure Added in SpiderMonkey 17. (This structure is now provided in "js/CallArgs.h" Added in SpiderMonkey 24 as well as through "jsapi.h".) This structure encapsulates access to the callee function, this, the function call's arguments, and the eventual return value. On success, the callback must set JS::CallArgs::rval
() or call JS_SET_RVAL (at least once) and return true. Otherwise it should either report an error (using e.g. JS_ReportError or JS_ReportOutOfMemory) or raise an exception (using JS_SetPendingException), and the callback must return false. (Returning false without reporting an error or raising an exception terminates the script with an uncatchable error. This has limited use cases; it's used to imp...
JSObjectOps.defaultValue
here. Description The JSObjectOps.defaultValue callback corresponds to the [[DefaultValue]] method defined in ECMA 262-3 ?8.6.2.6. Many expressions in the ECMAScript language, such as a+b, involve implicit conversion of the operands using [[DefaultValue]]. The default [[DefaultValue]] behavior for ordinary objects is as described in ES5 ?8.12.8. It calls the JavaScript methods obj.valueOf
() and/or obj.toString
(). Provide a custom JSObjectOps.defaultValue callback to implement customized [[DefaultValue]] behavior. The JSClass.convert callback should convert obj to the given type, returning JS_TRUE with the resulting value in *vp on success, and returning JS_FALSE on error or exception. On success, *vp must be a primitive value: per ES5 ?8.12.8, every object "must ensure that its [[D...
... exception. On success, *vp must be a primitive value: per ES5 ?8.12.8, every object "must ensure that its [[DefaultValue]] internal method can return only primitive values." Debug builds of SpiderMonkey will assert if a convert callback is successful but leaves *vp holding a primitive value. JS_ConvertStub implements the default behavior for the JSClass.convert hook, which is to call obj.valueOf
() and obj.toString
() in accordance with the algorithm in ES5 ?8.12.8. ...
JSPrincipals
JSBool (*)(JSContext *, JSPrincipals *) Flag indicating whether principals are enabled globally. Obsolete since JSAPI 12 destroy void (*)(JSContext *, JSPrincipals *) Pointer to the function that decrements the reference count and possibly frees the principals if they are no longer in use. Obsolete since JSAPI 13 Methods Name Description void dump
() This is not defined by the JS engine but should be provided by the embedding. Added in SpiderMonkey 17 Description JSPrincipals is the abstract base class of all principals objects, the objects that identify the source of a function or script and are used to determine its privileges. A principals object is like a Java CodeSource. JSPrincipals could be passed into the JS engine through...
...he engine through the JS_...ForPrincipals functions. Some examples of security-enhanced API call are JS_CompileScriptForPrincipals, JS_CompileFunctionForPrincipals, and JS_EvaluateScriptForPrincipals. These functions ensure that the given JSPrincipals object is indelibly associated not only with the script being compiled or evaluated, but with all functions ever created by that script or code eval
()-ed by it. codebase points to the common codebase for this object or script. Only objects and scripts that share a common codebase can interact. getPrincipalArray is a pointer to the function that retrieves the principals for this object or script. globalPrivilegesEnabled is a flag that indicates whether principals are enabled globally. refcount is the reference count. This is used for memory ...
JS_DumpHeap
void *thingToFind, size_t maxDepth, void *thingToIgnore); Name Type Description cx JSContext * Pointer to a JS context. Every JSContext is permanently associated with a JSRuntime; each JSRuntime contains a GC heap. fp FILE * File for the dump output. startThing void * NULL or a pointer to a GC thing (use JS::Value::toGCThing
() to obtain a pointer to pass here). When null, dump all things reachable from the runtime roots. When non-null, dump only things reachable from the object indicated. startKind JSGCTraceKind Trace kind of startThing, if startThing is not null. Must be JSTRACE_OBJECT when startThing is null. thingToFind void * NULL or a pointer to a GC thing. If this is non-null, JS_Dum...
...n tracing a thing, the GC needs to know about the layout of the object it is looking at. There are a fixed number of different layouts that the GC knows about. The "trace kind" is a static map which tells which layout a GC thing has. Although this map is public, the details are completely hidden. Not all of the matching C++ types are exposed, and those that are, are opaque. See JS::Value::gcKind
() and JSTraceCallback in <codde>Tracer.h</codde> for more details. See Also bug 378261 bug 1122842 ...
JS_GetLocaleCallbacks
If EXPOSE_INTL_API is defined, Intl API is used instead. JSLocaleToUnicode Convert locale specific string to Unicode string. Description JS_SetLocaleCallbacks establishes locale callbac...
...andleString src1, JS::HandleString src2, JS::MutableHandleValue rval); typedef bool (* JSLocaleToUnicode)(JSContext *cx, const char *src, JS::MutableHandleValue rval); Type Description JSLocaleToUpperCase Implementation of String.prototype.toLocaleUpperCase
() function. JSLocaleToLowerCase Implementation of String.prototype.toLocaleLowerCase
() function. JSLocaleCompare Implementation of String.prototype.localeCompare
() function. If EXPOSE_INTL_API is defined, Intl API is used instead. JSLocaleToUnicode Convert locale specific string to Unicode string. Description JS_SetLocaleCallbacks establishes locale callbacks. The pointer must persist as long as the JSRuntime. Passing nullptr restores the default behav...
JS_SetBranchCallback
* Pointer to a JSContext which the callback may use to call into JSAPI functions. For example, the callback my call JS_MaybeGC(cx). This is the context that is currently executing the code that triggered the callback. Provides request. In JS_THREADSAFE builds, the JavaScript engine calls this callback only from within an active request on cx. ...
...red the callback. Provides request. In JS_THREADSAFE builds, the JavaScript engine calls this callback only from within an active request on cx. The callback does not need to call JS_BeginRequest
()). script JSScript The script that is running. This is guaranteed to be non-null, unless the JSOPTION_NATIVE_BRANCH_CALLBACK option has been enabled for the context cx using JS_SetOptions
(). If the callback returns JS_TRUE, the JS engine continues to execute the script. If the callback raises an exception using JS_SetPendingException
() and returns JS_FALSE, then the JavaScript engine propagates the exception to the script that was executing at the time. If the callback returns JS_FALSE without raising an exception, then the JavaScript engine immediately stops running the sc...
JS_SetOptions
logical OR of zero or more constants from the following table: Option Description JSOPTION_EXTRA_WARNINGS Warn on dubious practice. MXR ID Search for JSOPTION_EXTRA_WARNINGS JSOPTION_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. M...
...ing converted to error reports. MXR ID Search for JSOPTION_DONT_REPORT_UNCAUGHT JSOPTION_RELIMIT Added in SpiderMonkey 1.8 Throw an exception if a regular expression backtracks more than n3 times, where n is the length of the input string. MXR ID Search for JSOPTION_RELIMIT JSOPTION_ANONFUNFIX Added in SpiderMonkey 1.8 Disallow function
() {} in statement context, per ECMA-262 Edition 3. This behavior is the default in releases where this option has been removed. MXR ID Search for JSOPTION_ANONFUNFIX JSOPTION_JIT Obsolete since JSAPI 11 Added in SpiderMonkey 1.8.1 Enables the JIT compilation of code in the context. Note that you may currently (Jan 2009) experience bugs with this option enabled. MXR ID ...
JS_ValueToString
decimal representation of the number, possibly using exponential notation. Otherwise v is an object. JS_ValueToString uses the steps below to convert it to a string. If at any point an error or exception occurs, or conversion succeeds, the rest of the steps are skipped. (This behavior is implemented by v's JSObjectOps.defaultValue method, so host objects can override it all.) If v.toString
() is a function, it is called. If that method returns a primitive value, the value is converted to a string as described above and conversion succeeds. Otherwise, the resulting object's JSClass.convert callback is called. For standard classes, this is JS_ConvertStub, which simply calls v.valueOf
() if present. If the convert callback produces a primitive value, the value is converted to a string...
... The resulting JSString is subject to garbage collection. Protect it using a local root, an object property, or the JS_AddRoot function. ...
SpiderMonkey 1.8
ail, bugzilla, or IRC.) Alternatively, you can install MozillaBuild and run the command make -f Makefile.ref in the js/src directory. SpiderMonkey 1.8 does not include the new TraceMonkey JIT or the configure-based build system, both of which are (a) pretty darn awesome and (b) coming in SpiderMonkey 1.8.1. On to the fun stuff. New JavaScript language features JavaScript 1.8 adds Array.reduce
() and reduceRight
(), expression closures, and generator expressions. There is also one obscure non-backwards-compatible change. For details, see New in JavaScript 1.8. New JSAPI features It has been a couple years since SpiderMonkey 1.7 was released, and many improvements have been made to the JSAPI. However, one of the most important advances for JSAPI application developers is that the document...
...hrowStopIteration throws the appropriate StopIteration exception object for the given context. Two new context options can be used with JS_SetOptions: JSOPTION_RELIMIT, which causes extremely long-running regular expression searches to fail with an error, and JSOPTION_ANONFUNFIX, which bans anonymous functions from appearing anyplace where a statement could appear, such as in the argument to eval
(). Functions that were JS_THREADSAFE-only in SpiderMonkey 1.7 (JS_BeginRequest, for example) are now present, but do nothing, in non-JS_THREADSAFE builds. This is to help applications share and reuse code regardless of whether they use threads. There are two new JSExtendedClass hooks, JSExtendedClass.iteratorObject and JSExtendedClass.wrappedObject. Both are documented but obscure. Many new mem...
TPS Tests
fails. Logger.AssertEqual(val1, val2, msg) Asserts that val1 is equal to val2, otherwise an exception is thrown and the test fails. Custom functions You can also write your own functions to be called as actions. For example, consider the first action in the phase above: [Bookmarks.add, bookmarks_initial] You could rewrite this as a custom function so as to add some custom logging: [async
() => { Logger.logInfo("adding bookmarks_initial"); await Bookmarks.add(bookmarks_initial); }] Note that this is probably best used for debugging, and new tests that want custom behavior should add it to the TPS addon so that other tests can use it. Example Test Here's an example TPS test to tie it all together. // Phase declarations var phases = { "phase1": "profile1", "phas...
...th --debug. This will enable much more verbose logging in all engines. Check the tps.log file written out after TPS runs. It will include log output written by the python driver, which includes information about where the temporary profiles it uses are stored. run test_sync.js. This test generally validates your tps setup and does a light test of a few engines. Comment out the goQuitApplication
() calls in services/sync/tps/extensions/tps/modules/tps.jsm (remember to undo this later!). You will have to manually quit the browser at each phase, but you will be able to inspect the browser state manually. Using this technique in conjunction with aboutsync is helpful. (Note that the python testrunner will generally still kill firefox after a TPS test runs for 5 or so minutes, so it's o...
Using the Places history service
such as "chrome:" URIs, are not stored when addURI is called. This function allows you to determine whether it will be or not. Advanced querying See Querying Places for more detailed examples on how to used the advanced querying functionality of NavHistory. nsINavHistoryService.getNewQuery: Returns a new query object initialized to the default values. You can pass this to executeQueries
(). nsINavHistoryService.getNewQueryOptions: Returns a new query options object initialized to the default values. You can pass this to executeQueries
(). nsINavHistoryService.executeQuery: Runs a query with a single query object and options. All the parameters set on the query object will be ANDed together. nsINavHistoryService.executeQueries: Runs multiple query objects as a query. The parameter...
... nsINavHistoryService.queriesToQueryString: Returns a serialized version of the queries as a "place:" URI. You should not count on this format, always use this function instead of hard-coding your own query strings. ...
The Publicity Stream API
on> ] } ]): Applications should call this method when an user-initiated activity deemed attractive to potential consumers occurs. This spawns a doorhanger which allows the user to specify which users can view the activity, and (following successful login and authorization with the stream server) registers the activity in a stream at [ADDRESS]. This stream can be pulled down by getPublicityStream
() and helps determine the results for getUserRecommendedApps
(). example use cases: 'Adam got a high score in Mafia Wars', 'Bethany bought a plane ticket to the Caribbean', etc. activity is an object, formatted as per the FIXME: deadLinkActivity Streams open specification. onsuccess is a callback that will be invoked with no arguments if the activity is successfully posted. onerror is an err...
...er refuses to publicize the activity permissionDenied - if the publicizing site is not allowed to post to the publicity stream networkError - if the publicity server is unreachable activityParseError - if the activity contains syntax errors (not proper JSON) invalidActivity - if the activity contains semantic errors (i.e. missing required properties) Finally, the publicizeActivity
() function will throw an exception if required arguments are missing, or if unsupported arguments are present. getPublicityStream( onsuccess: <function>, { [ onerror: <function> ], [ for_apps: <list> ], [ since: <Date> ], [ before: <Date> ], [ count: <int> ]): Provides a means for a web store to receive a list of the current user's socially relevant app activity by being called from an orig...
extISessionStorage
rage. ...
... Attributes Attribute Type Description events readonly attribute extIEvents The events object for the storage supports: "change" Methods has
() Determines if a storage item exists with the given name. boolean has(in AString aName) Parameters aName The name of an item Return value true if an item exists with the given name, false otherwise. set
() Sets the value of a storage item with the given name. void set(in AString aName, in nsIVariant aValue) Parameters aName The name of an item Return value get
() Gets the value of a storage item with the given name. Returns a default value if the item does not exist. nsIVariant get(in AString aName, in nsIVariant aDefaultValue) Parameters aName The name of an item Return value...
Component Internals
, the event you observe cannot be used to implement something like a "Are you sure you want to Quit?" dialog. Rather, the shutdown event gives the component or embedding application a last chance to clean up any leftovers before they are released. In order to support something like an "Are you sure you want to quit" dialog, the application needs to provide a higher-level event (e.g., startShutdown
()) which allows for cancellation. Note also that XPCOM services may deny you access once you have received the shutdown notification. It is possible that XPCOM will return an error if you access the nsIServiceManager at that point, for example, so you may have to keep a reference-counted pointer to the service you are interested in using during this notification. Component Loaders Components ca...
...ry object. At this layer of the XPCOM Component Library, the factory objects are factories for the core XPCOM objects of the layer below. One more layer outward is the module code. The module interface provides yet another abstraction - this time of the factories - and allows for multiple factory objects. From the outside of the component library, there is only the single entry point, NSGetModule
(). This point of entry may fan out to any number of factories, and from there, to any number of XPCOM objects. The factory design pattern in XPCOM is represented by the nsIFactory interface. The module layer is represented by the nsIModule interface. Most component libraries only need these two interfaces, along with the nsISupports interface, to have XPCOM load, recognize, and use their core obje...
Inheriting from implementation classes
with Java's interfaces). Example problem You have interfaces A and B, B inherits from A, and you have implementation classes for both A and B, and you want the implementation class for B to inherit from the implementation class for A. The latter is the problem. The lacking virtual in the generated IB C++ abstract class doesn't make things easier. So, in code: IDL: interface IA { void funcA
(); } interface IB : IA { void funcB
(); } interface IC : IB { void funcC
(); } C++ implementation: class A : public IA { ??? } class B : public A, public IB { ??? } class C : public B, public IC { ??? } Example solution A.h, as usual: class A : public IA { ... NS_DECL_ISUPPORTS NS_DECL_IA } A.cpp, as usual: NS_IMPL_ISUPPORTS1(A, IA) NS_IMETHODIMP A::funcA
() { ... } B...
... A : public IA { ... NS_DECL_ISUPPORTS NS_DECL_IA } A.cpp, as usual: NS_IMPL_ISUPPORTS1(A, IA) NS_IMETHODIMP A::funcA
() { ... } B.h: class B : public A, public IB { ... NS_DECL_ISUPPORTS_INHERITED NS_FORWARD_IA(A::) // need to disambiguate NS_DECL_IB } B.cpp: NS_IMPL_ISUPPORTS_INHERITED1(B, A, IB) // this, superclass,added ifaces NS_IMETHODIMP B::funcB
() { ... } C.h: class C : public B, public IC { ... NS_DECL_ISUPPORTS_INHERITED NS_FORWARD_IA(B::) NS_FORWARD_IB(B::) NS_DECL_IC } C.cpp: NS_IMPL_ISUPPORTS_INHERITED1(C, B, IC) NS_IMETHODIMP C::funcC
() { ... } Threadsafe If you want to make this threadsafe, you can replace NS_IMPL_ISUPPORTS1(A, IA) with NS_IMPL_THREADSAFE_ISUPPORTS1(A, IA) in the base implementatio...
XPCOM guide
Mozilla code uses a C++ class hierarchy to pass string data, rather than using raw pointers. This guide documents the string classes which are visible to code within the Mozilla codebase (code which is linked into libxul). ...
...a C++ class hierarchy to pass string data, rather than using raw pointers. This guide documents the string classes which are visible to code within the Mozilla codebase (code which is linked into libxul). mozilla::services namespaceThe services C++ namespace offers an easy and efficient alternative for obtaining a service as compared to the indirect XPCOM approach: GetService
(), CallGetService
(), etc methods are expensive and should be avoided when possible.Receiving startup notificationsSometimes it's necessary for XPCOM components to receive notifications as to the progress of the application's startup process, so they can start new services at appropriate times, for example.XPCOM array guideMozilla has many array classes because each array is optimized for a particular usage pattern. ...
Components.classes
ance, if the contract ID represents a service. A new XPCOM component instance can be created from the returned class object as follows: var obj = Components.classes["@mozilla.org/supports-array;1"] .createInstance(Components.interfaces.nsISupportsArray); which is a shortcut to var obj = Components.classes["@mozilla.org/supports-array;1"] .createInstance
(); obj.QueryInterface(Components.interfaces.nsISupportsArray); If you don't provide a specific interface to createInstance
(), it will return an XPConnect wrapper for the component, which only exposes the methods of the nsISupports interface (and under certain circumstances the special wrappedJSObject property). To access a service (a singleton component, only single instance of which exists at ...
...You still have to provide the interface name each time you create an instance, which is not necessary when using Components.Constructor. Determining if a component has to be instantiated or used as a service In the general case it is not possible to programmatically determine if a given component has to be instantiated or used as a service. Often, this is stated in the document...
Components.utils.evalInSandbox
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). ...
...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). ...
nsICache
ines the device(s) to which it belongs. See nsICacheSession and nsICacheEntryDescriptor for more details. Requires the cache entry to reside in persistent, reliable storage for offline use. NOT_STREAM_BASED 0 All entries for a cache session are stored as streams of data or as objects. This constant specify that cache session is not a stream based entry when calling nsICacheService.createSession
() method. STREAM_BASED 1 All entries for a cache session are stored as streams of data or as objects. This constant specify that cache session is a stream based entry when calling nsICacheService.createSession
() method. NON_BLOCKING 0 The synchronous OpenCacheEntry
() may be blocking or non-blocking. If a cache entry is waiting to be validated by another cache descriptor (so no new cache descrip...
... session are stored as streams of data or as objects. This constant specify that cache session is a stream based entry when calling nsICacheService.createSession
() method. NON_BLOCKING 0 The synchronous OpenCacheEntry
() may be blocking or non-blocking. If a cache entry is waiting to be validated by another cache descriptor (so no new cache descriptors for that key can be created), OpenCacheEntry
() will return NS_ERROR_CACHE_WAIT_FOR_VALIDATION in non-blocking mode. If the cache entry is validated, then a descriptor for that entry will be created and returned. If the cache entry was doomed, then a descriptor will be created for a new cache entry for the key. BLOCKING 1 The synchronous OpenCacheEntry
() may be blocking or non-blocking. In blocking mode, it will wait until the cache entry fo...
nsICacheEntryInfo
Read only. dataSize unsigned long Get the cache entry data size. Read only. deviceID string Get the id for the device that stores this cache entry. Read only. expirationTime PRUint32 Get the expiration time of the cache entry (in seconds since the Epoch). ...
.... fetchCount long Get the number of times the cache entry has been opened. Read only. key ACString Get the key identifying the cache entry. Read only. lastFetched PRUint32 Get the last time the cache entry was opened (in seconds since the Epoch). Read only. lastModified PRUint32 Get the last time the cache entry was modified (in seconds since the Epoch). Read only. Methods isStreamBased
() This method finds out whether or not the cache entry is stream based. boolean isStreamBased
(); Parameters None. Return value Returns true if the cache entry is stream based, otherwise returns false. See also nsICache nsICacheVisitor ...
nsICacheListener
cache/nsICacheListener.idlScriptable This interface is a cache listener. Inherits from: nsISupports Last changed in Gecko 14 (Firefox 14 / Thunderbird 14 / SeaMonkey 2.11) Method overview void onCacheEntryAvailable(in nsICacheEntryDescriptor descriptor, in nsCacheAccessMode accessGranted, in nsresult status); void onCacheEntryDoomed(in nsresult status); Methods onCacheEntryAvailable
() This method is called when the requested access (or appropriate subset) is acquired. The status parameter equals NS_OK on success. See nsICacheService for accessGranted values. void onCacheEntryAvailable( in nsICacheEntryDescriptor descriptor, in nsCacheAccessMode accessGranted, in nsresult status ); Parameters descriptor The cache entry descriptor. accessGranted The cache access mode. st...
...set) is acquired. The status parameter equals NS_OK on success. See nsICacheService for accessGranted values. void onCacheEntryAvailable( in nsICacheEntryDescriptor descriptor, in nsCacheAccessMode accessGranted, in nsresult status ); Parameters descriptor The cache entry descriptor. accessGranted The cache access mode. status The status of the cache entry availability. onCacheEntryDoomed
() This method is called when the processing started by nsICacheSession.doomEntry
() is completed. void onCacheEntryDoomed( in nsresult status ); Parameters status The status is NS_OK when the entry was doomed, or NS_ERROR_NOT_AVAILABLE when there is no such entry. See also nsICache nsICacheSession nsICacheEntryDescriptor ...
nsICacheVisitor
netwerk/cache/nsICacheVisitor.idlScriptable This interface provides information about cache devices and entries. ...
...boolean visitEntry( in string deviceID, in nsICacheEntryInfo entryInfo ); Parameters deviceID Specifies the device being visited. entryInfo Specifies information about this entry. ...
nsIChromeFrameMessageManager
ding of content in a remote chrome frame. 1.0 66 Introduced Gecko 2.0 Inherits from: nsIFrameMessageManager Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview void loadFrameScript(in AString aURL, in boolean aAllowDelayedLoad); void removeDelayedFrameScript(in AString aURL); Methods loadFrameScript
() Loads a script into the remote frame. void loadFrameScript( in AString aURL, in boolean aAllowDelayedLoad ); Parameters aURL The URL of the script to load into the frame; this must be an absolute URL, but data: URLs are supported. aAllowDelayedLoad If true, the script will be loaded when the remote frame becomes available; otherwise, the script will only be loade...
... in AString aURL, in boolean aAllowDelayedLoad ); Parameters aURL The URL of the script to load into the frame; this must be an absolute URL, but data: URLs are supported. aAllowDelayedLoad If true, the script will be loaded when the remote frame becomes available; otherwise, the script will only be loaded if the frame is already available. removeDelayedFrameScript
() Removes a script from the list of scripts supporting delayed load. void removeDelayedFrameScript( in AString aURL ); Parameters aURL The URL of the script to remove from the list of scripts supporting delayed load. See also Content process event handling nsIContentFrameMessageManager nsIFrameLoader nsIFrameMessageListener ...
nsICommandLineRunner
run them by processing the comand line handlers. toolkit/components/commandlines/public/nsICommandLineRunner.idlScriptable Please add a summary to this article. Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Inherits from: nsICommandLine Method overview void init(in long argc, in nsCharPtrArray argv, in nsIFile workingDir, in unsigned long state); void run
(); void setWindowContext(in nsIDOMWindow aWindow); Attributes Attribute Type Description helpText AUTF8String Process and combine the help text provided by each command-line handler. Read only. Methods init
() Called with the argc/argv combination passed to main. It assumes a native character set. On Windows the character set is UTF-8, not the native codepage. void init( in long argc,...
...epage. void init( in long argc, in nsCharPtrArray argv, in nsIFile workingDir, in unsigned long state ); Parameters argc The number of arguments being passed. argv An array storing pointers to the arguments workingDir Directory where the command will run. This is used to resolve file and URI paths. state The type of command line being processed. This is an nsICommandLine state flag. run
() Processes the command-line handlers in the proper order, and calls nsICommandLineHandler.handle
() on each. void run
(); Parameters None. Exceptions thrown NS_ERROR_ABORT Thrown when the handler aborts. All other errors thrown by handlers will be silently ignored. setWindowContext
() Sets the windowContext parameter. void setWindowContext( in nsIDOMWindow aWindow ); Parameters aWindow The DOM...
nsIContentFrameMessageManager
ipts can send either synchronous or asynchronous messages to the chrome process: for details on these messaging APIs see the documentation for the nsIContentFrameMessageManager's parent classes nsISyncMessageSender and nsIMessageSender. ...
...ssageManager's parent classes nsISyncMessageSender and nsIMessageSender. Methods void dump(in DOMString aStr); DOMString atob(in DOMString aAsciiString); DOMString btoa(in DOMString aBase64Data); dump
() Prints the specified string to standard output. Parameters Name Type Description aStr String The message to log. atob
() Convert ASCII base64 data to binary data. Parameters Name Type Description aAsciiString String ASCII string to decode. Returns String: the decoded binary data. btoa
() Convert binary data to ASCII base64 data . Parameters Name Type Description aBase64Data String Binary data to encode as base64. Returns Strin...
nsIContentPrefCallback2
This may be called multiple times before h...
... 0 COMPLETE_ERROR 1 Methods handleCompletion
() Called when the method finishes. This will be called exactly once for each method invocation, and afterward no other callback methods will be called. void handleCompletion( in unsigned short reason ); Parameters reason One of the COMPLETE_* values indicating the manner in which the method completed. handleError
() Called when an error occurs. This may be called multiple times before handleCompletion is called. void handleError( in nsresult error ); Parameters error A number in Components.results describing the error. handleResult
() For the retrieval methods, this is called once for each retrieved preference. It is not called for other methods. void handleResult( in nsIContentPref pref ); Pa...
nsIContentPrefObserver
to easily watch for changes to the values of content preferences. ...
... void onContentPrefSet( in AString aGroup, in AString aName, in nsIVariant aValue ); Parameters aGroup The group to which the preference belongs; this may be the URI of a web site. ...
nsIContentView
view will have scroll values that are reset to the default. Read only. scrollY float Horizontal scroll offset in chrome-document CSS pixels. Read only. viewportHeight float Height of the viewport in chrome-document CSS pixels. Read only. viewportWidth float Width of the viewport in chrome-document CSS pixels. Read only. Methods scrollBy
() Scrolls the content view by the specified number of chrome-document CSS pixels along each axis. Fails if the view isn't valid. void scrollBy( in float dxPx, in float dyPx ); Parameters dxPx The number of CSS pixels to scroll on the X axis; specify a positive value to scroll to the right or a negative value to scroll to the left. dyPx The number of CSS pixels to scroll on the Y axis;...
...g each axis. Fails if the view isn't valid. void scrollBy( in float dxPx, in float dyPx ); Parameters dxPx The number of CSS pixels to scroll on the X axis; specify a positive value to scroll to the right or a negative value to scroll to the left. dyPx The number of CSS pixels to scroll on the Y axis; specify a positive value to scroll down or a negative value to scroll up. scrollTo
() Scrolls the content view to the specified position, in chrome-document CSS pixels. Fails if the view isn't valid. void scrollTo( in float xPx, in float yPx ); Parameters xPx The X coordinate to scroll to, in CSS pixels. yPx The Y coordinate to scroll to, in CSS pixels. setScale
() Sets the content view's scale for each axis. void setScale( in float xScale, in float yScale ); ...
nsIContentViewManager
content/base/public/nsIFrameLoader.idlScriptable Manages the content views contained in a browser 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) To obtain a reference to the view manager for a document, you can QueryInterface
() the nsIFrameLoader object to nsIContentViewManager. See Getting access to content views for details. Once you have the view manager, you can call getContentViewsIn
() to get a list of the content views for a given portion of the browser display, then use those nsIContentView objects to manipulate the content views. Method overview void getContentViewsIn(in float aXPx, in float aYPx, in float aTopSize, in float aRightSize, in float aBottomSize, i...
...ntentViewsIn(in float aXPx, in float aYPx, in float aTopSize, in float aRightSize, in float aBottomSize, in float aLeftSize, [optional] out unsigned long aLength, [retval, array, size_is(aLength)] out nsIContentView aResult); Attributes Attribute Type Description rootContentView nsIContentView The root content view. Read only. Methods getContentViewsIn
() Returns an array of nsIContentView objects representing all of the content views that intersect with the specified rectangle in the browser. Note: The rectangle is specified using an anchor point, then four distances to indicate how far in each direction to expand the rectangle. This lets you, for example, take the coordinates at which the user clicked (or touched) the screen, and expand outwar...
nsIController
ontent/xul/document/public/nsIController.idlScriptable An interface that can be implemented to receive and process commands and events. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void doCommand(in string command); boolean isCommandEnabled(in string command); void onEvent(in string eventName); boolean supportsCommand(in string command); Methods doCommand
() When this method is called, your implementation should execute the command with the specified name. void doCommand( in string command ); Parameters command The name of the command to execute. isCommandEnabled
() Implement this method to indicate whether or not the specified command is enabled. boolean isCommandEnabled( in string command ); Parameters command The name of the command whose ...
...d The name of the command to execute. isCommandEnabled
() Implement this method to indicate whether or not the specified command is enabled. boolean isCommandEnabled( in string command ); Parameters command The name of the command whose availability is to be checked. Return value Return true if the specified command is currently available to be used; otherwise, it should return false. onEvent
() Implement this method to process the event with the specified name. void onEvent( in string eventName ); Parameters eventName The name of the event to process. supportsCommand
() Implement this method to report whether or not the command with the specified name is supported. boolean supportsCommand( in string command ); Parameters command The name of the command to determine whether or no...
nsICookieConsent
the policy for the given URI and channel is also returned. ...
...the policy for the given URI and channel is also returned. ...
nsICookieStorage
ies. modules/plugin/base/public/nsICookieStorage.idlNot scriptable Please add a summary to this article. ...
... void setCookie( in string aCookieURL, in constVoidPtr aCookieBuffer, in unsigned long aCookieSize ); Parameters aCookieURL URL string to look up cookie with.. aCookieBuffer Buffer containing cookie data. aCookieSize Specifies size of cookie data. ...
nsICrashReporter
itted. Only https and http URLs are allowed, as the submission is handled by OS-native networking libraries. Exceptions thrown NS_ERROR_FAILURE On get if no URL is set. NS_ERROR_INVALID_ARG On set if a non-http(s) URL is assigned. NS_ERROR_NOT_INITIALIZED If crash reporting is not initialized. submitReports boolean User preference for submitting crash reports. Methods annotateCrashReport
() Add some extra data to be submitted with a crash report. void annotateCrashReport( in ACString key, in ACString data ); Parameters key Name of the data to be added. data Data to be added. Exceptions thrown NS_ERROR_INVALID_ARG If key or data contain invalid characters. Invalid characters for key are '=' and '\n'. Invalid character for data is '\0'. NS_ERROR_NOT_INITIALIZED If crash report...
... report. void annotateCrashReport( in ACString key, in ACString data ); Parameters key Name of the data to be added. data Data to be added. Exceptions thrown NS_ERROR_INVALID_ARG If key or data contain invalid characters. Invalid characters for key are '=' and '\n'. Invalid character for data is '\0'. NS_ERROR_NOT_INITIALIZED If crash reporting not initialized. appendAppNotesToCrashReport
() Append some data to the "Notes" field, to be submitted with a crash report. Unlike annotateCrashReport
(), this method will append to existing data. void appendAppNotesToCrashReport( in ACString data ); Parameters data Data to be added. Exceptions thrown NS_ERROR_INVALID_ARG If data contains invalid characters. The only invalid character is '\0'. NS_ERROR_NOT_INITIALIZED If crash reporting n...
nsIDOMSerializer
tras/xmlserializer;1. To create an instance, use: var domSerializer = Components.classes["@mozilla.org/xmlextras/xmlserializer;1"] .createInstance(Components.interfaces.nsIDOMSerializer); Method overview void serializeToStream(in nsIDOMNode root, in nsIOutputStream stream, in AUTF8String charset); AString serializeToString(in nsIDOMNode root); Methods serializeToStream
() The subtree rooted by the specified element is serialized to a byte stream using the character set specified. void serializeToStream( in nsIDOMNode root, in nsIOutputStream stream, in AUTF8String charset ); Parameters root The root of the subtree to be serialized. This could be any node, including a Document. stream The byte stream to which the subtree is serialized. charset The name of t...
...putStream stream, in AUTF8String charset ); Parameters root The root of the subtree to be serialized. This could be any node, including a Document. stream The byte stream to which the subtree is serialized. charset The name of the character set to use for the encoding to a byte stream. If this string is empty and root is a document, the document's character set will be used. serializeToString
() The subtree rooted by the specified element is serialized to a string. AString serializeToString( in nsIDOMNode root ); Parameters root The root of the subtree to be serialized. This could be any node, including a Document. Return value The serialized subtree in the form of a Unicode string. ...
nsIDOMSimpleGestureEvent
a press and tap two finger gesture (first finger down, second finger down, second finger up, first finger up) on the input device. Client coordinates contain the center pivot point of the action. (XXX Not implemented on Mac) Default behavior: Some operating systems support default behaviors for gesture events when they are not handled by the application. Consumers should use event.preventDefault
() to prevent default behavior when consuming events. Method overview void initSimpleGestureEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in nsIDOMAbstractView viewArg, in long detailArg, in long screenXArg, in long screenYArg, in long clientXArg, in long clientYArg, in boolean ctrlKeyArg, in boolean altKeyArg, in boolean shiftKeyArg, in boolean metaKeyArg...
... 1 Upward swipe. DIRECTION_DOWN 2 Downward swipe. DIRECTION_LEFT 4 Leftward swipe. DIRECTION_RIGHT 8 Rightward swipe. Rotation constants Constant Value Description ROTATION_COUNTERCLOCKWISE 1 Counter-clockwise rotation. ROTATION_CLOCKWISE 2 Clockwise rotation. Methods initSimpleGestureEvent
() Initializes the gesture event. void initSimpleGestureEvent( in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in nsIDOMAbstractView viewArg, in long detailArg, in long screenXArg, in long screenYArg, in long clientXArg, in long clientYArg, in boolean ctrlKeyArg, in boolean altKeyArg, in boolean shiftKeyArg, in boolean metaKeyArg, in unsigned sh...
nsIDOMStorageManager
Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Implemented by @mozilla.org/dom/storagemanager;1 as a service: var domStorageManager = Components.classes["@mozilla.org/dom/storagemanager;1"] .getService(Components.interfaces.nsIDOMStorageManager); Method overview void clearOfflineApps
(); nsIDOMStorage getLocalStorageForPrincipal(in nsIPrincipal aPrincipal, in DOMString aDocumentURI); long getUsage(in AString aOwnerDomain); Methods clearOfflineApps
() Clears keys owned by offline applications. All data owned by a domain with the "offline-app" permission is removed from the database. void clearOfflineApps
(); Parameters None. getLocalStorageForPrincipal
() Returns the instan...
...bject for aURI's origin. This is used to ensure that only one local storage area exists for a given origin. nsIDOMStorage getLocalStorageForPrincipal( nsIPrincipal aPrincipal, DOMString aDocumentURI ); Parameters aPrincipal The principal for which to return the local storage object. aDocumentURI The document's URI. Return value The local storage object for the specified principal. getUsage
() Returns the amount of disk space used by a domain. Usage is checked against the domain of the page that set the key (the owner domain), not the domain of the storage object. long getUsage( AString aOwnerDomain ); Parameters aOwnerDomain The domain to check. Return value The space usage of the domain, in bytes.See also offline apps DOM Storage Structured client-side storage (HTML 5 specifica...
nsIDOMXPathResult
Read only. ...
...e order that they appear in the document. ANY_UNORDERED_NODE_TYPE 8 Type is a single node that matches the expression. The node is not necessarily the first node in the document that matches the expression used in the evaluator. FIRST_ORDERED_NODE_TYPE 9 Type is the first node in the document that matches the expression used in the evaluator. Methods iterateNext
() Iterates through the available nodes of an UNORDERED_NODE_ITERATOR_TYPE or ORDERED_NODE_ITERATOR_TYPE result. nsIDOMNode iterateNext
(); Parameters None. Return value A DOM node. snapshotItem
() Returns the specified node from what is essentially an array of resulting DOM nodes. Is only available if the result type is UNORDERED_NODE_SNAPSHOT_TYPE or ORDERED_NODE_SNAPSHOT_TYPE. nsIDOMNode snapshotI...
nsIDirIndexListener
void onInformationAvailable( in nsIRequest aRequest, in nsISupports aCtxt, in AString aInfo ); Parameters aRequest ...
...rts aCtxt, in nsIDirIndex aIndex); void onInformationAvailable(in nsIRequest aRequest, in nsISupports aCtxt, in AString aInfo); Methods onIndexAvailable
() Called for each directory entry. void onIndexAvailable( in nsIRequest aRequest, in nsISupports aCtxt, in nsIDirIndex aIndex ); Parameters aRequest The request. aCtxt Opaque parameter aIndex New index to add. onInformationAvailable
() Called for each information line. void onInformationAvailable( in nsIRequest aRequest, in nsISupports aCtxt, in AString aInfo ); Parameters aRequest The request. aCtxt Opaque parameter aInfo New info to add. ...
nsIDirectoryServiceProvider
xpcom/io/nsIDirectoryService.idlScriptable This interface is used by the Directory Service to get file locations. Inherits from: nsISupports Last changed in Gecko 1.7 nsIDirectoryServiceProvider. Method overview nsIFile getFile(in string prop, out PRBool persistent); Methods getFile
() The Directory Service calls this method when it gets the first request for a prop or on every request if the prop is not persistent. nsIFile getFile( in string prop, out PRBool persistent ); Parameters prop The symbolic name of the file. persistent true if the returned file will be cached by Directory Service. Subsequent requests for this prop will bypass the provider and use the cache. false if the provider will be asked for this prop each time it is requested. Return value The nsI...
...rvice. Subsequent requests for this prop will bypass the provider and use the cache. false if the provider will be asked for this prop each time it is requested. Return value The nsIFile represented by the property. Example This code creates a global, read-only string called currDir with the value of the current working directory. __defineGetter__("currDir", function getCurrDir
() { return Components.classes["@mozilla.org/file/directory_service;1"] .getService(Components.interfaces.nsIDirectoryServiceProvider) .getFile("CurWorkD",{}).path; }); Test it with to see the magic happen. alert(currDir); See also nsDirectoryService nsIDirectoryService Additionally,...
nsIDownloadManagerUI
components/downloads/public/nsIDownloadManagerUI.idlScriptable This interface is used to implement the user interface for the Download Manager. If you wish to replace the default Download Manager user interface, implement this interface. 1.0 66 Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) Method overview void getAttention
(); void show([optional] in nsIInterfaceRequestor aWindowContext, [optional] in unsigned long aID, [optional] in short aReason); Attributes Attribute Type Description visible boolean true if the Download Manager UI is visible; otherwise false. Read only. Constants Constant Value Description REASON_USER_INTERACTED 0 ...
... Value Description REASON_USER_INTERACTED 0 When opening the Download Manager user interface, this value indicates that it's being done at the user's request. REASON_NEW_DOWNLOAD 1 When opening the Download Manager user interface, this value indicates that the user interface is being displayed because a new download is being started. Methods getAttention
() Calls attention to the Download Manager's user interface if it's already open. The UI need not be visible to call this function, nor will the UI be made visible. void getAttention
(); Parameters None. Exceptions thrown NS_ERROR_UNEXPECTED The user interface isn't currently open. show
() Shows the Download Manager's user interface to the user. void show( in nsIInterfaceRequestor aWin...
nsIDragDropHandler
in the content area. Use this to register where the listeners should attach (something that implements nsPIDOMEventTarget which is what we end up using under the hood). content/base/public/nsIDragDropHandler.idlScriptable Please add a summary to this article. Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Inherits from: nsISupports Method overview void detach
(); void hookupTo(in nsIDOMEventTarget attachPoint, in nsIWebNavigation navigator); Methods detach
() Unregisters all handlers related to drag and drop. void detach
(); Parameters None. hookupTo
() Attaches drag handlers to a specified receiver, setting up callbacks to let built-in behaviors be overridden. void hookupTo( in nsIDOMEventTarget attachPoint, in nsIWebNavigation navigator ); Pa...
..., setting up callbacks to let built-in behaviors be overridden. void hookupTo( in nsIDOMEventTarget attachPoint, in nsIWebNavigation navigator ); Parameters attachPoint The receiver to which to attach drag handlers. navigator The nsIWebNavigation object to handle the dropped URLs. If this is NULL, the client must handle the drop itself, either through the method provided via overrideDrop
() or by letting the event bubble up through the DOM. ...
nsIDragSession
Read only. sourceNode nsIDOMNode The DOM node that was originally dragged to start the session, which will be null if the drag originated outside the application. Read only. targetSize nsSize Sets the current width and height of the drag target area. It will contain the current size of the Frame that the drag is currently in. ...
...If numDropItems is greater than one, there is no indication as to which of the items matches the data flavor. boolean isDataFlavorSupported( in string aDataFlavor ); Parameters aDataFlavor A string representing the MIME type of the data to be matched, such as "text/unicode". ...
nsIEditorDocShell
docshell/base/nsIEditorDocShell.idlScriptable Provides a way to get an editor from a specific frame in a docShell hierarchy. It is intended to be only used internally. Inherits from: nsISupports Last changed in Gecko 1.7 Use nsIEditingSession.makeWindowEditable
() and nsIEditingSession.getEditorForWindow
() from out side. Method overview void makeEditable(in boolean inWaitForUriLoad); Attributes Attribute Type Description editable boolean This docShell is editable. Read only. ...
...void makeEditable( in boolean inWaitForUriLoad ); Parameters inWaitForUriLoad true to wait for a URI before creating the editor. ...
nsIException
There is no unambiguous indicator for unknown. Read only. data nsISupports Arbitary data for the implementation. Read only. filename string Filename location. This is the location that caused the error, which may or may not be a source file location. ...
... only. location nsIStackFrame A stack trace, if available. Read only. message string A custom message set by the thrower. [binaryname(MessageMoz)] Read only. name string The name of the error code (A string representation of result) Read only. result nsresult The nsresult associated with this exception. Read only. Methods toString
() A generic formatter - make it suitable to print, etc. string toString
(); Parameters None. Return value A string suitable for output. ...
nsIFactory
is interface is a class factory that allows for the creation of nsISupports derived classes without specifying a concrete class type. Inherits from: nsISupports Last changed in Gecko 0.9.5 Method overview void createInstance(in nsISupports aOuter, in nsIIDRef iid, [retval, iid_is(iid)] out nsQIResult result); void lockFactory(in PRBool lock); Methods createInstance
() Creates an instance of the class associated with this factory. Unlike getService, this returns a new instance each time it is called. (See also nsIComponentManager.createInstance.) void createInstance( in nsISupports aOuter, in nsIIDRef iid, [retval, iid_is(iid)] out nsQIResult result ); Parameters aOuter Pointer to a component that wishes to be aggregated in the resulting instance.
... This can be nsnull if no aggregation is requested. iid The IID of the interface being requested in the component which is being currently created. result Pointer to the newly created instance, if successful. Exceptions thrown NS_ERROR_NO_INTERFACE Indicates that the requested interface is not supported. NS_ERROR_NO_AGGREGATION Indicates that aggregation is not supported. lockFactory
() This method provides the client a way to keep the component in memory until it is finished with it. Gecko 1.7 note As of Gecko 1.7, this method is unused. Most implementations do nothing interesting with this method. It exists primarily for binary compatibility with Microsoft COM's IClassFactory interface. void lockFactory( in PRBool lock ); Parameters lock true to lock the facto...
nsIFeedProcessor
void parseAsync(in nsIRequestObserver requestObserver, in nsIURI uri); void parseFromStream(in nsIInputStream stream, in nsIURI uri); void parseFromString(in AString str, in nsIURI uri); Attributes Attribute Type Description listener nsIFeedResultListener The feed result listener that will respond to feed events. Methods parseAsync
() Parses a feed asynchronously. The caller must then call the processor's nsIStreamListener methods to drive the parsing process. You must not call any of the other parsing methods on the nsIFeedProcessor interface during an asynchronous parse. void parseAsync( in nsIRequestObserver requestObserver, in nsIURI uri ); Parameters requestObserver The observer to be notified when parsing...
...rocess. You must not call any of the other parsing methods on the nsIFeedProcessor interface during an asynchronous parse. void parseAsync( in nsIRequestObserver requestObserver, in nsIURI uri ); Parameters requestObserver The observer to be notified when parsing starts and stops. This can be null. uri The base URI against which any URIs in the feed are resolved. parseFromStream
() Parses a feed from an nsIInputStream. void parseFromStream( in nsIInputStream stream, in nsIURI uri ); Parameters stream Pointer to the nsIInputStream from which to read and parse the feed. uri The base URI against which any URIs in the feed are resolved. parseFromString
() Parses a feed from an AString. void parseFromString( in AString str, in nsIURI uri ); Paramet...
nsIFileInputStream
l close automatically when the end of the file is reached. REOPEN_ON_REWIND 1<<3 If this is set, the file will be reopened whenever Seek(0) occurs. If the file is already open and the seek occurs, it will happen naturally. (The file will only be reopened if it is closed for some reason.) DEFER_OPEN 1<<4 If this is set, the file will be opened (i.e., a call to PR_Open
() done) only when we do an actual operation on the stream, or more specifically, when one of the following is called: Seek
() Tell
() Available
() Read
() ReadLine
() DEFER_OPEN is useful if we use the stream on a background thread, so that the opening and possible stating of the file happens there as well. Note: Using this flag results in the file not being ...
...so that the opening and possible stating of the file happens there as well. Note: Using this flag results in the file not being opened during the call to init. This means that any errors that might happen when this flag is not set would happen during the first read. Also, the file is not locked when init is called, so it might be deleted before we try to read from it. Methods init
() void init( in nsIFile file, in long ioFlags, in long perm, in long behaviorFlags ); Parameters file File to read from (must QI to nsILocalFile) ioFlags The file status flags define how the file is accessed. See PR_Open documentation for more details. If set to -1 the file will be opened in default mode (PR_RDONLY). perm File mode bits are described in the PR_Open documentation.
nsIFileOutputStream
7 Method overview void init(in nsIFile file, in long ioFlags, in long perm, in long behaviorFlags); Constants Behavior flag constants Constant Value Description DEFER_OPEN 1<<0 See the same constant in nsIFileInputStream. The deferred open will be performed when one of the following is called: Seek
() Tell
() Write
() Flush
() DEFER_OPEN is useful if we use the stream on a background thread, so that the opening and possible stating of the file happens there as well. Note: Using this flag results in the file not being opened during the call to init
(). This means that any errors that might happen when this flag is not set would happe...
...at the opening and possible stating of the file happens there as well. Note: Using this flag results in the file not being opened during the call to init
(). This means that any errors that might happen when this flag is not set would happen during the first write, and if the file is to be created, it will not appear on the disk until the first write. Methods init
() void init( in nsIFile file, in long ioFlags, in long perm, in long behaviorFlags ); Parameters file File to write to (must QI to nsILocalFile) ioFlags File open flags listed are listed in the PR_Open
() documentation. Use -1 to open the file in default mode (PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE). perm File mode bits are described in the PR_Op...
nsIFrameLoaderOwner
content/base/public/nsIFrameLoader.idlScriptable Represents the owner of an nsIFrameLoader. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview [noscript, notxpcom] alreadyAddRefed_nsFrameLoader GetFrameLoader
(); void swapFrameLoaders(in nsIFrameLoaderOwner aOtherOwner); Attributes Attribute Type Description frameLoader nsIFrameLoader The frame loader owned by this nsIFrameLoaderOwner. Read only. Methods getFrameLoader
() Returns the frame loader object owned by this object. [noscript, notxpcom] alreadyAddRefed_nsFrameLoader GetFrameLoader
(); Parameters None. Return value The nsIFrameLoader owned by this ...
...This may only be possible in a very limited set of circumstances, or never, depending on the object implementing this interface. ...
nsIFrameMessageListener
ssages from the browser process. 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) This interface is used when implementing out-of-process handling of frames; the process handling a frame should implement this interface in order to receive messages. Method overview void receiveMessage
(); Methods receiveMessage
() Note: This method is for JavaScript only. Called to deliver a message to the frame handling process; called with one parameter, which has the following properties: name The name of the message. sync A boolean value indicating whether or not the message should be handled synchronously. If true, the response should be returned in th...
...message should be handled synchronously. If true, the response should be returned in the specified JSON object. json The JSON object in which to return the response if the message is being handled synchronously. objects Unimplemented An array of cpow, or null if sync is false. When the listener is called, the this value is the target of the message. void receiveMessage
(); Parameters None. See also Content process event handling nsIFrameListener ...
nsIGSettingsCollection
st changed in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) Method overview boolean getBoolean(in AUTF8String key); long getInt(in AUTF8String key); AUTF8String getString(in AUTF8String key); void setBoolean(in AUTF8String key, in boolean value); void setInt(in AUTF8String key, in long value); void setString(in AUTF8String key, in AUTF8String value); Methods getBoolean
() boolean getBoolean( in AUTF8String key ); Parameters key Return value getInt
() long getInt( in AUTF8String key ); Parameters key Return value getString
() AUTF8String getString( in AUTF8String key ); Parameters key Return value setBoolean
() void setBoolean( in AUTF8String key, in boolean value ); Parameters key value setInt
() void setInt( in AUTF8String key, in lo...
...arameters key Return value getInt
() long getInt( in AUTF8String key ); Parameters key Return value getString
() AUTF8String getString( in AUTF8String key ); Parameters key Return value setBoolean
() void setBoolean( in AUTF8String key, in boolean value ); Parameters key value setInt
() void setInt( in AUTF8String key, in long value ); Parameters key value setString
() void setString( in AUTF8String key, in AUTF8String value ); Parameters key value ...
nsIGlobalHistory2
lkit interfaces. Inherits from: nsISupports Last changed in Gecko 1.7 This interface replaces and deprecates nsIGlobalHistory Method overview void addURI(in nsIURI aURI, in boolean aRedirect, in boolean aToplevel, in nsIURI aReferrer); boolean isVisited(in nsIURI aURI); void setPageTitle(in nsIURI aURI, in AString aTitle); Methods addURI
() Add a URI to global history. Note: Docshell will not filter out URI schemes like chrome:, data:, about: and view-source:. Embedders should consider filtering out these schemes and others, for example mailbox:, for the main nsIURI and the referrer. void addURI( in nsIURI aURI, in boolean aRedirect, in boolean aToplevel, in nsIURI aReferrer ); Parameters aURI The nsIURI of ...
...n aRedirect, in boolean aToplevel, in nsIURI aReferrer ); Parameters aURI The nsIURI of the page being added. aRedirect Whether the URI was redirected to another location; this is true for the original URI which is redirected. aToplevel Whether the URI is loaded in a top-level window. aReferrer The URI of the referring page. isVisited
() Checks to see whether the given URI is in history. boolean isVisited( in nsIURI aURI ); Parameters aURI The nsIURI of the page. Return value true if a URI has been visited. setPageTitle
() Set the page title for the given uri. URIs that are not already in global history will not be added. void setPageTitle( in nsIURI aURI, in AString aTitle ); Parameters aURI ...
nsIHapticFeedback
LongPress 1 Specify as the action type to perform a...
... void performSimpleAction( in long isLongPress ); Parameters isLongPress The press length; this will determine how long the vibration should last. See Press length constants for permitted values. ...
nsIHttpActivityObserver
1.0) Method overview void observeActivity(in nsISupports aHttpChannel, in PRUint32 aActivityType, in PRUint32 aActivitySubtype, in PRTime aTimestamp, in PRUint64 aExtraSizeData, in ACString aExtraStringData); Attributes Attribute Type Description isActive boolean true when the interface is active and should observe HTTP activity, otherwise false. If this is false, the observeActivity
() method should not be called. Read only. Note: This attribute is present only for compatibility and should not be used. Constants Activity type constants Constant Value Description ACTIVITY_TYPE_SOCKET_TRANSPORT 0x0001 Socket transport activity has occurred. ACTIVITY_TYPE_HTTP_TRANSACTION 0x0002 HTTP transport activity has occurred. Activity subtype constants Constant Value Descr...
... The HTTP request's body has been sent. ACTIVITY_SUBTYPE_RESPONSE_START 0x5003 The HTTP response has started to arrive. ACTIVITY_SUBTYPE_RESPONSE_HEADER 0x5004 The HTTP response header has arrived. ACTIVITY_SUBTYPE_RESPONSE_COMPLETE 0x5005 The complete HTTP response has been received. ACTIVITY_SUBTYPE_TRANSACTION_CLOSE 0x5006 The HTTP transaction has been closed. Methods observeActivity
() Called when activity occurs on the HTTP transport. You should implement this method to perform whatever tasks you wish to perform when HTTP activity occurs. void observeActivity( in nsISupports aHttpChannel, in PRUint32 aActivityType, in PRUint32 aActivitySubtype, in PRTime aTimestamp, in PRUint64 aExtraSizeData, in ACString aExtraStringData ); Parameters aHttpChannel The nsIHttpCha...
nsIInterfaceRequestor
xpcom/base/nsIInterfaceRequestor.idlScriptable This interface defines a generic interface for requesting interfaces that a given object might provide access to. Inherits from: nsISupports Last changed in Gecko 0.9.5 This is similar to nsISupports.QueryInterface
(). The main difference is that interfaces returned are not required to provide a way back to the object implementing nsIInterfaceRequestor. The semantics of nsISupports.QueryInterface
() dictate that given an interface A that you nsISupports.QueryInterface
() on to get to interface B, you must be able to nsISupports.QueryInterface
() on B to get back to A. nsIInterfaceRequestor, however, allows you to obtain an interface C from A that may (or most likely) will not have the ability to get back to A. Method overview void...
...void getInterface( in nsIIDRef uuid, [iid_is(uuid),retval] out nsQIResult result ); Parameters uuid The IID of the interface being requested. result The interface pointer to be filled in if the interface is accessible. Exceptions thrown NS_ERROR_NO_INTERFACE The requested interface is not available. ...
nsILoadGroup
hen requests are added to and removed from this load group. The groupObserver is weak referenced. notificationCallbacks nsIInterfaceRequestor Notification callbacks for the load group. requests nsISimpleEnumerator Returns the requests contained directly in this group. Enumerator element type: nsIRequest. Read only. Methods addRequest
() Adds a new request to the group. This will cause the default load flags to be applied to the request. If this is a foreground request then the groupObserver's onStartRequest will be called. If the request is the default load request or if the default load request is null, then the load group will inherit its load flags from the request. void addRequest( in nsIRequest aRequest, in nsISupports ...
.... If the request is the default load request or if the default load request is null, then the load group will inherit its load flags from the request. void addRequest( in nsIRequest aRequest, in nsISupports aContext ); Parameters aRequest The request to be added to the load group. aContext The context to be passed to the onStartRequest notification. removeRequest
() Removes a request from the group. If this is a foreground request then the groupObserver's onStopRequest will be called. By the time this call ends, aRequest will have been removed from the loadgroup, even if this function throws an exception. void removeRequest( in nsIRequest aRequest, in nsISupports aContext, in nsresult aStatus ); Parameters aRequest The request to be rem...
nsILoginManagerCrypto
pt(in AString cipherText); AString encrypt(in AString plainText); Attributes Attribute Type Description isLoggedIn boolean Current login state of the token used for encryption. If the user is not logged in, performing a crypto operation will result in a master password prompt. Read only. uiBusy boolean true when a master password prompt is being displayed. Read only. ...
...Note: The current implemention of this inferface simply uses NSS/PSM's "Secret Decoder Ring" service. It is not recommended for general purpose encryption/decryption. Can throw if the user cancels entry of their master password. AString encrypt( in AString plainText ); Parameters plainText The string to be encrypted. ...
nsIMIMEInputStream
es.nsIMIMEInputStream); Method overview void addHeader(in string name, in string value); void setData(in nsIInputStream stream); Attributes Attribute Type Description addContentLength boolean When true a "Content-Length" header is automatically added to the stream. The value of the content-length is automatically calculated using the available
() method on the data stream. The value is recalculated every time the stream is rewound to the start. Not allowed to be changed once the stream has been started to be read. Methods addHeader
() Adds an additional header to the stream on the form "name: value". May not be called once the stream has been started to be read. void addHeader( in string name, in string value ); Parameters ...
...May not be called once the stream has been started to be read. The cursor of the new stream should be located at the beginning of the stream if the implementation of the nsIMIMEInputStream also is used as an nsISeekableStream. ...
nsIMarkupDocumentViewer
docshell/base/nsIMarkupDocumentViewer.idlScriptable Describes the properties of a content viewer for an HTML or XML markup document. Inherits from: nsISupports Last changed in Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) Method overview void scrollToNode(in nsIDOMNode node); void sizeToContent
(); Attributes Attribute Type Description allowPlugins boolean If true, plugins are allowed within the doc shell. default = true. Obsolete since Gecko 1.8 authorStyleDisabled boolean Disable entire author style level (including HTML presentation hints) bidiCharacterSet octet Whether to force the user's character set 1 - use the document character set 2 - use the character set chosen by the us...
... minimum font size to allow. Note: This attribute was added late in the Gecko 2.0 development cycle and was implemented by the nsIMarkupDocumentViewer_MOZILLA_2_0_BRANCH interface; it was merged into this interface in Gecko 7.0. prevDocCharacterSet ACString textZoom float The amount by which to scale all text. Default is 1.0. Methods scrollToNode
() Scroll the make the specified node visible. void scrollToNode( in nsIDOMNode node ); Parameters node The nsIDOMNode of the node to make visible. sizeToContent
() Tell the container to shrink-to-fit or grow-to-fit its contents. void sizeToContent
(); Parameters None. See also Full page zoom ...
nsIMemoryMultiReporter
want to gather multiple measurements in a single operation (such as a single traversal of a large data structure), you can use a multi-reporter to do so. The callback, which must implement the nsIMemoryMultiReporterCallback interface, receives values that match the fields in the nsIMemoryReporter object. In order for a multi-reporter to gather and generate reports, you need to call collectReports
(). This will call the specified callback's nsIMemoryMultiReporterCallback.callback
() method once for each report. This will trigger any needed computation work. Note: This differs from the behavior of nsIMemoryReporter, which lets all fields except amount be accessed without triggering computation. Attributes Attribute Type Description explicitNonHeap PRInt64 ...
... is a hack that makes nsIMemoryReporterManager.explicit more efficient. This is important; multi-reporters can special-case this operation so it's much faster than gathering all the reports, filtering out the unneeded ones, and adding up the rest. Method overview void collectReports(in nsIMemoryMultiReporterCallback callback, in nsISupports closure); Methods collectReports
() void collectReports( in nsIMemoryMultiReporterCallback callback, in nsISupports closure ); Parameters callback The nsIMemoryMultiReporterCallback to call when collection is complete. closure An object containing any additional data your callback might need; this gets passed to the callback. You can specify null if your callback doesn't require any additional data. See also ...
nsIMemoryMultiReporterCallback
rom nsIMemoryMultiReporter instances. 1.0 66 Introduced Gecko 7.0 Inherits from: nsISupports Last changed in Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) Method overview void callback(in ACString process, in AUTF8String path, in PRInt32 kind, in PRInt32 units, in PRInt64 amount, in AUTF8String description, in nsISupports closure); Methods callback
() Called to provide information from a multi-reporter. Implement this method to handle the report information. void callback( in ACString process, in AUTF8String path, in PRInt32 kind, in PRInt32 units, in PRInt64 amount, in AUTF8String description, in nsISupports closure ); Parameters process The value of the process attribute for the memory reporter. path The value...
... The value of the path attribute. kind The value of the kind attribute. units The value of the units attribute. amount The value of the amount attribute. description The value of the description attribute. closure An nsISupports object providing any additional data the callback might need; you provide this when you call nsIMemoryMultiReporter.collectReports
(). It will be null if no additional data was provided. See also nsIMemoryMultiReporter nsIMemoryReporterManager nsIMemoryReporter ...
nsIMessageBroadcaster
e Message Manager interfaces for more details on the distinction between message senders and message broadcasters. Methods void broadcastAsyncMessage([optional] in AString messageName, [optional] in jsval obj, [optional] in jsval objects); nsIMessageListenerManager getChildAt(in unsigned long aIndex); broadcastAsyncMessage
() Like sendAsyncMessage
(), but also broadcasts this message to all "child" message managers of this message manager. See nsIMessageListener::receiveMessage
() for the format of the data delivered to listeners. WARNING: broadcasting messages can be very expensive and leak sensitive data. Use with extreme caution. Throws NS_ERROR_NOT_INITIALIZED if the sender is not initialized. For example, we w...
... message. obj Object. The message payload. A structured clone of this becomes the data property of the received message. objects Object. An object each of whose properties is an object. This becomes the objects property of the received message, with each original object replaced with a cross process object wrapper for it. getChildAt
() Return a single subordinate message manager. Parameters Name Type Description aIndex Number The index of the subordinate message manager to retrieve. Returns nsIMessageListenerManager: the message manager at the given index. Attributes childCount Number: the number of subordinate message managers. Read only. ...
nsIMicrosummaryObserver
Gecko 6.0 Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) Warning: Microsummary support was removed in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) Method overview void onContentLoaded(in nsIMicrosummary microsummary); void onElementAppended(in nsIMicrosummary microsummary); void onError(in nsIMicrosummary microsummary); Methods onContentLoaded
() Called when an observed microsummary updates its content. Since an observer might watch multiple microsummaries at the same time, the microsummary whose content has been updated gets passed to this handler. void onContentLoaded( in nsIMicrosummary microsummary ); Parameters microsummary The microsummary whose content has just been updated. onElementAppended
() Called when an element is append...
... gets passed to this handler. void onContentLoaded( in nsIMicrosummary microsummary ); Parameters microsummary The microsummary whose content has just been updated. onElementAppended
() Called when an element is appended to a microsummary set. void onElementAppended( in nsIMicrosummary microsummary ); Parameters microsummary The microsummary that has just been appended to the set. onError
() Called when an observed microsummary encounters an error during an update. void onError( in nsIMicrosummary microsummary ); Parameters microsummary The microsumary which could not be updated. See also Microsummary topics Creating a Microsummary ...
nsIMimeHeaders
nce(Components.interfaces.nsIMimeHeaders); Method overview string extractHeader([const] in string headerName, in boolean getAllOfThem); void initialize([const] in string allHeaders, in long allHeadersSize); Attributes Attribute Type Description allHeaders string Read only. ...
...ption allHeaders string Read only. ...
nsIMsgAccount
nsIMsgAccount mailnews/base/public/nsIMsgAccount.idlScriptable An account consists of an incoming server and one or more outgoing identities. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void addIdentity(in nsIMsgIdentity identity); void clearAllValues
(); void init
(); void removeIdentity(in nsIMsgIdentity identity); AString toString
(); Attributes Attribute Type Description defaultIdentity nsIMsgIdentity identities nsISupportsArray Read only. Outgoing identity list (array of nsIMsgIdentity's) incomingServer nsIMsgIncomingServer Incoming server stuff key ACString Internal key identifying itself Methods addIdentity
() Adds a new identity to this account. void addIdentity( in nsIMsgIdentity identity ); Parameters identity T...
...aultIdentity nsIMsgIdentity identities nsISupportsArray Read only. Outgoing identity list (array of nsIMsgIdentity's) incomingServer nsIMsgIncomingServer Incoming server stuff key ACString Internal key identifying itself Methods addIdentity
() Adds a new identity to this account. void addIdentity( in nsIMsgIdentity identity ); Parameters identity The identity to add. clearAllValues
() Clear all user preferences associated with an account. void clearAllValues
(); Parameters None. init
() Initializes an account. void init
(); Parameters None. Exceptions thrown NS_ERROR_ALREADY_OPENED if it is called more then once removeIdentity
() Removes an identity from this account. void removeIdentity( in nsIMsgIdentity identity ); Parameters identity The identity to remove. ...
Building an Account Manager Extension
g nsIAccountManagerExtension As first step we have to implement the nsIAccountManagerExtension. We name the Extension "devmo-account" and state that it is located in the Chrome Package "example@mozilla.org". Furthermore we show the new panel only for IMAP accounts... Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); //class constructor function DevmoAccountManagerExtension
() {}; // class definition DevmoAccountManagerExtension.prototype = { name : "devmo-account", chromePackageName : "example@mozilla.org", showPanel: function(server) { //this panel is only shown for imap accounts... if (server.type == \"imap\") return true; return false; }, QueryInterface: XPCOMUtils.generateQI([ Components.interfaces.nsI...
...red to include a property named prefPanel-devmo-account. prefPanel-devmo-account=Devmo Demo Panel Step4: The new panel and JavaScript the JavaScript for an account manager panel needs to implement at least the following functions. These functions are invoked by the Account Manager. function onPreInit(account, accountvalues) { } function onInit(pageId, serverId) { } function onAcceptEditor
() { } function onSave
() { } function UpdatePage
() {} Step5: Putting it all together // todo build an demo extension for this tutorial... How to Build an XPCOM Component in Javascript ...
nsIMsgDBViewCommandUpdater
a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Inherits from: nsISupports In Thunderbird this is implemented for different windows in several different places: nsMsgDBViewCommandUpdater (for the standalone message window) nsMsgDBViewCommandUpdater (for the threadpane message window) nsMsgSearchCommandUpdater (for search dialogs) Method overview void updateCommandStatus
(); void displayMessageChanged(in nsIMsgFolder aFolder, in AString aSubject, in ACString aKeywords); void updateNextMessageAfterDelete
(); Methods updateCommandStatus
() Called when the number of selected items changes. void updateCommandStatus
(); Parameters None. displayMessageChanged
() Called when the displayed message has changed. void displayMessageChanged(in nsIMsgFolder aFolder, ...
...dStatus
(); Parameters None. displayMessageChanged
() Called when the displayed message has changed. void displayMessageChanged(in nsIMsgFolder aFolder, in AString aSubject, in ACString aKeywords ); Parameters aFolder The folder containing selected message. aSubject The subject of the selected message. aKeywords Keywords associated with the selected message. updateNextMessageAfterDelete
() Allows the backend to tell the front end to re-determine which message we should select after a delete or move void updateNextMessageAfterDelete
(); Parameters None. ...
nsIMsgSendLater
void SendUnsentMessages(in nsIMsgIdentity identity); void RemoveListener(in nsIMsgSendLaterListener listener); void AddListener(in nsIMsgSendLaterListener listener); nsIMsgFolder getUnsentMessagesFolder](in nsIMsgIdentity identity); Attributes Attribute Type Description msgWindow nsIMsgWindow Methods SendUnsentMessages
() Sends all unsent messages for an identity. void SendUnsentMessages(in nsIMsgIdentity identity) Parameters identity The nsIMsgIdentity to send unsent messages for RemoveListener
() Remove an event listener from this nsISendMsgLater instance void RemoveListener(in nsIMsgSendLaterListener listener); Parameters listener The nsIMsgSendLaterListener to remove. AddListener
() Ad...
... an event listener from this nsISendMsgLater instance void RemoveListener(in nsIMsgSendLaterListener listener); Parameters listener The nsIMsgSendLaterListener to remove. AddListener
() Add an event listener to this nsISendMsgLater instance. void AddListener(in nsIMsgSendlaterListener listener); Parameters listener The nsIMsgSendLaterListener to add. getUnsentMessagesFolder
() Get the unsent messages folder for an identity. nsIMsgFolder getUnsentMessagesFolder(in nsIMsgIdentity identity); Parameters identity The nsIMsgIdentity to get the folder for. Return Value The nsIMsgFolder containing unsent messages. ...
nsINavHistoryQueryOptions
toolkit/components/places/nsINavHistoryService.idlScriptable Represents the global options for executing a query. 1.0 66 Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 13.0 (Firefox 13.0 / Thunderbird 13.0 / SeaMonkey 2.10) Method overview nsINavHistoryQueryOptions clone
(); Attributes Attribute Type Description applyOptionsToContainers boolean If true, the query options are only applied to the containers. asyncEnabled boolean When true, the root container node generated by these options and all of its descendant containers are opened asynchronously if they support doing so. By default, this is false. ...
...tion REDIRECTS_MODE_ALL 0 Include both redirected-from and redirected-to pages in the results. REDIRECTS_MODE_SOURCE 1 Include redirected-from pages but not redirected-to pages in the results. REDIRECTS_MODE_TARGET 2 Include redirected-to pages but not redirected-from pages in the results. Methods clone
() This method creates a new options item with the same parameters of this one. nsINavHistoryQueryOptions clone
(); Parameters None. Return value Returns the newly created cloned options. See also Places Using the Places history service Places query URIs Querying Places nsINavHistoryService ...
nsINavHistoryResultTreeViewer
ms are in the flattened list of results, that is how many rows are in this tree right now. The tree adaptor will also QI to nsITreeView, and this will be the same as nsITreeView.rowCount. This is only valid when a tree is attached, the result will be 0 otherwise. Read only. Obsolete since Gecko 1.9 Constants Constant Value Description INDEX_INVISIBLE 0xffffffff Returned by treeIndexForNode
() when the requested node isn't visible (such as when its parent is collapsed). Also returned if there is no tree attached. Methods nodeForTreeIndex
() Returns the node for a given row index. This is only valid when a tree is attached. nsINavHistoryResultNode nodeForTreeIndex( in unsigned long aIndex ); Parameters aIndex The row index of the note to return. Return value The node located at t...
...when its parent is collapsed). Also returned if there is no tree attached. Methods nodeForTreeIndex
() Returns the node for a given row index. This is only valid when a tree is attached. nsINavHistoryResultNode nodeForTreeIndex( in unsigned long aIndex ); Parameters aIndex The row index of the note to return. Return value The node located at the specified index in the tree. treeIndexForNode
() Returns the row index corresponding to the specified node within the tree, or INDEX_INVISIBLE if the tree is unattached or the node is not visible (if, for example, its parent container is collapsed). unsigned long treeIndexForNode( in nsINavHistoryResultNode aNode ); Parameters aNode The node whose index is to be returned. This must be a node retrieved from the same result that the viewer di...
nsIPasswordManager
Attribute Type Description enumerator nsISimpleEnumerator Readonly: An enumeration of the stored usernames and passwords as nsIPassword objects. enumerator nsISimpleEnumerator Readonly: An enumeration of the rejected sites as nsIPassword objects. Only the host portion of these objects is relevant. Methods addUser
() Stores a password. AString addUser(in AUTF8String aHost, in AString aUser, in AString aPassword); Parameters aHost The hostname of the password to store. aUser The username of the password to store. aPassword The password to store. removeUser
() Removes a stored password. void removeUser(in AUTF8String aHost, ...
...hostname of the password to store. aUser The username of the password to store. aPassword The password to store. removeUser
() Removes a stored password. void removeUser(in AUTF8String aHost, in AString aUser); Parameters aHost The hostname of the password to remove. aUser The username of the password to remove. addReject
() Blocks a hostname from having its passwords saved. void addReject(in AUTF8String aHost); Parameters aHost The name of the hostname for which passwords should no longer be saved. removeReject
() Unblocks a hostname from having its passwords saved. void removeReject(in AUTF8String aHost); Parameters aHost The name of the hostname for which passwords can be saved ag...
nsIPipe
ize, in unsigned long segmentCount, in nsIMemory segmentAllocator); Attributes Attribute Type Description inputStream nsIAsyncInputStream The pipe's input end, which also implements nsISearchableInputStream. Read only. outputStream nsIAsyncOutputStream The pipe's output end. Read only. Methods init
() initialize this pipe. void init( in boolean nonBlockingInput, in boolean nonBlockingOutput, in unsigned long segmentSize, in unsigned long segmentCount, in nsIMemory segmentAllocator ); Parameters nonBlockingInput true specifies non-blocking input stream behavior. nonBlockingOutput true specifies non-blocking output stream behavior. segmentSize ...
...e has data or until the pipe is closed. This example presumes that the pipe is being filled asynchronously on some background thread. The pipe supports nsIAsyncInputStream and nsIAsyncOutputStream, which give the user of a non-blocking pipe the ability to wait for the pipe to become ready again. For example, in the case of an empty non-blocking pipe, the user can call nsIAsyncInputStream.AsyncWait
() on the input end of the pipe to be notified when the pipe has data to read (or when the pipe becomes closed). NS_NewPipe2
() and NS_NewPipe
() provide convenient pipe constructors for C++. In most cases nsIPipe is not actually used. It is usually enough to just get references to the pipe's input and output end. In which case, the pipe is automatically closed when the respective pipe ends are releas...
nsIPrefBranch2
In Gecko 13 this Interface was merged into the nsIPrefBranch interface. Method overview void addObserver(in string aDomain, in nsIObserver aObserver, in boolean aHoldWeak); void removeObserver(in string aDomain, in nsIObserver aObserver); Methods addObserver
() Add a preference change observer. On preference changes, the following arguments will be passed to nsIObserver.observe
(): aSubject - The nsIPrefBranch object (this). aTopic - The string defined by NS_PREFBRANCH_PREFCHANGE_TOPIC_ID aData - The name of the preference which has changed, relative to the "root" of the aSubject branch. aSubject.get*Pref(aData) will get the new value of the modified preference. For example, if your observer is registered with addObserver("bar.", ...) on a branch with...
...or example holding the "root" prefbranch and calling addObserver("foo.bar.", ...) will observe changes to foo.bar.baz and foo.bar.bzip. aObserver The object to be notified if the preference changes. aHoldWeak true holds a weak reference to aObserver. The object must implement the nsISupportsWeakReference interface or this will fail. false holds a strong reference to aObserver. removeObserver
() Remove a preference change observer. Note: You must call removeObserver method on the same nsIPrefBranch2 instance on which you called addObserver
() method in order to remove aObserver; otherwise, the observer will not be removed. void removeObserver( in string aDomain, in nsIObserver aObserver ); Parameters aDomain The preference which is being observed for changes. aObse...
nsIPrefLocalizedString
r to distinguish between requests for normal wide strings nsISupportsString) and 'localized' wide strings, which get their default values from properites files. Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method overview void setDataWithLength(in unsigned long length, [size_is(length)] in wstring data); wstring toString
(); Attributes Attribute Type Description data wstring Provides access to string data stored in this property. Methods setDataWithLength
() Used to set the contents of this object. void setDataWithLength( in unsigned long length, [size_is(length)] in wstring data ); Parameters length The length of the string. This value should not include space ...
... object. void setDataWithLength( in unsigned long length, [size_is(length)] in wstring data ); Parameters length The length of the string. This value should not include space for the null terminator, nor should it account for the size of a character. It should only be the number of characters for which there is space in the string. data The string data to be stored. toString
() Used to retrieve the contents of this object into a wide string. Note: This makes a copy of the string argument passed in. wstring toString
(); Parameters None. Return value Returns wstring - The string containing the data stored within this object. ...
nsIPrinterEnumerator
defaultPrinterName wstring The name of the system default printer. This name should also be present in printerNameList. This is not necessarily gecko's default printer; see nsIPrintSettingsService.defaultPrinterName for that. Read only. printerNameList nsIStringEnumerator The list of printer names. Read only. Methods displayPropertiesDlg
() void displayPropertiesDlg( in wstring aPrinter, in nsIPrintSettings aPrintSettings ); Parameters aPrinter aPrintSettings enumeratePrinters
() Obsolete since Gecko 1.9 (Firefox 3) Returns an array of the names of all installed printers. void enumeratePrinters( out PRUint32 aCount, [retval, array, size_is(aCount)] out wstring aResu...
... enumeratePrinters
() Obsolete since Gecko 1.9 (Firefox 3) Returns an array of the names of all installed printers. void enumeratePrinters( out PRUint32 aCount, [retval, array, size_is(aCount)] out wstring aResult ); Parameters aCount Returns number of printers returned. aResult Returns array of names. initPrintSettingsFromPrinter
() Initializes certain settings from the native printer into the PrintSettings These settings include, but are not limited to: Page Orientation, Page Size, Number of Copies. void initPrintSettingsFromPrinter( in wstring aPrinterName, in nsIPrintSettings aPrintSettings ); Parameters aPrinterName aPrintSettings ...
nsIPrivateBrowsingService
orage databases start out empty. Extensions that record potentially private information should use this interface to detect whether private browsing mode is enabled, and if it is, avoid saving that information. For details on how to do this, see the article Supporting private browsing mode. Similarly, plug-ins can detect whether or not private browsing mode is in effect by using the NPN_GetValue
() function to check the current value of the NPNVprivateModeBool variable. Implemented by: @mozilla.org/privatebrowsing;1. To get access to the service from JavaScript, use: var pbs = Components.classes["@mozilla.org/privatebrowsing;1"] .getService(Components.interfaces.nsIPrivateBrowsingService); C++ callers should use the contract ID @mozilla.org/privatebrowsing-wrapper;1 inst...
.... privateBrowsingEnabled boolean Indicates whether or not private browsing mode is currently enabled. You may also turn private browsing mode on and off by setting the value of this attribute. Changing this value while handling one of the notifications generated by the private browsing service throws an NS_ERROR_FAILURE exception. Methods removeDataFromDomain
() Removes all data stored for the specified domain, including its subdomains. void removeDataFromDomain( in AUTF8String aDomain ); Parameters aDomain The domain for which data should be removed. ...
nsIProfileLock
toolkit/profile/public/nsIToolkitProfile.idlScriptable An object returned by the nsIToolkitProfile.lock method; as long as you hold a reference to the object, the profile remains locked. Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method overview void unlock
(); Attributes Attribute Type Description directory nsILocalFile The main profile directory. Read only. localDirectory nsILocalFile A directory corresponding to the main profile directory, which exists for the purpose of storing data on the local filesystem, including cache files or other data files that may not represent critical user data. (for example, this directory may not be included as part of a b...
... A directory corresponding to the main profile directory, which exists for the purpose of storing data on the local filesystem, including cache files or other data files that may not represent critical user data. (for example, this directory may not be included as part of a backup scheme.) In some cases, this directory may just be the main profile directory. Read only. Methods unlock
() Unlocks the profile. void unlock
(); Parameters None. Exceptions thrown NS_ERROR_UNEXPECTED The profile isn't locked. See also Profile management nsIToolkitProfileService nsIToolkitProfile nsIProfileUnlocker ...
nsIProxyInfo
Attribute Type Description failoverProxy nsIProxyInfo This attribute specifies the proxy to failover to when this proxy fails. failoverTimeout unsigned long This attribute specifies the failover timeout in seconds for this proxy. If a nsIProxyInfo is reported as failed via nsIProtocolProxyService.getFailoverForProxy
(), then the failed proxy will not be used again for this many seconds. Read only. flags unsigned long This attribute specifies flags that modify the proxy type. The value of this attribute is the bit-wise combination of the Proxy Flags defined below. Any undefined bits are reserved for future use. Read only. host AUTF8String This attribute s...
... the type of the proxy server as a case insensitive ASCII string. Some special values for this attribute include (but are not limited to) the following: "http" - HTTP proxy (or SSL CONNECT for HTTPS) "socks" - SOCKS v5 proxy "socks4" - SOCKS v4 proxy "direct" - no proxy "unknown" - unknown proxy (see nsIProtocolProxyService.resolve
()) A future version of this interface may define additional types. Read only. Note: Prior to Gecko 1.8 type was available by the type method. Constants The following "Proxy Flags" may be bit-wise combined to construct the flags attribute defined on this interface. All unspecified bits are reserved for future use. Constant Value Des...
nsIPushMessage
dom/interfaces/push/nsIPushNotifier.idlScriptable A push message sent to a system subscription. Inherits from: nsISupports Last changed in Gecko 46.0 (Firefox 46.0 / Thunderbird 46.0 / SeaMonkey 2.43) nsIPushMessage is the subject of a push-message observer notification. This interface resembles PushMessageData from the Push API. Method overview DOMString text
(); jsval json
(); void binary([optional] out uint32_t dataLen, [array, retval, size_is(dataLen)] out uint8_t data); Methods text
() Extracts the message data as a UTF-8 text string. DOMString text
(); Parameters None. json
() Parses the message data as JSON. jsval json
(); Parameters None. binary
() Extracts the message data as a byte array. void binary( [optional] out uin...
...Please see Method parameters in XPIDL for more details on using out parameters in JavaScript. ...
nsIResumableChannel
in unsigned long startPos, in nsIResumableEntityID entityID); Obsolete since Gecko 1.8 void resumeAt(in unsigned long long startPos, in ACString entityID); Attributes Attribute Type Description entityID ACString The entity id for this URI. Available after OnStartRequest. Read only. Exceptions thrown NS_ERROR_NOT_RESUMABLE If this load is not resumable. Methods asyncOpenAt
() Obsolete since Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Open this channel, and read starting at the specified offset. The request given to the nsIStreamListener will be QIable to nsIResumableInfo. void asyncOpenAt( in nsIStreamListener listener, in nsISupports ctxt, in unsigned long startPos, in nsIResumableEntityID entityID ); Parameters listener As fo...
...IResumableInfo. void asyncOpenAt( in nsIStreamListener listener, in nsISupports ctxt, in unsigned long startPos, in nsIResumableEntityID entityID ); Parameters listener As for asyncOpen. ctxt As for asyncOpen. startPos The starting offset, in bytes, to use to download. entityID Information about the file, to match before obtaining the file. Pass an empty string to use anything. resumeAt
() Prepare this channel for resuming. The request will not start until asyncOpen or open is called. Calling resumeAt after open or asyncOpen has been called has undefined behaviour. During OnStartRequest, this channel will have a status of NS_ERROR_NOT_RESUMABLE if the file cannot be resumed, for example because the server doesn't support this. This error may occur even if startPos is 0, so that the...
nsIScriptError2
sourceName, in wstring sourceLine, in PRUint32 lineNumber, in PRUint32 columnNumber, in PRUint32 flags, in string category, in unsigned long long innerWindowID); Attributes Attribute Type Description innerWindowID unsigned long long The inner window ID with which the error is associated. This is zero if the error was initialized by calling nsIScriptError.init
() instead of initWithWindowID
(). Read only. outerWindowID unsigned long long The window ID with which the error is associated. This is zero if the error was initialized by calling nsIScriptError.init
() instead of initWithWindowID
(). Read only. timeStamp long long Elapsed time, in milliseconds, from a platform-specific zero time to the time the message was created. Rea...
.... outerWindowID unsigned long long The window ID with which the error is associated. This is zero if the error was initialized by calling nsIScriptError.init
() instead of initWithWindowID
(). Read only. timeStamp long long Elapsed time, in milliseconds, from a platform-specific zero time to the time the message was created. Read only. Methods initWithWindowID
() void init( in wstring message, in wstring sourceName, in wstring sourceLine, in PRUint32 lineNumber, in PRUint32 columnNumber, in PRUint32 flags, in string category, in unsigned long long innerWindowID ); Parameters message The text of the message to add to the log. sourceName The URL of the file in which the error occurred. This will be a hyperlink in the JavaScript Cons...
nsISeekableStream
xpcom/io/nsISeekableStream.idlScriptable Provides seeking support in data streams. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void seek(in long whence, in long long offset); void setEOF
(); long long tell
(); Constants Constant Value Description NS_SEEK_SET 0 Specifies that the offset is relative to the start of the stream. NS_SEEK_CUR 1 Specifies that the offset is relative to the current position in the stream. NS_SEEK_END 2 Specifies that the offset is relative to the end of the stream. Methods seek
() This method moves the stream offset of the stream implementing this interface. void seek( in long whence, in long long offset ); Parameters whe...
...the stream offset associated with the implementing stream, according to the table of constants above. offset Specifies a value, in bytes, that is used in conjunction with the 'whence' parameter to set the stream offset of the implementing stream. A negative value causes seeking in the reverse direction. Exceptions thrown NS_BASE_STREAM_CLOSED If called on a closed stream. setEOF
() This method truncates the stream at the current offset. void setEOF
(); Parameters None. Exceptions thrown NS_BASE_STREAM_CLOSED If called on a closed stream. tell
() This method reports the current offset, in bytes, from the start of the stream. long long tell
(); Parameters None. Return value The current offset, in bytes, from the start of the stream. Exceptions thrown NS_BASE_STR...
nsISelection2
ool allowAdjacent, in RangeArray results); Native code only! void scrollIntoView(in short aRegion, in boolean aIsSynchronous, in short aVPercent, in short aHPercent); Attributes Attribute Type Description type short Returns the type of the selection (see nsISelectionController for available constants). Read only. Methods GetRangesForInterval
() Return array of ranges intersecting with the given DOM interval. void GetRangesForInterval( in nsIDOMNode beginNode, in PRInt32 beginOffset, in nsIDOMNode endNode, in PRInt32 endOffset, in PRBool allowAdjacent, out PRUint32 resultCount, [retval, array, size_is(resultCount)] out nsIDOMRange results ); Parameters beginNode beginOffset endNode endOffset These four p...
... allowAdjacent, in RangeArray results ); Parameters beginNode beginOffset endNode endOffset These four parameters represent the range to compare against the selection. allowAdjacent Specifies whether the returned ranges are allowed to touch the input range rather than merely overlapping it. results Returns the ranges that overlap (or touch) the input range. scrollIntoView
() Scrolls a region of the selection, so that it is visible in the scrolled view. void scrollIntoView( in short aRegion, in boolean aIsSynchronous, in short aVPercent, in short aHPercent ); Parameters aRegion The region inside the selection to scroll into view (see selection region constants defined in nsISelectionController). aIsSynchronous When true, scrolls the selection into vi...
nsISessionStartup
ced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5) Implemented by: @mozilla.org/browser/sessionstartup;1. To use this service, use: var sessionStartup = Components.classes["@mozilla.org/browser/sessionstartup;1"] .getService(Components.interfaces.nsISessionStartup); Method overview boolean doRestore
(); Attributes Attribute Type Description sessionType unsigned long The type of session being restored; this will be one of the Session type constants. Read only. state jsval The session state, as a JavaScript object. Read only. Note: Prior to Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5), this was a string. It was changed in order to improve performance, which was suffering ...
...evious session. RECOVER_SESSION 1 The last session crashed. It will either be restored or about:sessionrestore will be displayed. RESUME_SESSION 2 The previous session should be restored at startup. DEFER_SESSION 3 The previous session is viable but shouldn't be restored without explicit action (with the exception of app tabs, which are always restored in this case). Methods doRestore
() Determines whether or not there is a session to restore. boolean doRestore
(); Parameters None. Return value true if the session should be restored, otherwise false. ...
nsISimpleEnumerator
xpcom/ds/nsISimpleEnumerator.idlScriptable This interface represents an enumeration of XPCOM objects and provides methods to access elements sequentially. Inherits from: nsISupports Last changed in Gecko 0.9.6 Method overview nsISupports getNext
(); boolean hasMoreElements
(); Methods getNext
() Called to retrieve the next element in the enumerator. The "next" element is the first element upon the first call. Must be preceded by a call to hasMoreElements
() which returns PR_TRUE. This method is generally called within a loop to iterate over the elements in the enumerator. nsISupports getNext
(); Parameters None. Return value NS_OK if the call succeeded in returning a non-null value through the out parameter. NS_ERROR_FAILURE if there are no more elements to enumerate. has...
...pon the first call. Must be preceded by a call to hasMoreElements
() which returns PR_TRUE. This method is generally called within a loop to iterate over the elements in the enumerator. nsISupports getNext
(); Parameters None. Return value NS_OK if the call succeeded in returning a non-null value through the out parameter. NS_ERROR_FAILURE if there are no more elements to enumerate. hasMoreElements
() Called to determine whether or not the enumerator has any elements that can be returned via getNext
(). This method is generally used to determine whether or not to initiate or continue iteration over the enumerator, though it can be called without subsequent getNext
() calls. Does not affect internal state of enumerator. boolean hasMoreElements
(); Parameters None. Return value PR_TRUE if there ar...
nsISpeculativeConnect
cular site is likely to happen soon; this lets the networking layer begin setting up TCP and, if appropriate, SSL handshakes to save time when the connection is actually opened later. ...
...tually opened later. 1.0 66 Introduced Gecko 15.0 Inherits from: nsISupports Last changed in Gecko 15.0 (Firefox 15.0 / Thunderbird 15.0 / SeaMonkey 2.12) To use this service, simply call nsISupports.QueryInterface
() on the nsIIOService you plan to use for the connection, to get access to the I/O service's implementation of nsISpeculativeConnect. Then call speculativeConnect
() to let the networking layer know what you might be doing in the future. Method overview void speculativeConnect(in nsIURI aURI, in nsIInterfaceRequestor aCallbacks, in nsIEventTarget aTarget); Methods speculativeConnect
() Call this method to hint to the networking layer that a new transaction for the specified URI is likely to happen soon. The code implementing this method may use this info...
nsIStackFrame
filename string Filename location. This is the location that caused the error, which may or may not be a source file location. For example, standard language errors would generally have the same location as their top stack entry. File parsers may put the location of the file they were parsing, and so forth. null indicates "no data" Read only. ...
...ead only. lineNumber PRInt32 Valid line numbers begin at '1'. '0' indicates unknown. Read only. name string The name of the function at this point in the stack. Read only. sourceLine string The location of this function in filename Read only. Example To output the stack at a particular location: var s = Components.stack; while(s) { console.log(s.name); s = s.caller; } Methods toString
() A generic formatter - make it suitable to print, and so forth. string toString
(); Parameters None. Return value A string suitable for output. See also jsdIStackFrame ...
nsIStreamListener
netwerk/base/public/nsIStreamListener.idlScriptable This interface is used to listen to data being received on a stream. Inherits from: nsIRequestObserver Last changed in Gecko 1.0 Classes which want to consume data from a nsIChannel need to implement this interface. nsIRequestObserver contains two methods. So, in all the three methods - onDataAvailable
(), nsIRequestObserver.onStartRequest
() and nsIRequestObserver.onStopRequest
() have to be implemented. Method overview void onDataAvailable(in nsIRequest aRequest, in nsISupports aContext, in nsIInputStream aInputStream, in unsigned long aOffset, in unsigned long aCount); Methods onDataAvailable
() This method is called when the next chunk of data for the ongoing request may be read without blocking the calling thread. The...
...ataAvailable( in nsIRequest aRequest, in nsISupports aContext, in nsIInputStream aInputStream, in unsigned long aOffset, in unsigned long aCount ); Parameters aRequest An nsIRequest indicating the source of the data. aContext A user-defined context value. aInputStream An nsIInputStream from which the data is to be read. aOffset Number of bytes that were sent in previous onDataAvailable
() calls for this request. In other words, the sum of all previous count parameters. If that number is greater than or equal to 2^32, this parameter will be PR_UINT32_MAX (2^32 - 1). aCount The number of bytes available for reading. You must read all of these bytes before returning to the caller. Note: Throwing an exception will cancel the request. ...
nsIStringBundleOverride
ide); Note: You should never need to use this service directly. Instead, the string bundle service will automatically try to load this service. If there is no custom-strings.txt file then the service will fail to load. Method overview nsISimpleEnumerator enumerateKeysInBundle(in AUTF8String url); AString getStringFromName(in AUTF8String url, in ACString key); Methods enumerateKeysInBundle
() Get all override keys for a given string bundle. nsISimpleEnumerator enumerateKeysInBundle( in AUTF8String url ); Parameters url The URL of the original string bundle whose keys are to be overridden. Return value An enumeration of nsIPropertyElement objects for the keys that are overridden in the given string bundle. Note that these keys may not exist in the original string bundle. getString...
... override keys for a given string bundle. nsISimpleEnumerator enumerateKeysInBundle( in AUTF8String url ); Parameters url The URL of the original string bundle whose keys are to be overridden. Return value An enumeration of nsIPropertyElement objects for the keys that are overridden in the given string bundle. Note that these keys may not exist in the original string bundle. getStringFromName
() Get the override value for a particular key in a particular string bundle. AString getStringFromName( in AUTF8String url, in ACString key ); Parameters url The URL of the original string bundle whose keys are to be overridden. key The key to be overridden. Return value The override value. An exception is thrown if the key has not been overridden. However, no exception is thrown if the orig...
nsISupports proxies
d with the PROXY_SYNC flag. ...
...o_CreateInstance(FOO_CONTRACTID, &rv)); if(NS_FAILED(rv)) return rv; nsCOMPtr<IFoo> pProxy; rv = pIProxyObjectManager->GetProxyForObject(NS_PROXY_TO_MAIN_THREAD, IFoo::GetIID
(), pTestObj, NS_PROXY_SYNC | NS_PROXY_ALWAYS, getter_AddRefs(pProxy)); if(NS_FAILED(rv)) return rv; // we do not care about the real object anymore. // ie. GetProxyObject refcounts it. NS_RELEASE(pTestObj); pProxy->Bar
(); NS_RELEASE(pProxy); Original Document Information Author: Doug Turner Last Updated Date: January 27, 2007 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
nsITaggingService
nsigned long length, [retval, array, size_is(length)] out wstring aTags); Attributes Attribute Type Description allTags nsIVariant Retrieves all tags used to tag URIs in the data-base (sorted by name). tagContainerIconSpec AUTF8String Retrieves the URL spec for the tag container icon Methods tagURI
() This method tags a URI with the given set of tags. Current tags set for the URL persist. Tags in aTags which are already set for the given URI are ignored. void tagURI( in nsIURI aURI, in nsIVariant aTags ); Parameters aURI The URL to tag. aTags Array of tags to set for the given URI. untagURI
() This method removes tags from a URI. Tags from aTags which are ...
... tag. aTags Array of tags to set for the given URI. untagURI
() This method removes tags from a URI. Tags from aTags which are not set for the given URI are ignored. void untagURI( in nsIURI aURI, in nsIVariant aTags ); Parameters aURI The URL to un-tag. aTags Array of tags to unset. Pass NULL to remove all tags from the given URI. getURIsForTag
() This method retrieves all URIs tagged with the given tag. nsIVariant getURIsForTag( in AString aTag ); Parameters aTag The tag name. Return value Returns array of URIs tagged with aTag. getTagsForURI
() This method retrieves all tags set for the given URI. nsIVariant getTagsForURI( in nsIURI aURI, [optional] out unsigned long length, [retval, array, size_is(length)] out...
nsITaskbarPreview
indows as a common interface for both window and tab taskbar previews. 1.0 66 Introduced Gecko 1.9.2 Inherits from: nsISupports Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) You can not directly instantiate this interface. Instead, you use nsITaskbarTabPreview or nsITaskbarWindowPreview as appropriate. Method overview void invalidate
(); Attributes Attribute Type Description active boolean Indicates whether or not the preview is marked as active (currently selected) in the taskbar. controller nsITaskbarPreviewController The controller for this preview. The controller provides the behavior and appearance for the taskbar preview, a...
...r not the preview is visible; by default, this is false. Note: Changing this value is computationally expensive for tab previews, because doing so causes the proxy window to be destroyed and rebuilt, then re-registered with the taskbar. If any step of that process fails, an exception is thrown. For window previews, changing this value is computationally trivial. Methods invalidate
() Invalidates the taskbar's cached image of the preview, forcing a redraw if necessary. void invalidate
(); Parameters None. See also nsITaskbarPreviewController nsITaskbarTabPreview nsITaskbarWindowPreview nsITaskbarPreviewButton nsIWinTaskbar ...
nsITextInputProcessorNotification
won't be changed for keeping backward compatibility. Attributes Attribute Type Description type ACString The type of request or notification to IME. See type values below. Types "request-to-commit" This is required to be handled. When this is requested, the callback should commit composition synchronously, i.e., nsITextInputProcessor.commitComposition
() should be called. If the callback doesn't want to commit the composition synchronously, it's okay to commit it later (i.e., asynchronously). However, Gecko will commit the composition with the last composing string internally. This is typically notified when user clicks somewhere, focus is moved, or web contents modify the value of the editor during composition. "request-to-cancel" This is re...
...ever, Gecko will commit the composition with the last composing string internally. This is typically notified when user clicks somewhere, focus is moved, or web contents modify the value of the editor during composition. "request-to-cancel" This is required to be handled. When this is requested, the callback should cancel composition synchronously, i.e., nsITextInputProcessor.cancelComposition
() should be called. If the callback doesn't want to cancel the composition synchronously, it's okay to cancel it later (i.e., asynchronously). However, Gecko will cancel the composition with empty string internally. This is typically notified when the editor is being removed from the DOM tree during composition. "notify-detached" When the nsITextInputProcessor instance loses the rights to creat...
nsIThreadEventFilter
The nsIThreadEventFilter interface may be implemented to determine whether or not an event may be accepted by a nested event queue; see nsIThreadInternal.PushEventQueue
() for more information. You should implement this interface and its acceptEvent
() method, then pass the object implementing it as the filter. xpcom/threads/nsIThreadInternal.idlScriptable Please add a summary to this article. ...
...ethod, then pass the object implementing it as the filter. xpcom/threads/nsIThreadInternal.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Inherits from: nsISupports Method overview boolean acceptEvent(in nsIRunnable event);Violates the XPCOM interface guidelines Methods Violates the XPCOM interface guidelines acceptEvent
() This method is called to determine whether or not an event may be accepted by a nested event queue. (see nsIThreadInternal.PushEventQueue
()) Warning: This method must not make any calls on the thread object. boolean acceptEvent( in nsIRunnable event ); Parameters event The event being dispatched. Return value Implement this method to return true if the event is accepted, or f...
nsIToolkitProfile
itProfileService interface to create and obtain them. Method overview nsIProfileLock lock(out nsIProfileUnlocker aUnlocker); void remove(in boolean removeFiles); Attributes Attribute Type Description localDir nsILocalFile The location of the profile local directory, which may be the same as the root directory. See nsIProfileLock.localDirectory
(). Read only. name AUTF8String The profile's name. rootDir nsILocalFile The location of the profile directory. Read only. Methods lock
() Locks the profile using platform-specific locking methods. nsIProfileLock lock( out nsIProfileUnlocker aUnlocker ); Parameters aUnlocker On error, contains an nsIProfileUnlocker object you can use to unlock the prof...
...ject you can use to unlock the profile. Note: The unlocker object cannot be returned to JavaScript as the error causes an exception to be thrown. The unlocker object is only available in Gecko 34 or later when running on Windows Vista or later. Return value An nsIProfileLock object which holds a profile lock as long as you hold a reference to it. Example: var profile = profileList.getNext
().QueryInterface(Ci.nsIToolkitProfile); var locker = profile.lock({}); remove
() Removes the profile from the registry of profiles. void remove( in boolean removeFiles ); Parameters removeFiles Indicates whether or not the profile directory should be removed when the profile is removed from the profile list. See also Profile management nsIToolkitProfileService nsIProfileLock nsIP...
nsITreeColumn
The nsITreeColumn interface represents a tree column. layout/xul/base/src/tree/public/nsITreeColumns.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Inherits from: nsISupports Method overview void getIdConst([shared] out wstring idConst); Native code only! nsITreeColumn getNext
(); nsITreeColumn getPrevious
(); void invalidate
(); Attributes Attribute Type Description atom nsIAtom The atom attribute of nsITreeColumn which returns an nsIAtom for the column, making it fast to do comparisons. Read only. Native code only! columns nsITreeColumns The nsITreeColumns containing this column. Read only. cycler boolean If true, then the column is a cycler column. If the cycler attribute is not set, the column cells are regular text c...
...f nsITreeColumn. Read only. x long The X position in the tree of the left edge of the nsITreeColumn. Read only. Constants Constant Value Description TYPE_TEXT 1 Text column type. TYPE_CHECKBOX 2 Checkbox column type. TYPE_PROGRESSMETER 3 Progress meter column type. Methods Native code only!getIdConst void getIdConst( [shared] out wstring idConst ); Parameters idConst getNext
() Get the next column in the nsITreeColumns. nsITreeColumn getNext
(); Parameters None. Return value The next nsITreeColumn in the nsITreeColumns. getPrevious
() Get the previous column in the nsITreeColumn. nsITreeColumn getPrevious
(); Parameters None. Return value The previous nsITreeColumn in the nsITreeColumns. invalidate
() void invalidate
(); Parameters None. See also nsITreeColumns ...
nsIURLFormatter
fox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Variable names can contain 'A-Z' letters and '_' characters. Mozilla applications linking to Mozilla websites are strongly encouraged to use URLs of the following format: http[s]://%SERVICE%.mozilla.[com|org]/%LOCALE%/ Method overview AString formatURL(in AString aFormat); AString formatURLPref(in AString aPref); Methods formatURL
() Formats a string URL. The set of known variables is predefined. If a variable is unknown, it is left unchanged and a non-fatal error is reported. AString formatURL( in AString aFormat ); Parameters aFormat Unformatted URL as a string. Return value The formatted URL. formatURLPref
() Formats a string URL stored in a preference. If the preference value cannot be retrieved, a fatal error...
... formatted URL. formatURLPref
() Formats a string URL stored in a preference. If the preference value cannot be retrieved, a fatal error is reported and the "about:blank" URL is returned. AString formatURLPref( in AString aPref ); Parameters aPref A string representing the name of the preference from which to fetch the URL to format. Return value The formatted URL returned by formatURL
(), or "about:blank". ...
nsIUTF8ConverterService
intl/uconv/idl/nsIUTF8ConverterService.idlScriptable Please add a summary to this article. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview AUTF8String convertStringToUTF8(in ACString aString, in string aCharset, in boolean aSkipCheck); AUTF8String convertURISpecToUTF8(in ACString aSpec, in string aCharset); Methods convertStringToUTF8
() Ensure that aString is encoded in UTF-8. If not, convert to UTF-8 assuming it's encoded in aCharset and return the converted string in UTF-8. AUTF8String convertStringToUTF8( in ACString aString, in string aCharset, in boolean aSkipCheck, in boolean aAllowSubstitution ); Parameters aString A string to ensure its UTF8ness. aCharset The charset to convert from if aString is not i...
...m or a modified form used in IMAP folder names). aAllowSubstitution when true, allow the decoder to substitute invalid input sequences by replacement characters. Return value The converted string in UTF-8. Exceptions thrown NS_ERROR_UCONV_NOCONV When there is no decoder for aCharset or error code of nsIUnicodeDecoder in case of conversion failure. convertURISpecToUTF8
() Ensure that aSpec (after URL-unescaping it) is encoded in UTF-8. If not, convert it to UTF-8, assuming it's encoded in aCharset, and return the result. Make sure that all characters outside US-ASCII in your input spec are url-escaped if your spec is not in UTF-8 (before url-escaping) because the presence of non-ASCII characters is blindly regarded as an indication that your input spec is in unesc...
nsIUpdateItem
add-on. Read only. updateRDF AString The URL of the update RDF file for this item. Read only. version AString The Version of the item, in FVF format. Read only. xpiHash AString The string Hash for the XPI file. Can be null and if supplied must be in the format of "type:hash" (see the types in nsICryptoHash and nsIXPInstallManager.initManagerWithHashes
(). Read only. xpiURL AString The URL of the XPI where this item can be downloaded. Read only. Constants Item type constants Constants representing types of update checks. Constants that callers can use to indicate the reason for an add-on update check. Internal code uses other constants in nsExtensionManager.js.in. Constant Gecko version Description ...
... void init( in AString id, in AString version, in AString installLocationKey, in AString minAppVersion, in AString maxAppVersion, in AString name, in AString downloadURL, in AString xpiHash, in AString iconURL, in AString updateURL, in AString updateKey, in long type, in AString targetAppID ); Parameters id The item's GUID. version The it...
nsIUpdateManager
Service.idlScriptable This interface describes a global application service that maintains a list of previously installed updates, as well as the currently in use update. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method overview nsIUpdate getUpdateAt(in long index); void saveUpdates
(); Attributes Attribute Type Description activeUpdate nsIUpdate An nsIUpdate object describing the currently in use update. This update is not in the history list. Read only. updateCount long The number of updates in the history list; the updates can be fetched by calling getUpdateAt
(). Read only. Methods getUpdateAt
() Returns the update at the specified index into the history list. ns...
...umber of updates in the history list; the updates can be fetched by calling getUpdateAt
(). Read only. Methods getUpdateAt
() Returns the update at the specified index into the history list. nsIUpdate getUpdateAt( in long index ); Parameters index An index into the history list for the nsIUpdate to retrieve. Return value The nsIUpdate at the specified index into the history list. saveUpdates
() Saves all updates to disk. void saveUpdates
(); Parameters None. See also nsIUpdate nsIUpdateCheckListener nsIUpdateChecker nsIUpdatePatch nsIApplicationUpdateService nsIUpdatePrompt nsIUpdateTimerManager ...
nsIWeakReference
reference to an XPCOM object. Inherits from: nsISupports Last changed in Gecko 0.9.9 An instance of nsIWeakReference is a proxy object that cooperates with its referent to give clients a non-owning, non-dangling reference. Clients own the nsIWeakReference instance. Method overview void QueryReferent( in nsIIDRef uuid, [iid_is(uuid), retval] out nsQIResult result ); Methods QueryReferent
() This method queries an interface on the referent if it exists, and like nsISupports.QueryInterface
(), produces an owning reference to the desired interface.")}} It is designed to look and act exactly like (a proxied) nsISupports.QueryInterface
(). Do not hold on to the produced interface permanently; that would defeat the purpose of using a non-owning nsIWeakReference in the first place. void Quer...
...t ); Parameters uuid The UUID of the requested interface. ...
nsIWebBrowserFind
in Gecko 1.7 Get one by doing a GetInterface on an nsIWebBrowser. By default, the implementation will search the focused frame, or if there is no focused frame, the web browser content area. It does not by default search subframes or iframes. To change this behavior, and to explicitly set the frame to search, QueryInterface to nsIWebBrowserFindInFrames. Method overview boolean findNext
(); Attributes Attribute Type Description entireWord boolean Whether to match entire words only. Default is false. findBackwards boolean Whether to find backwards (towards the beginning of the document). Default is false (search forward). matchCase boolean Whether to match case (case sensitive) when searching. Default is false. ...
...arentFrames are set, this returns false. searchString wstring The string to search for. This must be non-empty to search. wrapFind boolean Whether the search wraps around to the start (or end) of the document if no match was found between the current position and the end (or beginning). Works correctly when searching backwards. Default is false. Methods findNext
() Finds, highlights, and scrolls into view the next occurrence of the search string, using the current search settings. Fails if the search string is empty. boolean findNext
(); Parameters None. Return value Whether an occurrence was found. See also nsIWebBrowserFindInFrames ...
nsIWebContentHandlerRegistrar
etService(Ci.nsIWebContentHandlerRegistrar); var htmlContentWindow = undefined; var registerUri = 'http://mail.live.com/secure/start?action=compose&to=%s'; var myURIHostName = Services.io.newURI(registerUri, null, null).host; // this section here is long and daunting, but its just finding a suitable contentWindow var DOMWindows = Services.wm.getEnumerator(null); while (DOMWindows.hasMoreElements
()) { var aDOMWindow = DOMWindows.getNext
(); if (aDOMWindow.gBrowser) { if (aDOMWindow.gBrowser.tabContainer) { //aDOMWindow has tabs var tabs = aDOMWindow.gBrowser.tabContainer.childNodes; for (var i = 0; i < tabs.length; i++) { console.log(tabs[i].linkedBrowser.contentWindow.location); if (tabs[i].linkedBrowser.con...
...mxr.mozilla.org/mozilla-release/source/browser/components/feeds/src/WebContentConverter.js#372 AND http://stackoverflow.com/questions/24900655/use-registerprotocolhandler-without-contentwindow place holder See also nsIWebContentSonverterService (under construction: page doesnt exist yet) registerProtocolHandler from Non-Privelaged Scope Web API Interfaces > Navigator.registerContentHandler
() Web API Interfaces > Navigator.registerProtocolHandler
() ...
nsIWebProgressListener2
IWebProgressListener Method overview void onProgressChange64(in nsIWebProgress aWebProgress, in nsIRequest aRequest, in long long aCurSelfProgress, in long long aMaxSelfProgress, in long long aCurTotalProgress, in long long aMaxTotalProgress); boolean onRefreshAttempted(in nsIWebProgress aWebProgress, in nsIURI aRefreshURI, in long aMillis, in boolean aSameURI); Methods onProgressChange64
() Notification that the progress has changed for one of the requests associated with aWebProgress. Progress totals are reset to zero when all requests in aWebProgress complete (corresponding to onStateChange being called with aStateFlags including the STATE_STOP and STATE_IS_WINDOW flags). This function is identical to nsIWebProgressListener.onProgressChange
(), except that this function supports 64...
...ss The nsIWebProgress instance that fired the notification. aRequest The nsIRequest that has new progress. aCurSelfProgress The current progress for aRequest. aMaxSelfProgress The maximum progress for aRequest. aCurTotalProgress The current progress for all requests associated with aWebProgress. aMaxTotalProgress The total progress for all requests associated with aWebProgress. onRefreshAttempted
() Notification that a refresh or redirect has been requested in aWebProgress. For example, via a <meta http-equiv="refresh"> or an HTTP Refresh: header. boolean onRefreshAttempted( in nsIWebProgress aWebProgress, in nsIURI aRefreshURI, in long aMillis, in boolean aSameURI ); Parameters aWebProgress The nsIWebProgress instance that fired the notification. aRefreshURI The new URI that aWebP...
nsIWebappsSupport
lScriptable Please add a summary to this article. ...
...boolean isApplicationInstalled( in wstring uri ); Parameters uri The uri of the web application. Return value true if the web application is installed, false if it's not installed. ...
nsIWifiListener
eceiving notifications when the list of available WiFi access points changes. ...
...void onError( in long error ); Parameters error The nsresult value indicating the error that occurred. ...
nsIWinAppHelper
ast changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Implemented by: @mozilla.org/xre/app-info;1. To create an instance, use: var xulAppInfo = Components.classes["@mozilla.org/xre/app-info;1"] .getService(Components.interfaces.nsIWinAppHelper); The nsIXULAppInfo and nsIXULRuntime interfaces are also implemented by "xre/app-info". Method overview void fixReg
(); Obsolete since Gecko 1.9 void postUpdate(in nsILocalFile logFile); Obsolete since Gecko 1.9.2 Attributes Attribute Type Description userCanElevate boolean Read only. Returns true only if all the following conditions are all true at once: The operating system is at least Windows Vista User Account Control is enabled The user is an Administrator The application is not already running ...
...nce Gecko 1.9.2 Attributes Attribute Type Description userCanElevate boolean Read only. Returns true only if all the following conditions are all true at once: The operating system is at least Windows Vista User Account Control is enabled The user is an Administrator The application is not already running with elevated permissions Otherwise it returns false. Methods fixReg
() Obsolete since Gecko 1.9 (Firefox 3) Invokes helper.exe with the /fixreg parameter. Note that this parameter was never actually supported. void fixReg
(); Parameters None. postUpdate
() Obsolete since Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Invokes helper.exe with the /postupdate parameter. This updates the uninstallation log so that the ...
nsIWorkerScope
eads/nsIDOMWorkers.idlScriptable This interface represents the global scope in which a worker's script runs. 1.0 66 Introduced Gecko 1.9.1 Inherits from: nsIWorkerGlobalScope Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Method overview void postMessage(in DOMString aMessage, [optional] in nsIWorkerMessagePort aMessagePort); void close
(); Attributes Attribute Type Description onclose nsIDOMEventListener A listener object to be called when the worker stops running. onmessage nsIDOMEventListener A listener object to be called when a message is posted on the port. 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...
...nclose nsIDOMEventListener A listener object to be called when the worker stops running. onmessage nsIDOMEventListener A listener object to be called when a message is posted on the port. 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. ...
nsIXMLHttpRequest
.... Conclusion: Do not use event listeners on XMLHttpRequest from C++, unless you're aware of all the security implications. And then think twice about it. ...
...BufferInputStream out of it or something xhr.send(null); } xhr('https://www.gravatar.com/avatar/eb9895ade1bd6627e054429d1e18b576?s=24&d=identicon&r=PG&f=1', data => { Services.prompt.alert(null, 'XHR Success', data); var file = OS.Path.join(OS.Constants.Path.desktopDir, "test.png"); var promised = OS.File.writeAtomic(file, new UInt8Array(data)); promised.then( function
() { alert('succesfully saved image to desktop') }, function(ex) { alert('FAILED in saving image to desktop') } ); }); ...
nsIXULRuntime
Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Implemented by: @mozilla.org/xre/app-info;1. To get an instance, use: var xulRuntime = Components.classes["@mozilla.org/xre/app-info;1"] .getService(Components.interfaces.nsIXULRuntime); Method overview void invalidateCachesOnRestart
(); Attributes Attribute Type Description accessibilityEnabled boolean If true, the accessibility service is running. Read only. browserTabsRemoteAutostart boolean If true, browser tabs may be opened by default in a different process from the main browser UI. Read only. inSafeMode boolean Whether the application was launched i...
... Read only. Constants Process type constants Constant Value Description PROCESS_TYPE_DEFAULT 0 The default (chrome) process. PROCESS_TYPE_PLUGIN 1 A plugin subprocess. PROCESS_TYPE_CONTENT 2 A content subprocess. PROCESS_TYPE_IPDLUNITTEST 3 IPDL unit testing subprocess. Methods invalidateCachesOnRestart
() Signal the apprunner to invalidate caches on the next restart. This will cause components to be auto registered and all fast load data to be re-created. void invalidateCachesOnRestart
(); Parameters None. Example Display the user's operating system in an alert box: var xulRuntime = Components.classes["@mozilla.org/xre/app-info;1"] .getService(Components.interface...
NS ENSURE TRUE
Summary Macro Returns return-value if expr evaluates to false. Syntax NS_ENSURE_TRUE( expr, return-value ); Usage nsresult mozMyClass::MozStringMucking
() { char *foo = new char[123]; NS_ENSURE_TRUE(foo, NS_ERROR_OUT_OF_MEMORY); // This is equivalent to doing: if (!foo) return NS_ERROR_OUT_OF_MEMORY; // Thou shalt not return NS_ERROR_FAILURE.. ...
... NS_ENSURE_TRUE( expr, return-value ); Usage nsresult mozMyClass::MozStringMucking
() { char *foo = new char[123]; NS_ENSURE_TRUE(foo, NS_ERROR_OUT_OF_MEMORY); // This is equivalent to doing: if (!foo) return NS_ERROR_OUT_OF_MEMORY; // Thou shalt not return NS_ERROR_FAILURE.. ...
nsMsgViewCommandType
ead. deleteMsg 7 Move the selected message to the accounts trash. deleteNoTrash 8 Delete the selected message. markThreadRead 9 Mark all messages in a thread as read. markAllRead 10 Mark all messages currently shown as read expandAll 11 Expand all threads. collapseAll 12 Collapse all threads. copyMessages 13 Copy the selected messages. Use with nsIMsgDBView.doCommandWithFolder
() to select the destination folder. moveMessages 14 Move the selected messages. Use with nsIMsgDBView.doCommandWithFolder
() to select the destination folder. selectAll 15 Select all messages. downloadSelectedForOffline 16 Download the selected messages for offline. downloadFlaggedForOffline 17 Download all flagged messages for offline. selectThread 18 Select the entire thread. sele...
...reload or print preview) are available. label0 21 Attach a label to the selected messages. label1 22 Attach a label to the selected messages. label2 23 Attach a label to the selected messages. label3 24 Attach a label to the selected messages. label4 25 Attach a label to the selected messages. ...
Using nsIDirectoryService
Content formerly at http://www.mozilla.org/projects/xpcom/nsDirectoryService.html General nsDirectoryService Information: nsDirectoryService implements the nsIProperties interface. This implementation will allow you to Get
(), Set
(), Define
(), and Undefine
() nsIFile. Getting a location: Most developers need to find where a file or directory is located. With nsDirectoryService, there are two steps involved. First, you must know what the string key (or property) is that refers to this locations. Header files containing known keys are listed in the Known Locations section of this document. Bear in mind that this list is not static. Components can add and remove locations at their will. Second, you must acquire the implementation and call Get
() passing the known string key. In the example...
...is object has to implement the nsISupports and nsIDirectoryServiceProvider interfaces. It does not need to be a component - it can be a static lib, a source file in your project - whatever. Just construct it, pass it to NS_InitEmbedding, and it will be installed. If you are not using NS_InitEmbedding, you will have to construct it and register it yourself using nsIDirectoryService.registerProvider
(). If you are registering it yourself it is very important to register it immediately after calling NS_InitXPCOM. There are things in the startup process that need these locations at a very early point - even before registering components. If you want to use mpfilelocprovider, or something like it, to provide one fixed profile, just construct it and call its Initialize method - it will register its...
Using nsIPasswordManager
ing a password from the password manager is more difficult. ...
...g for var queryString = 'http://www.example.com'; // ask the password manager for an enumerator: var e = passwordManager.enumerator; // step through each password in the password manager until we find the one we want: while (e.hasMoreElements
()) { try { // get an nsIPassword object out of the password manager. // This contains the actual password... ...
Working with out parameters
ing the method call. These are so-called out parameters. Usage In order to use such a method from JavaScript via XPConnect, you have to follow a specific rule. To get at the out parameters, you have to pass in an object. After the call, this object will have a new property called value, which contains the out values. Assuming you have an object called transferable, you would invoke getTransferData
() as follows: var aData = {}; var aDataLen = {}; transferable.getTransferData("text/unicode", aData, aDataLen); var data = aData.value; var dataLen = aDataLen.value; As you can see, after the call to getTransferData
(), the out values are then contained in the value properties of aData and aDataLen. Implementation When implementing a method which has out parameters in JavaScript, you have t...
... = aData.value; var dataLen = aDataLen.value; As you can see, after the call to getTransferData
(), the out values are then contained in the value properties of aData and aDataLen. Implementation When implementing a method which has out parameters in JavaScript, you have to set a new property called value to the out parameter which will hold the required value. You would implement getTransferData
() as follows: getTransferData: function(aFlavor, aData, aDataLen) { .. .. aData.value = resultData; aDataLen.value = resultData.length; } ...
XPIDL
lar property access, while native code sees attributes as a Get and possibly a Set method. Attributes can be declared readonly, in which case setting causes an error to be thrown in script contexts and native contexts lack the Set method, by using the "readonly" keyword. To native code, on attribute declared 'attribute type foo;' is syntactic sugar for the declaration of two methods 'type getFoo
();' and 'void setFoo(in type foo);'. If foo were declared readonly, the latter method would not be present. Attributes support all of the properties of methods with the exception of optional_argc, as this does not make sense for attributes. There are some special rules for attribute naming. As a result of vtable munging by the MSVC++ compiler, an attribute with the name `IID' is forbidden. In addi...
...sresult, and the return type acts as a final outparameter if it is not void. The name is translated so that the first character is unconditionally uppercase; subsequent characters are unaffected. However, the presence of the binaryname property allows the user to select another name to use in native code (to avoid conflicts with other functions). For example, the method '[binaryname(foo)] void bar
();' becomes 'nsresult Foo
()' in native code (note that capitalization is still applied). However, the capitalization is not applied when using binaryname with attributes; i.e., [binaryname(foo)] readonly attribute Quux bar; becomes Getfoo(Quux**) in native code. Attributes named 'IID' and methods named 'GetIID' are forbidden, although this is checked before binaryname conversion. The implicit_jsco...
XUL Overlays
Thus, given the following base: ... <menu id="file-menu"> <menupopup id="menu_FilePopup"> <menuitem name="New"/> <menuitem name="Open"/> <menuitem name="Save"/> <menuitem name="Close"/> </menupopup> </menu> ... And given the following overlay: <?xml version="1.0"?> <overlay id="singleItemE...
...lled with the browser. When a component such as the "Super Stream Player" from the examples above is registered there, overlays associated with that component are loaded automatically. When the component is not present, only the base files are loaded. Loading overlays at runtime Firefox 1.5 and other Gecko 1.8-based applications also support loading overlays on-the-fly via the document.loadOverlay
() function. TODO: elaborate Overlays and skins Warning: Always load master skins from base files. Never load master skins from overlays. Unlike base files, overlays should never load the master skin file for a package. The navigatorOverlay.xul file, for example, does not and should never load the navigator.css file that defines the master skin for the navigator package. Since the purpose of an ov...
Address Book examples
e Address Book Manager to get an nsISimpleEnumerator, then progress through the enumerator, looking for nsIAbItem, nsIAbCollection or nsIAbDirectory interfaces as you require. let abManager = Components.classes["@mozilla.org/abmanager;1"] .getService(Components.interfaces.nsIAbManager); let allAddressBooks = abManager.directories; while (allAddressBooks.hasMoreElements
()) { let addressBook = allAddressBooks.getNext
() .QueryInterface(Components.interfaces.nsIAbDirectory); if (addressBook instanceof Components.interfaces.nsIAbDirectory) { // or nsIAbItem or nsIAbCollection // alert ("Directory Name:" + addressBook.dirName); ... } } How do I get one address book? Address Books are uniquely identified by a URI. This...
...IComponent("mystr") The search queries use Lisp syntax with operators enumerated in nsAbQueryStringToExpression.cpp. Assuming you wish to search across multiple directories: let abManager = Components.classes["@mozilla.org/abmanager;1"] .getService(Components.interfaces.nsIAbManager); let allAddressBooks = abManager.directories; while (allAddressBooks.hasMoreElements
()) { let ab = allAddressBooks.getNext
(); if (ab instanceof Components.interfaces.nsIAbDirectory && !ab.isRemote) { let searchResult = abManager.getDirectory(ab.URI + "?" + searchQuery).childCards; // ... use searchResult as required. } } Note: This method doesn't work with remote address books (e.g. LDAP). Hence the additional !ab.isRemote check How do I add/edit/delete con...
Address book sync client design
// mapping table. // Public Interfaces There is a very simple interface to the address book sync component. This interface is defined in mozilla/mailnews/addrbook/public/nsIAbSyncDriver.idl #include "nsrootidl.idl" #include "nsIAbSyncListener.idl" [scriptable, uuid(91FDFEE1-EFBC-11d3-8F97-000073757374)] interface nsIAbSyncDriver : nsIAbSyncListener { void KickIt
(); }; As you can see, this is a very simple interface which allows for the starting of the address book sync operation. The interface of greater interest is the address book sync listener. This provides feedback of the current sync operation. This interface is as follows: #include "nsISupports.idl" #include "nsrootidl.idl" #include "nsIFileSpec.idl" [scriptable, uuid(E0ED29E0-098A-11d4-8FD6-0...
...provides feedback of the current sync operation. This interface is as follows: #include "nsISupports.idl" #include "nsrootidl.idl" #include "nsIFileSpec.idl" [scriptable, uuid(E0ED29E0-098A-11d4-8FD6-00A024A7D144)] interface nsIAbSyncListener : nsISupports { /** * Notify the observer that the AB Sync Authorization operation has begun. * */ void OnStartAuthOperation
(); /** * Notify the observer that the AB Sync operation has been completed. * * This method is called regardless of whether the the operation was * successful. * * aTransactionID - the ID for this particular request * aStatus - Status code for the sync request * aMsg - A text string describing the error (if any). ...
Mail event system
t increases. The folder pane needs to know that this changed so that it can update the message count so the user can see it. Interfaces The key interfaces here are: nsIFolder.idl is an interface for storing a hierarchy of objects with properties. This interface is not (should not be) mail-related. nsIFolders each store individual lists of folder listeners which are maintained with addListener
() and removeListener
(). When a notification is fired on a folder, all of the folder's folder listeners and the mail session itself is notified. nsIFolderListener.idl is an interface that an object can implement if it is interested in listening to changes on single folder or on all folders. If the object just needs to be notified about one folder, it should call that folder's addListener method. If...
..., a listener will be set up to be notified when the message count changes in a folder: // our variable to know if the listener fired var listenerHasFired = false; var totalMessagesListenerHasFired = false; // the listening function that will react to changes function myOnIntPropertyChanged(item, property, oldValue, newValue) { listenerHasFired=true; var propertyString = property.GetUnicode
(); dump("OnIntPropertyChanged has fired with property + " + propertyString + "!\n"); if (propertyString == "TotalMessages") { totalMessagesListenerHasFired=true; //now show us visually var folder = item.QueryInterface(Components.interfaces.nsIMsgFolder); dump("The folder " + folder.prettyName + " now has " + newValue + " messages."); } else if (propertyString ...
Filter Incoming Mail
ng mime conversion interface var mimeConvert = Components.classes["@mozilla.org/messenger/mimeconverter;1"] .getService(Components.interfaces.nsIMimeConverter); var subject = mimeConvert.decodeMimeHeader(aMsgHdr.subject, null, false, true); // Here with have a string to modify with Javascript. ...
...rue); // Here with have a string to modify with Javascript. By example, setting it to lower case subject = subject.toLocaleLowerCase
(); // Then we rebuild a subject objet by rencoding the string // and assign it to the message headers and we're done aMsgHdr.subject = mimeConvert.encodeMimePartIIStr_UTF8(subject, false, "UTF-8", 0, 72); } } }; function init
() { var notificationService = Components.classes["@mozilla.org/messenger/msgnotificationservice;1"] .getService(Components.interfaces.nsIMsgFolderNotificationService); notificationService.addListener(newMailListener, notificationService.msgAdded); } addEventListener("load", init, true); Have a look to nsIMsgDBHdr to get the full list of properties to be modified. You can take a look at ...
Use SQLite
se. This will create an SQLite db named tbird.sqlite inside your profile directory with a table called attachments. You can see the schema for the attachments table in the code. To double check the information you've inserted you can query the tbird.sqlite file using regular SQLite programs. const Cc = Components.classes; const Ci = Components.interfaces; var tbirdsqlite = { onLoad: function
() { // initialization code this.initialized = true; this.dbInit
(); }, dbConnection: null, dbSchema: { tables: { attachments:"id INTEGER PRIMARY KEY, \ name TEXT \ encoded TEXT NOT NULL" } }, dbInit: function
() { var dirService = Cc["@mozilla.org/file/directory_service;1"]. getService(Ci...
...ncoded TEXT NOT NULL" } }, dbInit: function
() { var dirService = Cc["@mozilla.org/file/directory_service;1"]. getService(Ci.nsIProperties); var dbFile = dirService.get("ProfD", Ci.nsIFile); dbFile.append("tbird.sqlite"); var dbService = Cc["@mozilla.org/storage/service;1"]. ...
customDBHeaders Preference
es header so that we can extract the 'X-Superfluous' field var key = gDBView.getKeyAt(row); var hdr = gDBView.db.GetMsgHdrForKey(key); var retval = hdr.getStringProperty("x-superfluous"); dump("x-superfluous: " + retval + "\n"); return retval; }, getSortStringForRow: function(hdr) { return hdr.getStringProperty("x-superfluous"); }, isString: function
() {return true;}, getCellProperties: function(row, col, props){}, getImageSrc: function(row, col) {return null;}, getSortLongForRow: function(hdr) {return 0;} } function addCustomColumnHandler
() { gDBView.addColumnHandler("colSuperfluous",columnHandler); dump("column handler being added: " + columnHandler + "\n"); } var CreateDbObserver = { // Components.interfaces.nsIO...
...eturn null;}, getSortLongForRow: function(hdr) {return 0;} } function addCustomColumnHandler
() { gDBView.addColumnHandler("colSuperfluous",columnHandler); dump("column handler being added: " + columnHandler + "\n"); } var CreateDbObserver = { // Components.interfaces.nsIObserver observe: function(aMsgFolder, aTopic, aData) { dump("HERE HERE!"); addCustomColumnHandler
(); } } function doOnceLoaded
(){ var ObserverService = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService); ObserverService.addObserver(CreateDbObserver, "MsgCreateDBView", false); window.document.getElementById('folderTree').addEventListener("select",addCustomColumnHandler,false); } window.addEventListener("load",doOnceLoaded,false)...
libmime content type handlers
ll be * called upon by libmime to process various attachments types. ...
...nline_display; } contentTypeHandlerInitStruct; #include "prtypes.h" #include "nsISupports.h" #include "mimecth.h" // {20DABD99-F8B5-11d2-8EE0-00A024A7D144} #define NS_IMIME_CONTENT_TYPE_HANDLER_IID \ { 0x20dabd99, 0xf8b5, 0x11d2, \ { 0x8e, 0xe0, 0x0, 0xa0, 0x24, 0xa7, 0xd1, 0x44 } } class nsIMimeContentTypeHandler : public nsISupports { public: static const nsIID& GetIID
() { static nsIID iid = NS_IMIME_CONTENT_TYPE_HANDLER_IID; return iid; } NS_IMETHOD GetContentType(char **contentType) = 0; NS_IMETHOD CreateContentTypeHandlerClass(const char *content_type, contentTypeHandlerInitStruct *initStruct, MimeObjectClass **objClass) = 0; }; #endif /* nsIMimeContentT...
Using C struct and pointers
new ctypes.StructType("st_t", [ { "self": ctypes.PointerType(ctypes.void_t) }, { "str": ctypes.PointerType(ctypes.char) }, { "buff_size": ctypes.size_t }, { "i": ctypes.int }, { "f": ctypes.float }, { "c": ctypes.char } ]); Here we are using the StructType
() factory method of the ctypes object to create a CType object that represents the C struct named st_t. The first parameter of this method is the name of the type, which corresponds to the name of the C struct. The second parameter is an array of field descriptors. Each field descriptor contains the name and field type of the corresponding field of the C struct. The call to StructType
() returns...
... References This example is based on code found here. ...
PointerType
ns a CType representing the data type "pointer to this type". This is the result of calling ctypes.PointerType(the_type). Read only. size Number The size of the type, in bytes. This is the same value as the C sizeof. Read only. Note: ctypes.void_t.size is undefined. Method overview Methods inherited from CType CType array([n]) String toSource
() String toString
() PointerType CData Syntax CData pointertype
(); pointertype is PointerType CType. Return value A CData representing the newly allocated pointer. PointerType CData Properties Property Type Description contents CData Reading this property returns a CData object referring to the pointed-to contents of the object. Writing to this va...
... constructor CType The data type of the CData object, as a CType. Read only. Note: This is never ctypes.void_t or an array type with an unspecified length. value object The JavaScript equivalent of the CData object's value. This will throw a TypeError exception if the value can't be converted. PointerType CData Method_overview bool isNull
() Methods inherited from CData CData address
() String toSource
() String toString
() PointerType CData Methods isNull
() Determines whether or not the pointer's value is null. bool isNull
(); Parameters None. Return value true if the pointer's value is null, otherwise false. See Also CType CData Type conversion ...
Mozilla
e various parts of the codebase. Android-specific test suites There are several Android-specific test suites that run on the Firefox for Android codebase: API change rules Until further notice, the following rules govern API changes: Application cache implementation overview This happens in nsHttpChannel::OpenCacheEntry
(). All top level document loading (navigation) channels are set ChooseApplicationCache flag, which happens in nsDocShell::DoURILoad
(). Channels having that flag set are searching for nsIApplicationCache object prior inspecting normal HTTP cache. nsIApplicationCacheService::ChooseApplicationCache is given the URL the channel is about to load. It synchronously returns an nsIApplicationCac...
... Httpd.js IME handling guide This document explains how Gecko handles IME. Implementing Download Resuming This document describes how an embedder or other Gecko/Necko-using application can implement download resuming. Implementing QueryInterface This document describes the right way to write QueryInterface
(). Infallible memory allocation There's ongoing work to implement infallible memory allocators. These are memory allocation routines that never return null; that is, they always successfully return the requested block of memory. This is in contrast to a traditional, fallible memory allocator that can return null indicating that the request failed. ...
Version, UI, and Status Information - Plugins
rts by using NPN_Version to get the version numbers. It then uses the netscape_minor version number to find out if the windowless feature, represented by the NPVERS_HAS_WINDOWLESS constant, is supported. If the method returns true, a windowless plug-in can confidently proceed. If false is returned, windowless plug-ins will not work, and the developer must provide alternatives. Bool has_windowless
() { int plugin_major, plugin_minor; int netscape_major, netscape_minor; /* Find the version numbers. */ NPN_Version(&plugin_major, &plugin_minor, &netscape_major, &netscape_minor); /* Use the netscape_minor version number: */ /* Does this version support the windowless feature? */ if (netscape_minor < NPVERS_HAS_WINDOWLESS) { /* Plug-in is running in a version of ...
... /* Plug-in is running in a Navigator version */ /* that has windowless support */ return TRUE; } Detecting Windowless Support on other platforms Browser implementations on other platforms did not have windowless plug-in support at the time it was added to MS Windows and Mac OS X, so a different method must be used to detect whether the browser provides support. Bool has_windowless
() { NPBool supportsWindowless = FALSE; NPError ret = NPN_GetValue(instance, NPNVSupportsWindowless, &supportsWindowless); return ret == NPERR_NO_ERROR && supportsWindowless; } Reloading a Plug-in When the browser starts up, it loads all the plug-ins it finds in the Plugins directory for the platform. If you call NPN_ReloadPlugins, the browser reloads all plug-ins in the Plugins direct...
Break on DOM mutation - Firefox Developer Tools
set the breakpoint. There are three choices: Subtree Modification Execution pauses if any of the element's descendant nodes are modified. That means, the script execution is stopped whenever a child node or descendant node deeper in the DOM structure is added to or removed from the element the option is set on. Examples for when this breakpoint is triggered are calling Node.appendChild
() and Node.removeChild
(), calling ChildNode.remove
() or setting Element.innerHTML on one of the subnodes. Attribute Modification Execution pauses when any of the elements' attributes are modified. That means, the script execution is stopped whenever an attribute is added to or removed from the element the option is set on or the value of one of its attributes is changed. Examples for when thi...
...ting Element.innerHTML on one of the subnodes. Attribute Modification Execution pauses when any of the elements' attributes are modified. That means, the script execution is stopped whenever an attribute is added to or removed from the element the option is set on or the value of one of its attributes is changed. Examples for when this breakpoint is triggered are calling Element.setAttribute
(), Element.removeAttribute
(), and Element.classList.add
(), or setting Element.id. Node Removal Execution pauses if the element the option is set on is removed. Examples for when this breakpoint is triggered are calling Element.remove
() or Node.removeChild
() on its parent node. Once you set the breakpoint, go to the Debugger. You can see the breakpoint listed in the right-most panel under DOM...
Debug eval sources - Firefox Developer Tools
This source is then listed in the source list pane, and can be opened and debugged like any other source. ...
...This source is then listed in the source list pane, and can be opened and debugged like any other source. ...
Aggregate view - Firefox Developer Tools
n allocation trace: open the Memory tool check "Record call stacks" load https://mdn.github.io/performance-scenarios/dom-allocs/alloc.html take a snapshot select "View/Aggregate" select "Group by/Call Stack" You should see something like this: This is telling us that 93% of the total heap snapshot was allocated in functions called from "alloc.js", line 35 (our initial createToolbars
() call). We can use the disclosure arrow to expand the tree to find out exactly where we're allocating memory: This is where the "Bytes" and "Count" columns are useful: they show allocation size and number of allocations at that exact point. So in the example above, we can see that we made 4002 allocations, accounting for 89% of the total heap, in createToolbarButton
(), at alloc.js line 9, pos...
...k" view helps with that. It gives you the bottom-up view of the program showing the exact places where allocations are happening, ranked by the size of allocation at each place. The disclosure arrow then walks you back up the call tree towards the top level. Let's see what the example looks like when we select "Inverted Call Stack": Now at the top we can immediately see the createToolbarButton
() call accounting for 89% of the heap usage in our page. (no stack available) In the example above you'll note that 7% of the heap is marked "(no stack available)". This is because not all heap usage results from your JavaScript. For example: any scripts the page loads occupy heap space sometimes an object is allocated when there is no JavaScript on the stack. For example, DOM Event objects ...
Migrating from Firebug - Firefox Developer Tools
ug 963933. Debugger What's the Script panel in Firebug, is the Debugger panel in the DevTools. Both allow you to debug JavaScript code executed on a website. Switch between sources Firebug has a Script Location Menu listing all JavaScript sources related to the website. Those sources can be static, i.e. files, or they can be dynamically generated (i.e. scripts executed via event handlers, eval
(), new Function
(), etc.). In the DevTools' Debugger panel the scripts are listed at the left side within the Sources side panel. Dynamically generated scripts are only listed there when they are named via a //# sourceURL comment. Managing breakpoints In Firebug you can set different types of breakpoints, which are all listed within the Breakpoints side panel. In the DevTools the breakpoints are s...
...yle sheets via the search field. The Style Editor in the DevTools also provides a way to search within a style sheet, though there is currently no option to search within multiple sheets (see bug 889571) and also not via a regular expression (see bug 1362030. Performance Tool Firebug allows to profile JavaScript performance via the "Profile" button within the Console panel or the console.profile
() and console.profileEnd
() commands. The DevTools provide advanced tooling regarding performance profiling. A profile can be created via console.profile
() and console.profileEnd
() like in Firebug or via the "Start Recording Performance" button in the Performance Tool. The output of the Call Tree is the one that comes nearest to the output in Firebug, but the Performance panel provides much more inf...
Network request list - Firefox Developer Tools
licking on a row in the list displays a context menu with the following options: Menuitem Description Copy > Copy URL Copies the URL. Copy > Copy as cURL Copies the network request to the clipboard as a cURL command, so you can execute it from a command line. See Copy as cURL, below. Copy > Copy as Fetch Copies the request as a call to the fetch
() method, including the URL and any settings object. Copy > Copy Request Headers Copies the request's header to the clipboard. Copy > Copy Response Headers Copies the headers of the response for this request, to the clipboard. Copy > Copy Response Copies the entire response that was sent for this request. Copy > Copy All As HAR Creates an HTTP Archive...
... selected URL for future requests. See Blocking a specific URL from the Request List. Open in New Tab Resends the request in a new tab -- very useful for debugging asynchronous requests. Open in Style Editor For a CSS resource, opens it in the Style Editor. Start Performance Analysis Use as Fetch in Console Submits the request as a call to the fetch
() method in the console. Copy as cURL The command may include the following options: -X [METHOD] If the method is not GET or POST --data For URL encoded request parameters --data-binary For multipart request parameters --http/VERSION If the HTTP version is not 1.1 -I If the method is HEAD -H One for each request h...
Accelerometer - Web APIs
To use this sensor, the user must grant permission to the 'accelerometer', device sensor through the Permissions API. If a feature policy blocks the 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 Accelerometer.Accelerometer
() Creates a new Accelerometer object. Properties Accelerometer.x Read only Returns a double containing the acceleration of the device along the device's x axis. Accelerometer.y Read only Returns a double containing the acceleration of the device along the device's y axis. Accelerometer.z Read only Returns a double containing the acceleration of the device along the device's z axis. ...
...ontaining the acceleration of the device along the device's y axis. Accelerometer.z Read only Returns a double containing the acceleration of the device along the device's z axis. Example Acceleration is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. let acl = new Accelerometer({frequency: 60}); acl.addEventListener('reading',
() => { console.log("Acceleration along the X-axis " + acl.x); console.log("Acceleration along the Y-axis " + acl.y); console.log("Acceleration along the Z-axis " + acl.z); }); acl.start
(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. AccelerometerThe definition of 'Accelerometer' i...
AesCtrParams - Web APIs
AES is a block cipher, meaning that it splits the message into blocks and encrypts it a block at a time. In CTR mode, every time a block of the message is encrypted, an extra block of data is mixed in. This extra block is called the "counter block". ...
...re used for the actual counter. The counter must be big enough that it doesn't wrap: if the message is n blocks and the counter is m bits long, then the following must be true: n <= 2m. The NIST SP800-38A standard, which defines CTR, suggests that the counter should occupy half of the counter block (see Appendix B.2), so for AES it would be 64. Examples See the examples for SubtleCrypto.encrypt
() and SubtleCrypto.decrypt
(). Specifications Specification Status Comment Web Cryptography APIThe definition of 'SubtleCrypto.AesCtrParams' in that specification. Recommendation ...
AmbientLightSensor - Web APIs
s sensor, the user must grant permission to the 'ambient-light-sensor' 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. ...
...e shown to a user. See Feature-Policy for implementation instructions. Constructor AmbientLightSensor.AmbientLightSensor
() Creates a new AmbientLightSensor object. Properties AmbientLightSensor.illuminance Returns the current light level in lux of the ambient light level around the hosting device. Example if ( 'AmbientLightSensor' in window ) { const sensor = new AmbientLightSensor
(); sensor.onreading =
() => { console.log('Current light level:', sensor.illuminance); }; sensor.onerror = (event) => { console.log(event.error.name, event.error.message); }; sensor.start
(); } Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. Ambient Light SensorThe definitio...
Animation.oncancel - Web APIs
The oncancel property of the Web Animations API's Animation interface is the event handler for the cancel event. The cancel event can be triggered manually with Animation.cancel
() when the animation enters the "idle" play state from another state, such as when the animation is removed from an element before it finishes playing Creating a new animation that is initially idle does not trigger a cancel event on the new animation. ...
...ying Creating a new animation that is initially idle does not trigger a cancel event on the new animation. Syntax var cancelHandler = Animation.oncancel; Animation.oncancel = cancelHandler; Value A function to be executed when the animation is cancelled, or null if there is no cancel event handler. Examples If this animation is canceled, remove its element. animation.oncancel = function
() { animation.effect.target.remove
(); }; Specifications Specification Status Comment Web AnimationsThe definition of 'Animation.oncancel' in that specification. Working Draft Editor's draft. ...
Animation.onfinish - Web APIs
The "paused" play state supersedes the "finished" play state; if the animation is both paused and finished, the "paused" state is the one that will be reported. ...
...veral times in the Alice in Web Animations API Land Growing/Shrinking Alice Game. Here is one instance where we add pointer events back to an element after its opacity animation has faded it in: // Add an animation to the game's ending credits var endingUI = document.getElementById("ending-ui"); var bringUI = endingUI.animate(keysFade, timingFade); // Pause said animation's credits bringUI.pause
(); // This function removes pointer events on the credits. hide(endingUI); // When the credits are later faded in, // we re-add the pointer events when they're done bringUI.onfinish = function
() { endingUI.style.pointerEvents = 'auto'; }; Specifications Specification Status Comment Web AnimationsThe definition of 'Animation.onfinish' in that specification. Working ...
Animation.playState - Web APIs
Working Draft ...
...) { el.animate( tearsFalling, { delay: getRandomMsRange(-1000, 1000), // randomized for each tear duration: getRandomMsRange(2000, 6000), // randomized for each tear iterations: Infinity, easing: 'cubic-bezier(0.6, 0.04, 0.98, 0.335)' }); el.pause
(); }); // Play the tears falling when the ending needs to be shown. tears.forEach(function(el) { el.play
(); }); // Reset the crying tears animations and pause them. tears.forEach(function(el) { el.pause
(); el.currentTime = 0; }); Specifications Specification Status Comment Web AnimationsThe definition of 'playState' in that specification. Working Draft Initial definition. ...
Animation.ready - Web APIs
Since the same Promise is used for both pending play and pending pause requests, authors are advised to check the state of the animation when the promise is resolved. Syntax var readyPromise = Animation.ready; Value A Promise which resolves when the animation is ready to be played. ...
...imation.ready.then(function
() { // Do whatever needs to be done when // the animation is ready to run }); Example In the following example, the state of the animation will be running when the current ready Promise is resolved because the animation does not leave the pending play state in between the calls to pause and play and hence the current ready Promise does not change. animation.pause
(); animation.ready.then(function
() { // Displays 'running' alert(animation.playState); }); animation.play
(); Specifications Specification Status Comment Web AnimationsThe definition of 'Animation.ready' in that specification. Working Draft Editor's draft. ...
Animation.startTime - Web APIs
is currently set at, and you can change this value to make the animation start at a different time. Examples In the Running on Web Animations API example, the we can sync all new animated cats by giving them all the same startTime as the original running cat: var catRunning = document.getElementById ("withWAAPI").animate(keyframes, timing); /* A function that makes new cats. ...
...by giving them all the same startTime as the original running cat: var catRunning = document.getElementById ("withWAAPI").animate(keyframes, timing); /* A function that makes new cats. */ function addCat
(){ var newCat = document.createElement("div"); newCat.classList.add("cat"); return newCat; } /* This is the function that adds a cat to the WAAPI column */ function animateNewCatWithWAAPI
() { // make a new cat var newCat = addCat
(); // animate said cat with the WAAPI's "animate" function var newAnimationPlayer = newCat.animate(keyframes, timing); // set the animation's start time to be the same as the original .cat#withWAAPI newAnimationPlayer.startTime = catRunning.startTime; // Add the cat to the pile. WAAPICats.appendChild(newCat); } Reduced time precision T...
AnimationEvent - Web APIs
Properties Also inherits properties from its parent Event. AnimationEvent.animationName Read only Is a DOMString containing the value of the animation-name that generated the animation. AnimationEvent.elapsedTime Read only Is a float giving the amount of time the animation has been running, in seconds, when this event fired, e...
...ich case the event will be fired with elapsedTime containing (-1 * delay). AnimationEvent.pseudoElement Read only Is a DOMString, starting with '::', containing the name of the pseudo-element the animation runs on. If the animation doesn't run on a pseudo-element but on the element, an empty string: ''. Methods Also inherits methods from its parent Event. AnimationEvent.initAnimationEvent
() Initializes a AnimationEvent created using the deprecated Document.createEvent("AnimationEvent") method. Specifications Specification Status Comment CSS AnimationsThe definition of 'AnimationEvent' in that specification. Working Draft Initial definition. ...
AudioDestinationNode.maxChannelCount - Web APIs
The maxchannelCount property of the AudioDestinationNode interface is an unsigned long defining the maximum amount of channels that the physical device can handle. The AudioNode.channelCount property can be set between 0 and this value (both included). If maxChannelCount is 0, like in OfflineAudioContext, the channel count cannot be changed. ...
...luded). If maxChannelCount is 0, like in OfflineAudioContext, the channel count cannot be changed. Syntax var audioCtx = new AudioContext
(); var myDestination = audioCtx.destination; myDestination.maxChannelCount = 2; Value An unsigned long. Example The following would set up a simple audio graph, featuring an AudioDestinationNode with maxChannelCount of 2: var audioCtx = new AudioContext
(); var source = audioCtx.createMediaElementSource(myMediaElement); source.connect(gainNode); audioCtx.destination.maxChannelCount = 2; gainNode.connect(audioCtx.destination); To see a more complete implementation, check out one of our MDN Web Audio examples, such as Voice-change-o-matic or Violent Theremin. Specifications Specification Status Comment Web Audio APIThe defi...
AudioNode.channelCount - Web APIs
mixing connections to any inputs to the node. channelCount's usage and precise definition depend on the value of AudioNode.channelCountMode: It is ignored if the channelCountMode value is max. It is used as a maximum value if the channelCountMode value is clamped-max. It is used as the exact value if the channelCountMode value is explicit. ...
...untMode value is max. It is used as a maximum value if the channelCountMode value is clamped-max. It is used as the exact value if the channelCountMode value is explicit. Syntax var oscillator = audioCtx.createOscillator
(); var channels = oscillator.channelCount; Value An integer. Example var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext
(); var oscillator = audioCtx.createOscillator
(); var gainNode = audioCtx.createGain
(); oscillator.connect(gainNode); gainNode.connect(audioCtx.destination); oscillator.channelCount; Specifications Specification Status Comment Web Audio APIThe definition of 'channelCount' in that specification. Working Draft ...
AudioNode.channelCountMode - Web APIs
nnels of all connections, clamped to the value of channelCount. PannerNode, ConvolverNode, DynamicsCompressorNode explicit The number of channels is defined by the value of channelCount. AudioDestinationNode, AnalyserNode, ChannelSplitterNode In older versions of the spec, the default for a ChannelSplitterNode was max. ...
...tionNode, AnalyserNode, ChannelSplitterNode In older versions of the spec, the default for a ChannelSplitterNode was max. Syntax var oscillator = audioCtx.createOscillator
(); oscillator.channelCountMode = 'explicit'; Value A enumerated value representing a channelCountMode. Example var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext
(); var oscillator = audioCtx.createOscillator
(); var gainNode = audioCtx.createGain
(); oscillator.connect(gainNode); gainNode.connect(audioCtx.destination); oscillator.channelCountMode = 'explicit'; Specifications Specification Status Comment Web Audio APIThe definition of 'channelCountMode' in that specification. Working Draft ...
AudioNode.channelInterpretation - Web APIs
the input channel with the same index. Channels with no corresponding input channels are left silent. any (x) any (y) where x>y Down-mix discrete channels. Fill each output channel with its input counterpart, that is the input channel with the same index. Input channels with no corresponding output channels are dropped. ...
...that is the input channel with the same index. Input channels with no corresponding output channels are dropped. Syntax var oscillator = audioCtx.createOscillator
(); oscillator.channelInterpretation = 'discrete'; Value An enumerated value representing a channelInterpretation. Example var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext
(); var oscillator = audioCtx.createOscillator
(); var gainNode = audioCtx.createGain
(); oscillator.connect(gainNode); gainNode.connect(audioCtx.destination); oscillator.channelInterpretation = 'discrete'; Specifications Specification Status Comment Web Audio APIThe definition of 'channelInterpretation' in that specification. Working Draft ...
AudioTrack - Web APIs
roperty in order to mute and unmute the track. Properties enabled A Boolean value which controls whether or not the audio track's sound is enabled. Setting this value to false mutes the track's audio. id Read only A DOMString which uniquely identifies the track within the media. This ID can be used to locate a specific track within an audio track list by calling AudioTrackList.getTrackById
(). The ID can also be used as the fragment part of the URL if the media supports seeking by media fragment per the Media Fragments URI specification. kind Read only A DOMString specifying the category into which the track falls. For example, the main audio track would have a kind of "main". label Read only A DOMString providing a human-readable label for the track. For example, an audio comme...
...ia source. Usage notes To get an AudioTrack for a given media element, use the element's audioTracks property, which returns an AudioTrackList object from which you can get the individual tracks contained in the media: var el = document.querySelector("video"); var tracks = el.audioTracks; You can then access the media's individual tracks using either array syntax or functions such as forEach
(). This first example gets the first audio track on the media: var firstTrack = tracks[0]; The next example scans through all of the media's audio tracks, enabling any that are in the user's preferred language (taken from a variable userLanguage) and disabling any others. tracks.forEach(function(track) { if (track.language === userLanguage) { track.enabled = true; } else { track.ena...
AudioTrackList.onaddtrack - Web APIs
an event handler which is called when the addtrack event occurs, indicating that a new audio track has been added to the media element whose audio tracks the AudioTrackList represents. The event is passed into the event handler in the form of a TrackEvent object, whose track property identifies the newly-added track. Note: You can also add a handler for the addtrack event using addEventListener
(). Syntax AudioTrackList.onaddtrack = eventHandler; Value Set onaddtrack to a function that accepts as input a TrackEvent object which indicates in its track property which audio track has been added to the media. Usage notes The addtrack event is called whenever a new track is added to the media element whose audio tracks are represented by the AudioTrackList object. This happens when track...
...alled whenever a new track is added to the media element whose audio tracks are represented by the AudioTrackList object. This happens when tracks are added to the element when the media is first attached to the element; one addtrack event will occur for each audio track in the media resource. Example This snippet establishes a handler for the addtrack event that calls a function, addToTrackList
(), passing in the AudioTrack object representing the newly-added track. In this scenario, that function's role is to add the new track to a list of audio tracks available to choose from. document.querySelector("video").audioTracks.onaddtrack = function(event) { addToTrackList(event.track); }; Specifications Specification Status Comment HTML Living StandardThe defin...
AudioTrackList.onchange - Web APIs
g that one or more of the AudioTracks in the AudioTrackList have been enabled or disabled. The event is passed into the event handler in the form of an Event object; the event doesn't provide any additional information. To determine the new state of media's tracks, you'll have to look at their AudioTrack.enabled flags. Note: You can also add a handler for the change event using addEventListener
(). Syntax AudioTrackList.onchange = eventHandler; Value Set onchange to a function that should be called whenever tracks are enabled or disabled on the media element. Example This snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track. va...
...event that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track. var trackList = document.querySelector("video").audioTracks; trackList.onchange = function(event) { trackList.forEach(function(track) { updateTrackEnabledButton(track.id, track.enabled); }); }; The updateTrackEnabledButton
(), in this example, should be a function that finds a user interface control using the track's id (perhaps the app uses the track ID as the control element's ID) and the track's enabled flag to determine which state the control should be in now. Specifications Specification Status Comment HTML Living StandardThe definition of 'AudioTrackList.onchange' in that specifica...
AudioWorkletGlobalScope.registerProcessor - Web APIs
Working Draft ...
...ed when calling registerProcessor -- and connect it to an audio graph. const audioContext = new AudioContext
() await audioContext.audioWorklet.addModule('test-processor.js') const node = new AudioWorkletNode(audioContext, 'test-processor') node.connect(audioContext.destination) Specifications Specification Status Comment Web Audio APIThe definition of 'registerProcessor
()' in that specification. Working Draft ...
AudioWorkletNode.port - Web APIs
console.log(e.data) this.port.postMessage('pong') } } process (inputs, outputs, parameters) { return true } } registerProcessor('ping-pong-processor', PingPongProcessor) Now in our main scripts file we'll load the processor, create an instance of AudioWorkletNode passing the name of the processor, and connect the node to an audio graph. ...
...kletNode passing the name of the processor, and connect the node to an audio graph. const audioContext = new AudioContext
() await audioContext.audioWorklet.addModule('ping-pong-processor.js') const pingPongNode = new AudioWorkletNode(audioContext, 'ping-pong-processor') // send the message containing 'ping' string // to the AudioWorkletProcessor from the AudioWorkletNode every second setInterval(
() => pingPongNode.port.postMessage('ping'), 1000) pingPongNode.port.onmessage = (e) => console.log(e.data) pingPongNode.connect(audioContext.destination) This will output "ping" and "pong" strings to the console every second. Specifications Specification Status Comment Web Audio APIThe definition of 'port' in that specification. Working Draft ...
AudioWorkletProcessor.port - Web APIs
console.log(e.data) this.port.postMessage('pong') } } process (inputs, outputs, parameters) { return true } } registerProcessor('ping-pong-processor', PingPongProcessor) Now in our main scripts file we'll load the processor, create an instance of AudioWorkletNode passing the name of the processor, and connect the node to an audio graph. ...
...kletNode passing the name of the processor, and connect the node to an audio graph. const audioContext = new AudioContext
() await audioContext.audioWorklet.addModule('ping-pong-processor.js') const pingPongNode = new AudioWorkletNode(audioContext, 'ping-pong-processor') // send the message containing 'ping' string // to the AudioWorkletProcessor from the AudioWorkletNode every second setInterval(
() => pingPongNode.port.postMessage('ping'), 1000) pingPongNode.port.onmessage = (e) => console.log(e.data) pingPongNode.connect(audioContext.destination) This will output "ping" and "pong" strings to the console every second. Specifications Specification Status Comment Web Audio APIThe definition of 'port' in that specification. Working Draft ...
AuthenticatorAssertionResponse - Web APIs
This interface inherites from AuthenticatorResponse. Note: This interface is restricted to top-level contexts. Use from within an <iframe> element will not have any effect. Properties AuthenticatorAssertionResponse.clientDataJSON Secure contextRead only The client data for the authentication, such as origin and challenge. ...
... presence and user verification flags, and any extensions processed by the authenticator. AuthenticatorAssertionResponse.signature Secure contextRead only An assertion signature over AuthenticatorAssertionResponse.authenticatorData and AuthenticatorResponse.clientDataJSON. The assertion signature is created with the private key of keypair that was created during the navigator.credentials.create
() call and verified using the public key of that same keypair. AuthenticatorAssertionResponse.userHandle Secure contextRead only An ArrayBuffer containing an opaque user identifier. Methods None. Examples var options = { challenge: new Uint8Array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publicKey": options }) .then(function (credentialInfoAssertion) { v...
AuthenticatorAttestationResponse - Web APIs
This response should be sent to the relying party's server to complete the creation of the credential. This interface inherites from AuthenticatorResponse. Note: This interface is restricted to top-level contexts. Use from within an <iframe> element will not have any effect. ...
... contextRead only Client data for the authentication, such as origin and challenge. The clientDataJSON property is inherited from the AuthenticatorResponse. AuthenticatorAttestationResponse.attestationObject Secure contextRead only An ArrayBuffer containing authenticator data and an attestation statement for a newly-created key pair. Methods AuthenticatorAttestationResponse.getTransports
()Secure context Returns an Array of strings describing which transport methods (e.g. usb, nfc) are believed to be supported with the authenticator. The array may be empty if the information is not available. Examples var publicKey = { challenge: /* from the server */, rp: { name: "Example CORP", id : "login.example.com" }, user: { id: new Uint8Array(16), name: "jdoe@exa...
BatteryManager.ondischargingtimechange - Web APIs
vents occur when the battery dischargingTime is updated. Syntax battery.ondischargingtimechange = funcRef Where battery is a BatteryManager object, and funcRef is a function to be called when the dischargingtimechange event occurs. ...
... a BatteryManager object, and funcRef is a function to be called when the dischargingtimechange event occurs. ...
BatteryManager.onlevelchange - Web APIs
receive levelchange events. These events occur when the battery level is updated. Syntax navigator.battery.onlevelchange = funcRef Where battery is a BatteryManager object, and funcRef is a function to be called when the levelchange event occurs. ...
...y level is updated. Syntax navigator.battery.onlevelchange = funcRef Where battery is a BatteryManager object, and funcRef is a function to be called when the levelchange event occurs. ...
BatteryManager - Web APIs
Properties BatteryManager.charging Read only A Boolean value indicating whether or not the battery is currently being charged. BatteryManager.chargingTime Read only A number representing the remaining time in seconds until the battery is fully charged, or 0 if the battery is already fully charged. ...
...vent is sent when the battery charging time is updated BatteryManager.ondischargingtimechange A handler for the dischargingtimechange event; This event is sent when the battery discharging time is updated. BatteryManager.onlevelchange A handler for the levelchange event; This event is sent when the battery level is updated. Methods Inherited from EventTarget: EventTarget.addEventListener
() Registers an event handler of a specific event type on the EventTarget. EventTarget.removeEventListener
() Removes an event listener from the EventTarget. EventTarget.dispatchEvent
() Dispatches an event to this EventTarget. Additional methods in Mozilla chrome codebase Mozilla includes a couple of extensions for use by JS-implemented event targets to implement onevent properties. See also...
Beacon API - Web APIs
a no-op loop for several seconds within the unload handler to delay the unload and submit data to a server. Not only do these techniques represent poor coding patterns, some of them are unreliable and result in the perception of poor page load performance for the next navigation. The Beacon API provides a standard way to address these issues. Global context The Beacon API's Navigator.sendBeacon
() method is used to send a beacon of data to the server in the global browsing context. 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 returns "false" otherwise. Worker context T...
...data to the server in the global browsing context. 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 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". ...
BeforeInstallPromptEvent - Web APIs
Properties Inherits properties from its parent, Event. BeforeInstallPromptEvent.platforms Read only Returns an array of DOMString items containing the platforms on which the event was dispatched. This is provided for user agents that want to present a choice of versions to the user such as, for example, "web" or "play" which would allow the user to...
...patched. This is provided for user agents that want to present a choice of versions to the user such as, for example, "web" or "play" which would allow the user to chose between a web version or an Android version. BeforeInstallPromptEvent.userChoice Read only Returns a Promise that resolves to a DOMString containing either "accepted" or "dismissed". Methods BeforeInstallPromptEvent.prompt
() Allows a developer to show the install prompt at a time of their own choosing. This method returns a Promise. Example window.addEventListener("beforeinstallprompt", function(e) { // log the platforms provided as options in an install prompt console.log(e.platforms); // e.g., ["web", "android", "windows"] e.userChoice.then(function(choiceResult) { console.log(choiceResult.outcome);...
BluetoothCharacteristicProperties - Web APIs
sponse is permitted. writeWithoutResponseRead only Returns a boolean that is true if the writing to the characteristic without response is permitted. Examples The following example shows how tell if a GATT characteristic supports value change notifications. ...
... Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
BluetoothRemoteGATTDescriptor - Web APIs
The BluetoothRemoteGATTDescriptor interface of the Web Bluetooth API provides a GATT Descriptor, which provides further information about a characteristic's value. Interface interface BluetoothRemoteGATTDescriptor { readonly attribute BluetoothGATTCharacteristic characteristic; readonly attribute UUID uuid; readonly attribute ArrayBuffer? value; Promise<ArrayBuffer> readValue
(); Promise<void> writeValue(BufferSource value); }; Properties BluetoothRemoteGATTDescriptor.characteristicRead only Returns the BluetoothRemoteGATTCharacteristic this descriptor belongs to. BluetoothRemoteGATTDescriptor.uuidRead only Returns the UUID of the characteristic descriptor, for example '00002902-0000-1000-8000-00805f9b34fb' for theClient Characteristic Configuration descriptor.
...ATTDescriptor.uuidRead only Returns the UUID of the characteristic descriptor, for example '00002902-0000-1000-8000-00805f9b34fb' for theClient Characteristic Configuration descriptor. BluetoothRemoteGATTDescriptor.valueRead only Returns the currently cached descriptor value. This value gets updated when the value of the descriptor is read. Methods BluetoothRemoteGATTDescriptor.readValue
() Returns a Promise that resolves to an ArrayBuffer holding a duplicate of the value property if it is available and supported. Otherwise it throws an error. BluetoothRemoteGATTDescriptor.writeValue
() Sets the value property to the bytes contained in an ArrayBuffer and returns a Promise. Specifications Specification Status Comment Web BluetoothThe definition of 'Bluet...
BluetoothRemoteGATTServer - Web APIs
The BluetoothRemoteGATTServer interface of the Web Bluetooth API represents a GATT Server on a remote device. Interface interface BluetoothRemoteGATTServer { readonly attribute BluetoothDevice device; readonly attribute boolean connected; Promise<BluetoothRemoteGATTServer> connect
(); void disconnect
(); Promise<BluetoothRemoteGATTService> getPrimaryService(BluetoothServiceUUID service); Promise<sequence<BluetoothRemoteGATTService>> getPrimaryServices(optional BluetoothServiceUUID service); }; Properties BluetoothRemoteGATTServer.connectedRead only A boolean value that returns true while this script execution environment is connected to this.device. It can be false while the user agent is physically connected. BluetoothRemoteGATTServer.deviceRead only A refer...
...thServiceUUID service); }; Properties BluetoothRemoteGATTServer.connectedRead only A boolean value that returns true while this script execution environment is connected to this.device. It can be false while the user agent is physically connected. BluetoothRemoteGATTServer.deviceRead only A reference to the BluetoothDevice running the server. Methods BluetoothRemoteGATTServer.connect
() Causes the script execution environment to connect to this.device. BluetoothRemoteGATTServer.disconnect
() Causes the script execution environment to disconnect from this.device. BluetoothRemoteGATTServer.getPrimaryService
() Returns a promise to the primary BluetoothGATTService offered by the bluetooth device for a specified BluetoothServiceUUID. BluetoothRemoteGATTServer.getPrimaryServices(...
Body.bodyUsed - Web APIs
The bodyUsed read-only property of the Body mixin contains a Boolean that indicates whether the body has been read yet. Syntax var myBodyUsed = response.bodyUsed; Value A Boolean. Example In our fetch request example (run fetch request live), we create a new request using the Request
() constructor, then use it to fetch a JPG. When the fetch is successful, we read a Blob out of the response using blob
(), put it into an object URL using URL.createObjectURL, and then set that URL as the source of an <img> element to display the image. Notice that we log response.bodyUsed to the console once before the response.blob
() call and once after. This returns false before and true afterwards, as at that point the body has been read. HTML Content <img class="my-image" src="https://udn.realityri...
...before and true afterwards, as at that point the body has been read. HTML Content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> JS Content var myImage = document.querySelector('.my-image'); fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg').then(function(response) { console.log(response.bodyUsed); var res = response.blob
(); console.log(response.bodyUsed); return res; }).then(function(response) { var objectURL = URL.createObjectURL(response); myImage.src = objectURL; }); Specifications Specification Status Comment FetchThe definition of 'bodyUsed' in that specification. Living Standard ...
BroadcastChannel - Web APIs
Properties This interface also inherits properties from its parent, EventTarget. BroadcastChannel.name Read only Returns a DOMString, the name of the channel. Event handlers BroadcastChannel.onmessage An EventHandler property that specifies the function to execute when a message event is fired on this object. BroadcastChannel.onmess...
...essage An EventHandler property that specifies the function to execute when a message event is fired on this object. BroadcastChannel.onmessageerror An EventHandler called when a MessageEvent of type MessageError is fired--that is, when it receives a message that cannot be deserialized. Methods This interface also inherits methods from its parent, EventTarget. BroadcastChannel.postMessage
() Sends the message, of any type of object, to each BroadcastChannel object listening to the same channel. BroadcastChannel.close
() Closes the channel object, indicating it won't get any new messages, and allowing it to be, eventually, garbage collected. Events message Fired when when a message arrives on the channel. Also available via the onmessage property. messageerror Fired when a ...
Broadcast Channel API - Web APIs
ning a channel A client joins a broadcast channel by creating a BroadcastChannel object. Its constructor takes one single parameter: the name of the channel. If it is the first to connect to that broadcast channel name, the underlying channel is created. // Connection to a broadcast channel const bc = new BroadcastChannel('test_channel'); Sending a message It is enough to call the postMessage
() method on the created BroadcastChannel object, which takes any object as an argument. An example string message: // Example of sending of a very simple message bc.postMessage('This is a test message.'); Any kind of object can be sent, not just a DOMString. The API doesn't associate any semantics to messages, so it is up to the code to know what kind of messages to expect and what to do with t...
...and what to do with them. Receiving a message When a message is posted, a message event is dispatched to each BroadcastChannel object connected to this channel. A function can be run for this event with the onmessage event handler: // A handler that only logs the event to the console: bc.onmessage = function (ev) { console.log(ev); } Disconnecting a channel To leave a channel, call the close
() method on the object. This disconnects the object from the underlying channel, allowing garbage collection. // Disconnect the channel bc.close
(); Conclusion The Broadcast Channel API's self-contained interface allows cross-context communication. It can be used to detect user actions in other tabs within a same origin, like when the user logs in or out. The messaging protocol is not defined a...
CSS numeric factory functions - Web APIs
The CSS numeric factory functions, such as CSS.em
() and CSS.turn
() are methods that return CSSUnitValues with the value being the numeric argument and the unit being the name of the method used. These functions create new numeric values less verbosely than using the CSSUnitValue.CSSUnitValue
() constructor. Syntax CSS.number(number); CSS.percent(number); // <length> CSS.em(number); CSS.ex(number); CSS.ch(number); CSS.ic(number); CSS.rem(number); CSS.lh(number); CSS.rlh(number); CSS.vw(number); CSS.vh(number); CSS.vi(number); CSS.vb(number); CSS.vmin(number); CSS.vmax(number); CSS.cm(number); CSS.mm(number); CSS.Q(number); CSS.in(number); CSS.pt(number); CSS.pc(number); CSS.px(number); // <angle> CSS.deg(number); CSS.grad(number); CSS.rad(number); CSS.turn(number); // <time> CSS.s(number...
...er); CSS.mm(number); CSS.Q(number); CSS.in(number); CSS.pt(number); CSS.pc(number); CSS.px(number); // <angle> CSS.deg(number); CSS.grad(number); CSS.rad(number); CSS.turn(number); // <time> CSS.s(number); CSS.ms(number); // <frequency> CSS.Hz(number); CSS.kHz(number); // <resolution> CSS.dpi(number); CSS.dpcm(number); CSS.dppx(number); // <flex> CSS.fr(number); Examples We use the CSS.vmax
() numeric factory function to create a CSSUnitValue: let height = CSS.vmax(50); console.log( height ); // CSSUnitValue {value: 50, unit: "vmax"} console.log( height.value ) // 50 console.log( height.unit ) // vmax In this example, we set the margin on our element using the CSS.px
() factory function: myElement.attributeStyleMap.set('margin', CSS.px(40)); let currentMargin = myElement.at...
CSS - Web APIs
an be created: only static properties are defined on it. Static properties CSS.paintWorklet Secure context Provides access to the Worklet responsible for all the classes related to painting. Methods The CSS interface is a utility interface and no object of this type can be created: only static methods are defined on it. Static methods No inherited static methods. CSS.registerProperty
() Registers custom properties, allowing for property type checking, default values, and properties that do or do not inherit their value. CSS.supports
() Returns a Boolean indicating if the pair property-value, or the condition, given in parameter is supported. CSS.escape
() Can be used to escape a string mostly for use as part of a CSS selector. CSS factory functions Can be used to return a n...
...ion method used. CSS.em(3) // CSSUnitValue {value: 3, unit: "em"} Specifications Specification Status Comment CSS Painting API Level 1The definition of 'paintWorklet' in that specification. Working Draft Adds the paintWorklet static property. CSS Object Model (CSSOM)The definition of 'CSS' in that specification. Working Draft Adds the escape
() static method. CSS Conditional Rules Module Level 3The definition of 'CSS' in that specification. Candidate Recommendation Initial definition ...
CSSKeyframesRule - Web APIs
erties of these interfaces. It has two properties : CSSKeyframesRule.name Represents the name of the animation, used by the animation-name property. CSSKeyframesRule.cssRules Read only Returns a CSSRuleList of the CSS rules in the media rule. Methods As a CSSRule, CSSKeyframesRule also implements the methods of that interface. It has three specific methods: CSSKeyframesRule.appendRule
() Inserts a new keyframe rule into the current CSSKeyframesRule. The parameter is a DOMString containing a keyframe in the same format as an entry of a @keyframes at-rule. If it contains more than one keyframe rule, a DOMException with a SYNTAX_ERR is thrown. CSSKeyframesRule.deleteRule
() Deletes a keyframe rule from the current CSSKeyframesRule. The parameter is the index of the keyframe to be ...
...The key is a DOMString containing an index of the keyframe to be returned, resolving to a percentage between 0% and 100%. ...
CompositionEvent - Web APIs
Properties This interface also inherits properties of its parent, UIEvent, and its ancestor -- Event. CompositionEvent.data Read only Returns the characters generated by the input method that raised the event; its varies depending on the type of event that generated the CompositionEvent object. CompositionEvent.locale Read only Returns...
... event; its varies depending on the type of event that generated the CompositionEvent object. CompositionEvent.locale Read only Returns the locale of current input method (for example, the keyboard layout locale if the composition is associated with IME). Methods This interface also inherits methods of its parent, UIEvent, and its ancestor -- Event. CompositionEvent.initCompositionEvent
() Initializes the attributes of a CompositionEvent object. Specifications Specification Status Comment UI EventsThe definition of 'CompositionEvent' in that specification. Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'CompositionEvent' in that specification. Obsolete ...
CountQueuingStrategy - Web APIs
The CountQueuingStrategy interface of the the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. Constructor CountQueuingStrategy
() Creates a new CountQueuingStrategy object instance. Properties None. Methods CountQueuingStrategy.size
() Returns 1. Examples const queueingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); const writableStream = new WritableStream({ // Implement the sink write(chunk) { ... }, close
() { ... }, abort(err) { console.log("Sink error:", err); } }, queueingStrategy); var size = queueingStrategy.size
(); Specifications Specification Status Comment StreamsThe definition of 'CountQueuingStrategy' in that specification. Living Stand...
...reams.enabled preference (needs to be set to true) and the javascript.options.streams preference (needs to be set to true). ...
CryptoKeyPair - Web APIs
It contains two properties, which are both CryptoKey objects: a privateKey property containing the private key and a publicKey property containing the public key. ...
...t. For signing and verification algorithms it is used to sign. CryptoKey.publicKey A CryptoKey object representing the public key. For encryption and decryption algorithms, this key is used to encrypt. For signing and verification algorithms it is used to verify signatures. Examples The examples for SubtleCrypto methods often use CryptoKeyPair objects. For example: SubtleCrypto.generateKey
() SubtleCrypto.deriveKey
() SubtleCrypto.importKey
() SubtleCrypto.exportKey
() SubtleCrypto.wrapKey
() SubtleCrypto.unwrapKey
() SubtleCrypto.encrypt
() SubtleCrypto.decrypt
() SubtleCrypto.sign
() SubtleCrypto.verify
() Specifications Specification Status Comment Web Cryptography APIThe definition of 'CryptoKeyPair' in that specification. Recommendation Initial de...
DOMHighResTimeStamp - Web APIs
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
(). ...
...ethods 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 Worker contexts. Example To determine how much time has elapsed since a particular point in your code, you can do something like this: let startTime = performance.now
(); /* ... do things for a while ... */ let elapsedTime = performance.now
() - startTime; Upon completion, the value of elapsedTime is the number of milliseconds that have elapsed since you recorded the starting time in line 1. Specifications Specification Status Comment High Resolution Time Level 2The definition of 'DOMHighResTimeStamp' in that specification. Rec...
DOMPointInit.w - Web APIs
wPerspective }; DOMPointInit.w = wPerspective; var wPerspective = DOMPointInit.w; Value A double-precision floating-point value indicating the point's w perspective value. This value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be NaN or +-Infinity). There are two methods which use DOMPointInit: The static function DOMPointReadOnly.fromPoint
() takes an object that complies with DOMPointInit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created. This method is, by inheritance, also available as DOMPoint.fromPoint
(). The DOMPointReadOnly.toJSON
() method returns a DOMPointInit object that describes the same point as the original point. By inheritance, this method is also available as...
... that complies with DOMPointInit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created. This method is, by inheritance, also available as DOMPoint.fromPoint
(). The DOMPointReadOnly.toJSON
() method returns a DOMPointInit object that describes the same point as the original point. By inheritance, this method is also available as DOMPoint.toJSON
(). This value is assumed to be 1 by default if not included in the DOMPointInit object passed into fromPoint
(). Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'w' in that specification. Candidate Recommendation Initial definition ...
DOMPointInit.y - Web APIs
o change. Syntax var DOMPointInit = { y: yPos }; DOMPointInit.y = yPos; var yPos = DOMPointInit.y; Value A double-precision floating-point value indicating the point's y-coordinate. This value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be NaN or +-Infinity). If this property is missing when the DOMPointInit object is passed into fromPoint
(), the value is assumed to be 0 by default. There are two methods which use DOMPointInit: The static function DOMPointReadOnly.fromPoint
() takes an object that complies with DOMPointInit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created. This method is, by inheritance, also available as DOMPoint.fromPoint
(). The DOMPointReadOnly.toJSON...
..., the value is assumed to be 0 by default. There are two methods which use DOMPointInit: The static function DOMPointReadOnly.fromPoint
() takes an object that complies with DOMPointInit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created. This method is, by inheritance, also available as DOMPoint.fromPoint
(). The DOMPointReadOnly.toJSON
() method returns a DOMPointInit object that describes the same point as the original point. By inheritance, this method is also available as DOMPoint.toJSON
(). Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'y' in that specification. Candidate Recommendation Initial definition ...
DOMPointInit.z - Web APIs
tax var DOMPointInit = { z: zPos }; DOMPointInit.z = zPos; var zPos = DOMPointInit.z; Value A double-precision floating-point value indicating the point's z-coordinate. This value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be NaN or +-Infinity). There are two methods which use DOMPointInit: The static function DOMPointReadOnly.fromPoint
() takes an object that complies with DOMPointInit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created. This method is, by inheritance, also available as DOMPoint.fromPoint
(). The DOMPointReadOnly.toJSON
() method returns a DOMPointInit object that describes the same point as the original point. By inheritance, this method is also available as...
... that complies with DOMPointInit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created. This method is, by inheritance, also available as DOMPoint.fromPoint
(). The DOMPointReadOnly.toJSON
() method returns a DOMPointInit object that describes the same point as the original point. By inheritance, this method is also available as DOMPoint.toJSON
(). If this property is missing when the DOMPointInit object is passed into fromPoint
(), the value is assumed to be 0 by default. Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'z' in that specification. Candidate Recommendation Initial definition ...
DOMPointReadOnly - Web APIs
instance. First, you can use its constructor, passing in the values of the parameters for each dimension and, optionally, the perspective: /* 2D */ const point = new DOMPointReadOnly(50, 50); /* 3D */ const point = new DOMPointReadOnly(50, 50, 25); /* 3D with perspective */ const point = new DOMPointReadOnly(100, 100, 100, 1.0); The other option is to use the static DOMPointReadOnly.fromPoint
() method: const point = DOMPointReadOnly.fromPoint({x: 100, y: 100, z: 50; w: 1.0}); Constructor DOMPointReadOnly
() Creates a new DOMPointReadOnly object given the values of its coordinates and perspective. To create a point using aDOMPointInit object, you can instead use DOMPointReadOnly.fromPoint
(). Properties DOMPointReadOnly.x Read only The point's horizontal coordinate, x. DOMPoi...
...OMPointInit object, you can instead use DOMPointReadOnly.fromPoint
(). Properties DOMPointReadOnly.x Read only The point's horizontal coordinate, x. DOMPointReadOnly.y Read only The point's vertical coordinate, y. DOMPointReadOnly.z Read only The point's depth coordinate, z. DOMPointReadOnly.w Read only The point's perspective value, w. Static methods DOMPointReadOnly.fromPoint
() A static method that creates a new DOMPointReadOnly object given the coordinates provided in the specified DOMPointInit object. Methods matrixTransform
() Applies a matrix transform specified as a DOMMatrixInit object to the DOMPointReadOnly object. toJSON
() Returns a JSON representation of the DOMPointReadOnly object. Specifications Specification Status Comment ...
DOMQuad - Web APIs
A DOMQuad is a collection of four DOMPoints defining the corners of an arbitrary quadrilateral. Returning DOMQuads lets getBoxQuads
() return accurate information even when arbitrary 2D or 3D transforms are present. It has a handy bounds attribute returning a DOMRectReadOnly for those cases where you just want an axis-aligned bounding rectangle. Constructor DOMQuad.DOMQuad
() Creates a new DOMQuad object. Properties p1,p2,p3,p4 Read only are DOMPoint objects for each of the DOMQuad object's four corners. Methods DOMQuad.fromRect
() Returns a new DOMQuad object based on the passed set of coordinates. ...
...tribute returning a DOMRectReadOnly for those cases where you just want an axis-aligned bounding rectangle. Constructor DOMQuad.DOMQuad
() Creates a new DOMQuad object. Properties p1,p2,p3,p4 Read only are DOMPoint objects for each of the DOMQuad object's four corners. Methods DOMQuad.fromRect
() Returns a new DOMQuad object based on the passed set of coordinates. DOMQuad.fromQuad
() Returns a new DOMQuad object based on the passed set of coordinates. DOMQuad.getBounds
() Returns a DOMRect object with the coordinates and dimensions of the DOMQuad object. DOMQuad.toJSON
() Returns a JSON representation of the DOMQuad object. Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'DOMQuad' in that specificat...
DOMRect - Web APIs
Properties DOMRect inherits properties from its parent, DOMRectReadOnly. The difference is that they are not read-only anymore. DOMRectReadOnly.x The x coordinate of the DOMRect's origin. DOMRectReadOnly.y The y coordinate of the DOMRect's origin. DOMRectReadOnly.width The width of the DOMRect. DOMRectReadOnly.height The height of the DOMRect. DOMRe...
... Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'DOMRect' in that specification. Candidate Recommendation Initial definition. ...
DOMRectReadOnly - Web APIs
Note that this constructor cannot be called by 3rd party JavaScript; doing so returns an "Illegal constructor" TypeError. Properties DOMRectReadOnly.x Read only The x coordinate of the DOMRect's origin. DOMRectReadOnly.y Read only The y coordinate of the DOMRect's origin. DOMRectReadOnly.width Read only The width of the DOMRect. DOMRectReadOnly.height Read only The height of the DOMRect. ...
...e as y.) DOMRectReadOnly.right Read only Returns the right coordinate value of the DOMRect (usually the same as x + width). DOMRectReadOnly.bottom Read only Returns the bottom coordinate value of the DOMRect (usually the same as y + height). DOMRectReadOnly.left Read only Returns the left coordinate value of the DOMRect (usually the same as x). Static methods DOMRectReadOnly.fromRect
() Creates a new DOMRect object with a given location and dimensions. Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'DOMRectReadOnly' in that specification. Candidate Recommendation Initial definition. ...
Binary strings - Web APIs
t characters, but binary data. The size of the data so represented is twice as big as it would be in normal binary format, however this will not be visible to the final user, since the length of JavaScript strings is calculated using two bytes as the unit. Binary strings are not part of the JavaScript language design. However at least one native function requires binary strings as its input, btoa
(): invoking it on a string that contains codepoints greater than 255 will cause a Character Out Of Range error. The reason that brought to use UTF-16 code units as placeholders for uint8 numbers is that as web applications become more and more powerful (adding features such as audio and video manipulation, access to raw data using WebSockets, and so forth) it has become clear that there are times ...
...web applications become more and more powerful (adding features such as audio and video manipulation, access to raw data using WebSockets, and so forth) it has become clear that there are times when it would be helpful for JavaScript code to be able to quickly and easily manipulate raw binary data. In the past, this had to be simulated by treating the raw data as a string and using the charCodeAt
() method to read the bytes from the data buffer (i.e., using binary strings). However, this is slow and error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32-bit integers or floats). JavaScript typed arrays provide a mechanism for accessing raw binary data much more efficiently. The StringView Non native construc...
DataTransfer.items - Web APIs
types[" + i + "] = " + ev.dataTransfer.types[i]); } } // Print each item'...
...i + "] = " + ev.dataTransfer.types[i]); } } // Print each item's "kind" and "type" if (ev.dataTransfer.items != null) { for (var i=0; i < ev.dataTransfer.items.length; i++) { console.log("... ...
DataTransfer.types - Web APIs
types[" + i + "] = " + ev.dataTransfer.types[i]); } } // Print each item'...
...i + "] = " + ev.dataTransfer.types[i]); } } // Print each item's "kind" and "type" if (ev.dataTransfer.items != null) { for (var i=0; i < ev.dataTransfer.items.length; i++) { console.log("... ...
DataTransferItem.kind - Web APIs
le. Syntax var itemKind = DataTransferItem.kind; Return value A DOMString representing the drag data item's kind. It must be one of the following values: 'file' If the drag data item is a file. 'string' If the kind of drag data item is a plain Unicode string. Example This example shows the use of the kind property. ...
...ion (s){ ev.target.appendChild(document.getElementById(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // Drag data item is HTML console.log("... Drop: HTML"); } else if ((data[i].kind == 'file') && (data[i].type.match('^image/'))) { // Drag data item is an image file var f = data[i].getAsFile
(); console.log("... Drop: File "); } } } Specifications Specification Status Comment HTML Living StandardThe definition of 'kind' in that specification. Living Standard Initial version HTML 5.1The definition of 'kind' in that specification. Recommendation W3C snapshot of the WHATWG document. ...
Using the W3C DOM Level 1 Core - Web APIs
pt to access the document property of the global object. This document object implements the Document interface from the W3C's DOM Level 1 spec. A simple example Suppose the author wants to change the header of the above document and write two paragraphs instead of one. ...
...nts the Document interface from the W3C's DOM Level 1 spec. A simple example Suppose the author wants to change the header of the above document and write two paragraphs instead of one. The following script would do the job: HTML Content <body> <input type="button" value="Change this document." onclick="change
()"> <h2>Header</h2> <p>Paragraph</p> </body> JavaScript Content function change
() { // document.getElementsByTagName("H2") returns a NodeList of the <h2> // elements in the document, and the first is number 0: var header = document.getElementsByTagName("H2").item(0); // the firstChild of the header is a Text node: header.firstChild.data = "A dynamic document"; // now the header is "A dynamic document". var para = document.getElementsByTagName("P")...
EXT_color_buffer_half_float - Web APIs
For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is available to WebGL 1 contexts only. For WebGL 2, use the EXT_color_buffer_float extension. The OES_texture_half_float extension implicitly enables this extension. Constants ext.RGBA16F_EXT RGBA 16-bit floating-point color-renderable format. ...
...tension. The OES_texture_half_float extension implicitly enables this extension. Constants ext.RGBA16F_EXT RGBA 16-bit floating-point color-renderable format. ext.RGB16F_EXT RGB 16-bit floating-point color-renderable format. ext.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT ? ext.UNSIGNED_NORMALIZED_EXT ? Extended methods This extension extends WebGLRenderingContext.renderbufferStorage
(): The internalformat parameter now accepts ext.RGBA16F_EXT and ext.RGBA16F_EXT. Examples var ext = gl.getExtension('EXT_color_buffer_half_float'); gl.renderbufferStorage(gl.RENDERBUFFER, ext.RBGA16F_EXT, 256, 256); Specifications Specification Status Comment EXT_color_buffer_half_floatThe definition of 'EXT_color_buffer_half_float' in that specification. Recomm...
EXT_frag_depth - Web APIs
The EXT_frag_depth extension is part of the WebGL API and enables to set a depth value of a fragment from within the fragment shader. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default. It requires GLSL #version 300 es. ...
...nly available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default. It requires GLSL #version 300 es. Examples Enable the extension: gl.getExtension('EXT_frag_depth'); Now the output variable gl_FragDepthEXT is available to set a depth value of a fragment from within the fragment shader: <script type="x-shader/x-fragment"> void main
() { gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0); gl_FragDepthEXT = 0.5; } </script> Specifications Specification Status Comment EXT_frag_depthThe definition of 'EXT_frag_depth' in that specification. Recommendation Initial definition. ...
EXT_sRGB - Web APIs
The EXT_sRGB extension is part of the WebGL API and adds sRGB support to textures and framebuffer objects. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default. The constants in WebGL2 are: gl.SRGB, gl.SRGB8, gl.SRGB8_ALPHA8 and gl.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING. Constants This extension exposes the following constants, which can be used in the texImage2D
(), texSubImage2D
(), renderbufferStorage
() and getFramebufferAttachmentParameter
() methods. ext.SRGB_EXT Unsized sRGB format that leaves the precision up to the dr...
..._EXT Unsized sRGB format that leaves the precision up to the driver. ext.SRGB_ALPHA_EXT Unsized sRGB format with unsized alpha component. ext.SRGB8_ALPHA8_EXT Sized (8-bit) sRGB and alpha formats. ext.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT Returns the framebuffer color encoding (gl.LINEAR or ext.SRGB_EXT). Examples var ext = gl.getExtension('EXT_sRGB'); var texture = gl.createTexture
(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, ext.SRGB_EXT, 512, 512, 0, ext.SRGB_EXT, gl.UNSIGNED_BYTE, image); Specifications Specification Status Comment EXT_sRGBThe definition of 'EXT_sRGB' in that specification. Recommendation Initial definition. ...
EXT_shader_texture_lod - Web APIs
For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is only available to WebGL1 contexts. ...
... Recommendation Initial definition. ...
EXT_texture_compression_bptc - Web APIs
The EXT_texture_compression_bptc extension is part of the WebGL API and exposes 4 BPTC compressed texture formats. These compression formats are called BC7 and BC6H in Microsoft's DirectX API. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: Support depends on the system's graphics driver. There is no support on Windows. This extension is available to both, WebGL1 and WebGL2 contexts. Constants The compressed texture formats are exposed by 4 constants and can be used in two functions: compressedTexImage2D
() and compressedTexSubImage2D
(). ext.COMPRESSED_RGBA_BPTC_UNORM_EXT Compresses 8-bit fixed-point data. Each 4x4 block of texels consists of 128 bits of RGBA...
...rned alpha value is 1.0. See also BC6H format. ext.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT Compresses high dynamic range unsigned floating point values. Each 4x4 block of texels consists of 128 bits of RGB data. ...
EXT_texture_compression_rgtc - Web APIs
The EXT_texture_compression_rgtc extension is part of the WebGL API and exposes 4 RGTC compressed texture formats. RGTC is a block-based texture compression format suited for unsigned and signed red and red-green textures (Red-Green Texture Compression). WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: Support depends on the system's graphics driver. There is no support on Windows. This extension is available to both, WebGL1 and WebGL2 contexts. Constants The compressed texture formats are exposed by 4 constants and can be used in two functions: compressedTexImage2D
() and compressedTexSubImage2D
(). ext.COMPRESSED_RED_RGTC1_EXT Each 4x4 block of texels consists...
...age data followed by 64 bits of compressed unsigned green image data. See also BC5 unsigned. ...
EcdhKeyDeriveParams - Web APIs
The EcdhKeyDeriveParams dictionary of the Web Crypto API represents the object that should be passed as the algorithm parameter into SubtleCrypto.deriveKey
(), when using the ECDH algorithm. ECDH enables two people who each have a key pair consisting of a public and a private key to derive a shared secret. They exchange public keys and use the combination of their private key and the other entity's public key to derive a secret key that they -- and noone else -- share. The parameters for ECDH deriveKey
() therefore include the other entity's public key, which is combined with this entity's private key to derive the shared secret. Properties name A DOMString. This should be set to ECDH. public A CryptoKey object representing the public key of the other entity. Examples See the exa...
...key that they -- and noone else -- share. The parameters for ECDH deriveKey
() therefore include the other entity's public key, which is combined with this entity's private key to derive the shared secret. Properties name A DOMString. This should be set to ECDH. public A CryptoKey object representing the public key of the other entity. Examples See the examples for SubtleCrypto.deriveKey
(). Specifications Specification Status Comment Web Cryptography APIThe definition of 'SubtleCrypto.EcdhKeyDeriveParams' in that specification. Recommendation ...
Element: contextmenu event - Web APIs
enu. This event is typically triggered by clicking the right mouse button, or by pressing the context menu key. In the latter case, the context menu is displayed at the bottom left of the focused element, unless the element is a tree, in which case the context menu is displayed at the bottom left of the current row. Any right-click event that is not disabled (by calling the event's preventDefault
() method) will result in a contextmenu event being fired at the targeted element. Bubbles Yes Cancelable Yes Interface MouseEvent Event handler property oncontextmenu Examples In this example, the default action of the contextmenu event is canceled using preventDefault
() when the contextmenu event is fired at the first paragraph. As a result,...
...raph will do nothing when right-clicked, while the second paragraph will show the standard context menu offered by your browser. HTML <p id="noContextMenu">The context menu has been disabled on this paragraph.</p> <p>But it has not been disabled on this one.</p> JavaScript noContext = document.getElementById('noContextMenu'); noContext.addEventListener('contextmenu', e => { e.preventDefault
(); }); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'contextmenu' in that specification. Living Standard ...
Element: copy event - Web APIs
Cancelable Yes Interface ClipboardEvent Event handler property oncopy The event's default action is to copy the selection (if any) to the clipboard. A handler for this event can modify the clipboard contents by calling setData(format, data) on the event's ClipboardEvent.clipboardData property, and cancelling the event's default action using event.preventDefault
(). However, the handler cannot read the clipboard data. It's possible to construct and dispatch a synthetic copy event, but this will not affect the system clipboard. Examples Live example HTML <div class="source" contenteditable="true">Try copying text from this box...</div> <div class="target" contenteditable="true">...and pasting it into this one</div> CSS div.source, div.target { ...
...m this box...</div> <div class="target" contenteditable="true">...and pasting it into this one</div> CSS div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } JS const source = document.querySelector('div.source'); source.addEventListener('copy', (event) => { const selection = document.getSelection
(); event.clipboardData.setData('text/plain', selection.toString
().toUpperCase
()); event.preventDefault
(); }); Result Specifications Specification Status Clipboard API and events Working Draft ...
Element: cut event - Web APIs
ClipboardEvent Event handler property oncut The event's default action is to copy the current selection (if any) to the system clipboard and remove it from the document. A handler for this event can modify the clipboard contents by calling setData(format, data) on the event's ClipboardEvent.clipboardData property, and cancelling the default action using event.preventDefault
(). Note though that cancelling the default action will also prevent the document from being updated. So an event handler which wants to emulate the default action for "cut" while modifying the clipboard must also manually remove the selection from the document. The handler cannot read the clipboard data. It's possible to construct and dispatch a synthetic cut event, but this will not affect the ...
...om this box...</div> <div class="target" contenteditable="true">...and pasting it into this one</div> CSS div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } JS const source = document.querySelector('div.source'); source.addEventListener('cut', (event) => { const selection = document.getSelection
(); event.clipboardData.setData('text/plain', selection.toString
().toUpperCase
()); selection.deleteFromDocument
(); event.preventDefault
(); }); Result Specifications Specification Status Clipboard API and events Working Draft ...
Element.innerHTML - Web APIs
Note: If a <div>, <span>, or <noembed> node has a child text node that includes the characters (&), (<), or (>), innerHTML returns these characters as the HTML entities "&", "<" and ">" respectively. Use Node.textContent to get a raw copy of these text nodes' contents. To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML
(). Syntax const content = element.innerHTML; element.innerHTML = htmlString; Value A DOMString containing the HTML serialization of the element's descendants. Setting the value of innerHTML removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString. Exceptions SyntaxError An attempt was made to set the value of inn...
... result in your code being rejected. For example, if you use innerHTML in a browser extension and submit the extension to addons.mozilla.org, it will not pass the automated review process. Example This example uses innerHTML to create a mechanism for logging messages into a box on a web page. JavaScript function log(msg) { var logElem = document.querySelector(".log"); var time = new Date
(); var timeStr = time.toLocaleTimeString
(); logElem.innerHTML += timeStr + ": " + msg + "<br/>"; } log("Logging mouse events inside this container..."); The log
() function creates the log output by getting the current time from a Date object using toLocaleTimeString
(), and building a string with the timestamp and the message text. Then the message is appended to the box with the class "log".
Element.localName - Web APIs
the Node interface. Syntax name = element.localName Return value A DOMString representing the local part of the element's qualified name. ...
...Qualified names are typically used in XML as part of the namespac...
Element.name - Web APIs
lement in the DOM. It only applies to the following elements: <a>, <applet>, <button>, <form>, <frame>, <iframe>, <img>, <input>, <map>, <meta>, <object>, <param>, <select>, and <textarea>. Note: The name property doesn't exist for other elements; unlike tagName and nodeName, it is not a property of the Node, Element or HTMLElement interfaces. name can be used in the document.getElementsByName
() method, a form and with the form elements collection. When used with a form or elements collection, it may return a single element or a collection. Syntax HTMLElement.name = string let elName = HTMLElement.name let fControl = HTMLFormElement.elementName let controlCollection = HTMLFormElement.elements.elementName Example <form action="" name="formA"> <input type="text" value="foo"> </form...
... ...
Element: paste event - Web APIs
Interface ClipboardEvent Event handler property onpaste If the cursor is in an editable context (for example, in a <textarea> or an element with contenteditable attribute set to true) then the default action is to insert the contents of the clipboard into the document at the cursor position. A handler for this event can access the clipboard contents by calling getData
() on the event's clipboardData property. To override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventDefault
(), and then insert its desired data manually. It's possible to construct and dispatch a synthetic paste event, but this will not affect the document's contents.
...and pasting it into this one</div> CSS div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } JS const target = document.querySelector('div.target'); target.addEventListener('paste', (event) => { let paste = (event.clipboardData || window.clipboardData).getData('text'); paste = paste.toUpperCase
(); const selection = window.getSelection
(); if (!selection.rangeCount) return false; selection.deleteFromDocument
(); selection.getRangeAt(0).insertNode(document.createTextNode(paste)); event.preventDefault
(); }); Result Specifications Specification Status Clipboard API and events Working Draft ...
Element.scrollHeight - Web APIs
s the element's padding, but not its border, margin or horizontal scrollbar (if present). It can also include the height of pseudo-elements such as ::before or ::after. If the element's content can fit without a need for vertical scrollbar, its scrollHeight is equal to clientHeight This property will round the value to an integer. If you need a fractional value, use Element.getBoundingClientRect
(). Syntax elemScrollHeight = element.scrollHeight; Value An integer corresponding to the scrollHeight pixel value of the element. Example padding-top Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis au...
...label for="agree">I agree</label> <input type="submit" id="nextstep" value="Next" /> </p> </form> CSS #notice { display: inline-block; margin-bottom: 12px; border-radius: 5px; width: 600px; padding: 5px; border: 2px #7FDF55 solid; } #rules { width: 600px; height: 130px; padding: 5px; border: #2A9F00 solid 2px; border-radius: 5px; } JavaScript function checkReading
() { if (checkReading.read) { return; } checkReading.read = this.scrollHeight - this.scrollTop === this.clientHeight; document.registration.accept.disabled = document.getElementById("nextstep").disabled = !checkReading.read; checkReading.noticeBox.innerHTML = checkReading.read ? "Thank you." : "Please, scroll and read the following text."; } onload = function
() { var oToBeRead = do...
Element: scroll event - Web APIs
place; they are only fired after the scrolling has completed. See Bootstrap issue #16202. Safari and WKWebViews are not affected by this bug. Examples Scroll event throttling Since scroll events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as DOM modifications. Instead, it is recommended to throttle the event using requestAnimationFrame
(), setTimeout
(), or a CustomEvent, as follows. Note, however, that input events and animation frames are fired at about the same rate, and therefore the optimization below is often unnecessary. This example optimizes thescroll event for requestAnimationFrame. // Reference: http://www.html5rocks.com/en/tutorials/speed/animations/ let last_known_scroll_position = 0; let ticking = false; function ...
...event for requestAnimationFrame. // Reference: http://www.html5rocks.com/en/tutorials/speed/animations/ let last_known_scroll_position = 0; let ticking = false; function doSomething(scroll_pos) { // Do something with the scroll position } window.addEventListener('scroll', function(e) { last_known_scroll_position = window.scrollY; if (!ticking) { window.requestAnimationFrame(function
() { doSomething(last_known_scroll_position); ticking = false; }); ticking = true; } }); Note: You can find more examples on the resize event page. Specifications Specification Status CSS Object Model (CSSOM) View Module Working Draft ...
Element.shadowRoot - Web APIs
The Element.shadowRoot read-only property represents the shadow root hosted by the element. Use Element.attachShadow
() to add a shadow root to an existing element. Syntax var shadowroot = element.shadowRoot; Value A ShadowRoot object instance, or null if the associated shadow root was attached with its mode set to closed. (See Element.attachShadow
() for further details). Examples The following snippets are taken from our life-cycle-callbacks example (see it live also), which creates an element that displays a square of a size and color specified in the element's attributes. Inside the <custom-square> element's class definition we include some life cycle callbacks that make a call to an external function, updateStyle
(), which actually applies the size and color to the element. You'll...
...n element that displays a square of a size and color specified in the element's attributes. Inside the <custom-square> element's class definition we include some life cycle callbacks that make a call to an external function, updateStyle
(), which actually applies the size and color to the element. You'll see that we are passing it this (the custom element itself) as a parameter. connectedCallback
() { console.log('Custom square element added to page.'); updateStyle(this); } attributeChangedCallback(name, oldValue, newValue) { console.log('Custom square element attributes changed.'); updateStyle(this); } In the updateStyle
() function itself, we get a reference to the shadow DOM using Element.shadowRoot. From here we use standard DOM traversal techniques to find the <style> element i...
Element: wheel event - Web APIs
g an element via the wheel This example shows how to scale an element using the mouse (or other pointing device) wheel. ...
... Working Draft ...
ElementCSSInlineStyle.style - Web APIs
The style property is not useful for completely learning about the styles applied on the element, since it represents only the CSS declarations set in the element's inline style attribute, not those that come from style rules elsewhere, such as style rules in the <head> section, or external style sheets. ...
...yle attribute, not those that come from style rules elsewhere, such as style rules in the <head> section, or external style sheets. To get the values of all CSS properties for an element you should use Window.getComputedStyle
() instead. ...
ExtendableMessageEvent - Web APIs
The ExtendableMessageEvent interface of the Service Worker API represents the event object of a message event fired on a service worker (when a message is received on the ServiceWorkerGlobalScope from another context) -- extends the lifetime of such events. 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. ExtendableMessageEvent.origin Read only Returns the origin of the Client that sent the message. ExtendableMessageEvent.lastEventId Read only Represents, in server-sent events, the last event ID of the event source. T...
...lient object that sent the message. ExtendableMessageEvent.ports Read only Returns the array containing the MessagePort objects representing the ports of the associated message channel. Methods Inherits methods from its parent, ExtendableEvent. Examples In the below example a page gets a handle to the ServiceWorker object via ServiceWorkerRegistration.active, and then calls its postMessage
() function. // in the page being controlled if (navigator.serviceWorker) { navigator.serviceWorker.register('service-worker.js'); navigator.serviceWorker.addEventListener('message', event => { // event is a MessageEvent object console.log(`The service worker sent me a message: ${event.data}`); }); navigator.serviceWorker.ready.then( registration => { registration.active.post...
FetchEvent.navigationPreload - Web APIs
stance of NavigationPreloadManager associated with the current service worker registration. Syntax var promise = fetchEvent.navigationPreload Value A Promise that resolves to the instance of NavigationPreloadManager. Example The following example shows the implementation of a fetch event that uses a preloaded response. ...
... Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
Fetch basic concepts - Web APIs
ervice Workers is an example of an API that makes heavy use of Fetch. Fetch takes the asynchronous nature of such requests one step further. The API is completely Promise-based. Guard Guard is a feature of Headers objects, with possible values of immutable, request, request-no-cors, response, or none, depending on where the header is used. ...
...epending on where the header is used. When a new Headers object is created using the Headers
() constructor, its guard is set to none (the default). When a Request or Response object is created, it has an associated Headers object whose guard is set as summarized below: new object's type creating constructor guard setting of associated Headers object Request Request
() request Request
() with mode of no-cors request-no-cors Response Response
() response error
() or redirect
() methods immutable A header's guard affects the set
(), delete
(), and append
() methods which change the header's contents. A TypeError is thrown if you try to modify a Headers object whose guard is immutable. However, the operation will work if ...
Cross-global fetch usage - Web APIs
d from an <iframe>, the relative URL used to be resolved against the current global location, rather than the iframe's location. The edge case Many sites will never comes up against this edge case. To see it: You need a same-origin iframe That same-origin iframe needs to have a location with a different base URL You have to use the fetch function cross-global, e.g. frame.contentWindow.fetch
() The URL passed to fetch needs to be relative The problem In the past we would resolve the relative URL against the current global, for example: let absolute = new URL(relative, window.location.href) This is not a problem as such. It is just that different APIs that exhibit this kind of behavior were doing it inconsistently with the behavior defined in the spec, which could lead to problems ...
...l, for example: let absolute = new URL(relative, window.location.href) This is not a problem as such. It is just that different APIs that exhibit this kind of behavior were doing it inconsistently with the behavior defined in the spec, which could lead to problems further down the line. The solution In Firefox 60 onwards, Mozilla resolves the relative URL against the global that owns the fetch
() function being used (see bug 1432272). So in the case described above, it is resolved against the iframe's location: let absolute = new URL(relative, frame.contentWindow.location.href) There is a lot of discussion in progress about getting new specs to align with this behavior change, to mitigate potential problems going forward. ...
File.lastModified - Web APIs
const fileWithDate = new File([], 'file.bin', { lastModified: new Date(2017, 1, 1), }); console.log(fileWithDate.lastModified); //returns 1485903600000 const fileWithoutDate = new File([], 'file.bin'); console.log(fileWithoutDate.lastModified); //returns c...
...iles; for (let file of files) { const date = new Date(file.lastModified); console.log(`${file.name} has a last modified date of ${date}`); } }); Try the results out below: Dynamically created files If a File is created dynamically, the last modified time can be supplied in the new File
() constructor function. If it is missing, lastModified inherits the current time from Date.now
() at the moment the File object gets created. const fileWithDate = new File([], 'file.bin', { lastModified: new Date(2017, 1, 1), }); console.log(fileWithDate.lastModified); //returns 1485903600000 const fileWithoutDate = new File([], 'file.bin'); console.log(fileWithoutDate.lastModified); //returns current time Reduced time precision To offer protection against timing attacks and fingerprin...
File.lastModifiedDate - Web APIs
// reduced time precision with `privacy.resistFingerprinting` enable...
... time precision To offer protection against timing attacks and fingerprinting, the precision of someFile.lastModifiedDate.getTime
() might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecision preference is enabled by default and defaults to 20us in Firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in Firefox 60 someFile.lastModifiedDate.getTime
(); // 1519211809934 // 1519211810362 // 1519211811670 // ... // reduced time precision with `privacy.resistFingerprinting` enabled someFile.lastModifiedDate.getTime
(); // 1519129853500 // 1519129858900 // 1519129864400 // ... In Firefox, you can also enable privacy.resistFingerprinting, the precision will be 100ms or the value of privacy.resistFingerprinting.reduceTimerPrecision.microseconds, w...
FileEntrySync - Web APIs
u write content to a file. Inherits from: EntrySync About this document This document was last updated on March 2, 2012 and follows the W3C Specifications (Working Draft) drafted on April 19, 2011. This specification is more or less abandoned as it didn't get significant traction among browser makers. Basic concepts To write content to file, create a FileWriter object by calling createWriter
(). Method overview FileWriterSync createWriter
() raises (FileException); File file
() raises (FileException); Methods createWriter
() Creates a new FileWriter associated with the file that the FileEntry represents. void createWriter ( ) raises (FileException); Parameter None. Returns FileWriterSync Exceptions This method can raise a FileException with the foll...
...leEntry represents. void createWriter ( ) raises (FileException); Parameter None. Returns FileWriterSync Exceptions This method can raise a FileException with the following codes: Exception Description NOT_FOUND_ERR The file does not exist. INVALID_STATE_ERR The file is no longer valid for some reason other than it having been deleted. file
() Returns a File that represents the current state of the file that this FileEntry represents. void file ( ) raises (FileException); Parameter None. Returns File Exceptions This method can raise a FileException with the following codes: Exception Description NOT_FOUND_ERR The file does not exist. INVALID_STATE_ERR The file is no longer valid for some ...
FileList - Web APIs
t id="fileItem" type="file"> The following line of code fetches the first file in the node's file list as a File object: var file = document.getElementById('fileItem').files[0]; Method overview File item(index); Properties Attribute Type Description length integer A read-only value indicating the number of files in the list. Methods item
() Returns a File object representing the file at the specified index in the file list. File item( index ); Parameters index The zero-based index of the file to retrieve from the list. Return value The File representing the requested file. Example This example iterates over all the files selected by the user using an input element: // fileInput is an HTML input element: <input typ...
...les; var file; // loop through files for (var i = 0; i < files.length; i++) { // get item file = files.item(i); //or file = files[i]; alert(file.name); } Here is a complete example. ...
FileReader.readyState - Web APIs
has been called. 2 DONE The operation is complete. EMPTY The FileReader has been created, but no readAs method was called yet. LOADING A readAs method was invoked. A File or Blob is being read, and no error has occurred yet. DONE The read operation is complete. ...
... The FileReader has been created, but no readAs method was called yet. LOADING A readAs method was invoked. A File or Blob is being read, and no error has occurred yet. DONE The read operation is complete. This could mean that: the entire File or Blob has been read into memory, a file read error occurred, or abort
() was called and the read was cancelled. Example var reader = new FileReader
(); console.log('EMPTY', reader.readyState); // readyState will be 0 reader.readAsText(blob); console.log('LOADING', reader.readyState); // readyState will be 1 reader.onloadend = function
() { console.log('DONE', reader.readyState); // readyState will be 2 }; Value A number which is one of the three possible state constants define for the FileReader API. Specifications Specificati...
FileReaderSync - Web APIs
The FileReaderSync interface allows to read File or Blob objects synchronously. This interface is only available in workers as it enables synchronous I/O that could potentially block. Properties This interface does not have any properties. Methods FileReaderSync.readAsArrayBuffer
() This method converts a specified Blob or a File into an ArrayBuffer representing the input data as a binary string. FileReaderSync.readAsBinaryString
() This method converts a specified Blob or a File into a DOMString representing the input data as a binary string. This method is deprecated, consider using readAsArrayBuffer
() instead. FileReaderSync.readAsText
() This method converts a specified Blob or a File into a DOMString representing the input data as a text string. The optional encoding paramet...
... Specifications Specification Status Comment File APIThe definition of 'FileReaderSync' in that specification. Working Draft Initial definition. ...
FileSystemFlags.create - Web APIs
The create property on the FileSystemFlags dictionary is used to indicate whether or not the file should be created if it's missing. FileSystemFlags is only used when calling FileSystemDirectoryEntry.getFile
() or FileSystemDirectoryEntry.getDirectory
(). Syntax fileSystemFlags.create = booleanValue Values The table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. ...
...= booleanValue Values The table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. Option values File/directory condition Result create exclusive false n/a[1] Path exists and matches the desired type (depending on whether the function called is getFile
() or getDirectory
() The successCallback is called with a FileSystemFileEntry if getFile
() was called or a FileSystemDirectoryEntry if getDirectory
() was called. false n/a[1] Path exists but doesn't match the desired type The errorCallback is called with an appropriate error code (if the callback was provided). true false Path exists The existing file or direct...
FileSystemFlags.exclusive - Web APIs
The exclusive property on the FileSystemFlags dictionary is used in tandem with the create property to determine whether or not it's acceptable to require that the file not already exist when the reference to it is created by calling FileSystemDirectoryEntry.getFile
() or FileSystemDirectoryEntry.getDirectory
(). ...
...= booleanValue Values The table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. Option values File/directory condition Result create exclusive false n/a[1] Path exists and matches the desired type (depending on whether the function called is getFile
() or getDirectory
() The successCallback is called with a FileSystemFileEntry if getFile
() was called or a FileSystemDirectoryEntry if getDirectory
() was called. false n/a[1] Path exists but doesn't match the desired type The errorCallback is called with an appropriate error code (if the callback was provided). true false Path exists The existing file or direct...
File and Directory Entries API support in Firefox - Web APIs
ows: Content scripts can't create file systems or initiate access to a file system. There are only two ways to get access to file system entries at this time: The <input> element, using the HTMLInputElement.webkitEntries property to access an array of FileSystemEntry objects describing file system entries you can then read. Using drag and drop by calling the DataTransferItem.getAsEntry
() method, which lets you get a FileSystemFileEntry or FileSystemDirectoryEntry for files dropped on a drop zone. You can't use the LocalFileSystem.requestFileSystem
() method to get access to a specified local file system. The LocalFileSystem.resolveLocalFileSystemURL
() method isn't implemented. Only the asynchronous versions of the interfaces are implemented. Any interfaces with names that ...
...) method to get access to a specified local file system. The LocalFileSystem.resolveLocalFileSystemURL
() method isn't implemented. Only the asynchronous versions of the interfaces are implemented. Any interfaces with names that end in "Sync" aren't available. Firefox only supports reading from files in the file system. You can't write to them. In particular, the FileSystemFileEntry.createWriter
() method, used to create a FileWriter to handle writing to a file, is not implemented and will just treturn an error. Firefox doesn't support the "filesystem:" URL scheme. ...
Introduction to the File and Directory Entries API - Web APIs
onous API doesn't give you data by returning values; instead, you have to pass a callback function. You send requests 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 d...
... want to know why your calls failed. At minimum, handle the errors to provide error messages, so you'll have an idea of what's going on. The File and Directory Entries API interacts with other APIs The File and Directory Entries API is designed to be used with other APIs and elements on the web platform. For example, you are likely to use one of the following: XMLHttpRequest (such as the send
() method for file and blob objects) Drag and Drop API Web Workers (for the synchronous version of the File and Directory Entries API) The input element (to programmatically obtain a list of files from the element) The File and Directory Entries API is case sensitive The filesystem API is case-sensitive, and case-preserving. Restrictions For security reasons, browsers impose restrictions on...
FontFace - Web APIs
Properties This interface doesn't inherit any property. ...
...depoints encompassing the font. It is equivalent to the unicode-range descriptor. FontFace.variant A CSSOMString that retrieves or sets the variant of the font. It is equivalent to the font-variant descriptor. FontFace.weight A CSSOMString that contains the weight of the font. It is equivalent to the font-weight descriptor. Methods This interface doesn't inherit any method. FontFace.load
() Loads a font based on current object's constructor-passed requirements, including a location or source buffer, and returns a Promise that resolves with the current FontFace object. Specifications Specification Status Comment CSS Font Loading Module Level 3The definition of 'FontFace' in that specification. Working Draft Initial definition ...
FontFaceSetLoadEvent - Web APIs
Properties FontFaceSetLoadEvent.fontfacesRead only Returns an array of FontFace instances each of which represents a single usable font. Specifications Specification Status Comment CSS Font Loading Module Level 3The definition of 'FontFaceSetLoadEvent' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
... NoChrome Android Full support 35Firefox Android Full support YesOpera Android Full support 22Safari iOS ? Samsung Internet Android Full support 3.0FontFaceSetLoadEvent
() constructor ExperimentalChrome Full support 57Edge Full support <=79Firefox ? IE ? Opera Full support 44Safari ? WebView Android No support ...
Frame Timing API - Web APIs
. When one of those event types is recorded in the browser's performance timeline, the application is notified of the event via the observer's callback function that was specified when the observer was created. To observe "frame" performance entry types, the application first creates a PerformanceObserver object with a specific frame observer callback (function). ...
...This method returns a list of "frame" PerformanceEntry objects. Each frame object's duration property returns the timestamp of two consecutive frames. ...
Gamepad.axes - Web APIs
Gamepad.axes property of the Gamepad interface returns an array representing the controls with axes present on the device (e.g. analog thumb sticks).- Each entry in the array is a floating point value in the range -1.0 - 1.0, representing the axis position from the lowest value (-1.0) to the highest value (1.0). ...
... controls with axes present on the device (e.g. analog thumb sticks).- Each entry in the array is a floating point value in the range -1.0 - 1.0, representing the axis position from the lowest value (-1.0) to the highest value (1.0). Syntax readonly attribute double[] axes; Example function gameLoop
() { if(navigator.webkitGetGamepads) { var gp = navigator.webkitGetGamepads
()[0]; } else { var gp = navigator.getGamepads
()[0]; } if(gp.axes[0] != 0) { b -= gp.axes[0]; } else if(gp.axes[1] != 0) { a += gp.axes[1]; } else if(gp.axes[2] != 0) { b += gp.axes[2]; } else if(gp.axes[3] != 0) { a -= gp.axes[3]; } ball.style.left = a*2 + "px"; ball.style.top = b*2 + "px"; var start = rAF(gameLoop); }; Value An array of double values. ...
GamepadEvent - Web APIs
Properties GamepadEvent.gamepad Read only Returns a Gamepad object, providing access to the associated gamepad data for the event fired. Examples The gamepad property being called on a fired Window.gamepadconnected event. ...
...d Full support 22 Full support 22 No support 14 -- 21Prefixed Prefixed Implemented with the vendor prefix: webkitSafari iOS Full support 10.3Samsung Internet Android Full support YesGamepadEvent
() constructorChrome Full support 35Edge Full support 12Firefox Full support 29 Full support 29 No support 24 -- 28Disabled Disabled From version 24 until version 28 (exclusive): this feature is b...
Geolocation - Web APIs
security reasons, when a web page tries to access location information, the user is notified and asked to grant permission. Be aware that each browser has its own policies and methods for requesting this permission. Properties The Geolocation interface neither implements, nor inherits any property. Methods The Geolocation interface doesn't inherit any method. ...
...owser has its own policies and methods for requesting this permission. Properties The Geolocation interface neither implements, nor inherits any property. Methods The Geolocation interface doesn't inherit any method. Geolocation.getCurrentPosition
() Secure context Determines the device's current location and gives back a GeolocationPosition object with the data. Geolocation.watchPosition
() Secure context Returns a long value representing the newly established callback function to be invoked whenever the device location changes. Geolocation.clearWatch
() Secure context Removes the particular handler previously installed using watchPosition
(). Specifications Specification Status Comment Geolocation API Recommendation Initial specification. ...
GeometryUtils - Web APIs
The GeometryUtils interface provides different utility function to retrieve geometry information about DOM nodes. GeometryUtils is a raw interface and no object of this type can be created; it is implemented by Text, Element, CSSPseudoElement, and Document objects. Properties This interface does not implement any properties. ...
... information about DOM nodes. GeometryUtils is a raw interface and no object of this type can be created; it is implemented by Text, Element, CSSPseudoElement, and Document objects. Properties This interface does not implement any properties. Methods GeometryUtils.getBoxQuads
() Returns a list of DOMQuad objects representing the CSS fragments of the node. GeometryUtils.convertQuadFromNode
() FIXME: Needs a description GeometryUtils.convertRectFromNode
() FIXME: Needs a description GeometryUtils.convertPointFromNode
() FIXME: Needs a description Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'GeometryUtils' in that specification. Working Draft Initial definition ...
GlobalEventHandlers.onanimationcancel - Web APIs
Event.elapsedTime to get information about the event which occurred. function log(msg, event) { let logBox = document.getElementById("log"); logBox.innerHTML += msg; if (event) { logBox.innerHTML += " <code>"+ event.animationName + "</code> at time " + event.elapsedTime.toFixed(2) + " seconds."; } logBox.innerHTML += "\n"; }; Then we set up the handleCancelEvent
() function, which is called in response to the animationcancel event, as set up in the HTML above. All we do here is log information to the console, but you might find other use cases, such as starting a new animation or effect, or terminating some dependent operation. function handleCancelEvent(event) { log("Animation canceled", event); }; Then we add a method to handle toggle display between...
... cases, such as starting a new animation or effect, or terminating some dependent operation. function handleCancelEvent(event) { log("Animation canceled", event); }; Then we add a method to handle toggle display between "flex" and "none" and establish it as the handler for a click event on the "Hide/Show" the Box button: document.getElementById('toggleBox').addEventListener('click', function
() { if (box.style.display == "none") { box.style.display = "flex"; document.getElementById("toggleBox").innerHTML = "Hide the box"; } else { box.style.display = "none"; document.getElementById("toggleBox").innerHTML = "Show the box"; } }); Toggling the box to display: none has the effect of aborting its animation. In browsers that support animationcancel, the event is fired ...
GlobalEventHandlers.onclick - Web APIs
e a mouse or a touch screen. Syntax target.onclick = functionRef; Value functionRef is a function name or a function expression. The function receives a MouseEvent object as its sole argument. Within the function, this will be the element upon which the event was triggered. Only one onclick handler can be assigned to an object at a time. ...
...as triggered. Only one onclick handler can be assigned to an object at a time. You may prefer to use the EventTarget.addEventListener
() method instead, since it's more flexible. Examples Detecting clicks This example simply changes the color of an element when it's clicked upon. HTML <div id="demo">Click here</div> JavaScript document.getElementById('demo').onclick = function changeContent
() { document.getElementById('demo').innerHTML = "Help me"; document.getElementById('demo').style = "Color: red"; } Result Getting the coordinates of clicks This example displays the coordinates at which the most recent mouse button click occurred. HTML <p>Click anywhere in this example.</p> <p id="log"></p> JavaScript let log = document.getElementById('log'); document.onclick = in...
GlobalEventHandlers.oncontextmenu - Web APIs
icked on the window. Unless the default behavior is prevented, the browser context menu will activate. Syntax target.oncontextmenu = functionRef; Value functionRef is a function name or a function expression. The function receives an Event object as its sole argument. Only one oncontextmenu handler can be assigned to an object at a time. ...
...to an object at a time. You may prefer to use the EventTarget.addEventListener
() method instead, since it's more flexible. Examples Disabling context menus This snippet prevents context menus from opening in the window. The context menu typically appears upon a right click. HTML <p>Try opening the context menu. Is it disabled?<p> JavaScript window.oncontextmenu = (e) => { e.preventDefault
(); } Result Pausing an animation This example pauses a spinning shape whenever you open the context menu. HTML <div class="shape">Spinning</div> <p class="note" hidden>Click to unpause.</p> CSS @keyframes spin { from { transform: rotate(0); } to { transform: rotate(1turn); } } .shape { width: 8em; height: 8em; display: flex; align-items: center; justify-content:...
GlobalEventHandlers.onerror - Web APIs
The onerror property of the GlobalEventHandlers mixin is an EventHandler that processes error events. Error events are fired at various targets for different kinds of errors: When a JavaScript runtime error (including syntax errors and exceptions thrown within handlers) occurs, an error event using interface ErrorEvent is fired at window and window.onerror
() is invoked (as well as handlers attached by window.addEventListener (not only capturing)). When a resource (such as an <img> or <script>) fails to load, an error event using interface Event is fired at the element that initiated the load, and the onerror
() handler on the element is invoked. These error events do not bubble up to window, but (at least in Firefox) can be handled with a window.addEventListener configured with useCaptu...
...overriden in some browsers using the crossorigin attribute on <script> and having the server send the appropriate CORS HTTP response headers. A workaround is to isolate "Script error." and handle it knowing that the error detail is only viewable in the browser console and not accessible via JavaScript. ...
HTMLOptionElement - Web APIs
elected Is a Boolean that indicates whether the option is currently selected. HTMLOptionElement.text Is a DOMString that contains the text content of the element. HTMLOptionElement.value Is a DOMString that reflects the value of the value HTML attribute, if it exists; otherwise reflects value of the Node.textContent property. Methods Inherits methods from its parent, HTMLElement. Option
() Is a constructor creating an HTMLOptionElement object. It has four values: the text to display, text, the value associated, value, the value of defaultSelected, and the value of selected. The last three values are optional. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLOptionElement' in that specification. Living Standard ...
...ciated, value, the value of defaultSelected, and the value of selected. The last three values are optional. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLOptionElement' in that specification. Living Standard HTML5The definition of 'HTMLOptionElement' in that specification. Recommendation A constructor, Option
(), has been added. The form property can be the null value. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLOptionElement' in that specification. Obsolete The selected property changed its meaning: it now indicates if the option is currently selected and no longer if it was initally selected. The defaultSelected property is no longer read-only. ...
HTMLOutputElement - Web APIs
hat this element is in. HTMLOutputElement.value A DOMString representing the value of the contents of the elements. Behaves like the Node.textContent property. HTMLOutputElement.willValidateRead only A Boolean indicating whether the element is a candidate for constraint validation. Methods This interface also inherits methods from its parent, HTMLElement. HTMLOutputElement.checkValidity
() Checks the validity of the element and returns a Boolean holding the check result. HTMLOutputElement.reportValidity
() This method reports the problems with the constraints on the element, if any, to the user. If there are problems, fires an invalid event at the element, and returns false; if there are no problems, it returns true. When the problem is reported, the user agent may focus the ele...
...hange the scrolling position of the document or perform some other action that brings the element to the user's attention. User agents may report more than one constraint violation if this element suffers from multiple problems at once. If the element is not rendered, then the user agent may report the error for the running script instead of notifying the user. HTMLOutputElement.setCustomValidity
() Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. Modes This element behaves in one of two modes: default mode and value mode. Default mode Initially, the element is in default mode, and so the contents of the element represent both the value of the element and its defau...
HTMLSlotElement - Web APIs
The HTMLSlotElement interface of the Shadow DOM API enables access to the name and assigned nodes of an HTML <slot> element. Properties HTMLSlotElement.name DOMString: Can be used to get and set the slot's name. Methods HTMLSlotElement.assignedNodes
() Returns a sequence of the nodes assigned to this slot, and if the flatten option is set to true, the assigned nodes of any other slots that are descendants of this slot. If no assigned nodes are found, it returns the slot's fallback content. HTMLSlotElement.assignedElements
() Returns a sequence of the elements assigned to this slot (and no other nodes). If the flatten option is set to true, it also returns the assigned elements of any other slots that are descendants of this slot. If no assigned nodes are found, it returns the slo...
... returns the slot's fallback content. Events slotchange Fired on an HTMLSlotElement instance (<slot> element) when the node(s) contained in that slot change. Examples The following snippet is taken from our slotchange example (see it live also). let slots = this.shadowRoot.querySelectorAll('slot'); slots[1].addEventListener('slotchange', function(e) { let nodes = slots[1].assignedNodes
(); console.log('Element in Slot "' + slots[1].name + '" changed to "' + nodes[0].outerHTML + '".'); }); Here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template -- which is the one that keeps having its contents changed in the example. Every time the element inserted in the slot changes, we log a report to the console saying which slot has c...
HTMLTrackElement: cuechange event - Web APIs
Track has changed the currently displaying cues. The event is fired at both the TextTrack and at the HTMLTrackElement in which it's being presented, if any. ...
...t is fired at both the TextTrack and at the HTMLTrackElement in which it's being presented, if any. Bubbles No Cancelable No Interface Event Event handler oncuechange Examples On the TextTrack You can set up a listener for the cuechange event on a TextTrack using the addEventListener
() method: track.addEventListener('cuechange', function
() { let cues = track.activeCues; // array of current cues }); Or you can just set the oncuechange event handler property: track.oncuechange = function
() { let cues = track.activeCues; // array of current cues } On the track element The underlying TextTrack, indicated by the track property, receives a cuechange event every time the currently-presented cue is changed. This happens even if ...
HTMLVideoElement.msHorizontalMirror - Web APIs
ck horizontally. Video perspective is flipped on a horizontal axis - this may be useful for playback of a webcam video, providing the user with better mirroring of their real behaviors (ie. ...
...cam video, providing the user with better mirroring of their real behaviors (ie. when user moves left, their representation on-screen would move left as well). ...
HashChangeEvent - Web APIs
window is navigating. HashChangeEvent.oldURL Read only The previous URL from which the window was navigated. Methods This interface has no methods of its own, but inherits the methods of its parent, Event. Examples Syntax options for a hash change You can listen for the hashchange event using any of the following options: window.onhashchange = funcRef; or <body onhashchange="funcRef
();"> or window.addEventListener("hashchange", funcRef, false); Basic example function locationHashChanged
() { if (location.hash === '#somecoolfeature') { somecoolfeature
(); } } window.addEventListener('hashchange', locationHashChanged); Polyfill There are several fallback scripts listed on the Modernizr GitHub page. Basically, those scripts check the location.hash at a regular ...
...ar interval. Here is a version that allows only one handler to be bound to the onhashchange property: ;(function(window) { // Exit if the browser implements that event if ( "onhashchange" in window.document.body ) { return; } var location = window.location, oldURL = location.href, oldHash = location.hash; // Check the location hash on a 100ms interval setInterval(function
() { var newURL = location.href, newHash = location.hash; // If the hash has changed and a handler has been bound... if ( newHash != oldHash && typeof window.onhashchange === "function" ) { // Execute the handler window.onhashchange({ type: "hashchange", oldURL: oldURL, newURL: newURL }); oldURL = newURL; oldHash = newHash; ...
HkdfParams - Web APIs
The HkdfParams dictionary of the Web Crypto API represents the object that should be passed as the algorithm parameter into SubtleCrypto.deriveKey
(), when using the HKDF algorithm. Properties name A DOMString. This should be set to HKDF. hash A DOMString representing the digest algorithm to use. This may be one of: SHA-1 SHA-256 SHA-384 SHA-512 salt A BufferSource. The HKDF specification states that adding salt "adds significantly to the strength of HKDF". Ideally, the salt is a random or pseudo-random value with the same length as the output of the digest function. Unlike the input key material passed into deriveKey
(), salt does not need to be kept secret. info A BufferSource representing application-specific contextual information. This is used to bind the deriv...
...tion-specific contextual information. This is used to bind the derived key to an application or context, and enables you to derive different keys for different contexts while using the same input key material. It's important that this should be independent of the input key material itself. This property is required but may be an empty buffer. Examples See the examples for SubtleCrypto.deriveKey
(). Specifications Specification Status Comment Web Cryptography APIThe definition of 'SubtleCrypto.HkdfParams' in that specification. Recommendation ...
HmacImportParams - Web APIs
Properties name A DOMString. This should be set to HMAC. hash A DOMString representing the name of the digest function to use. The can take a value of SHA-256, SHA-384, or SHA-512. Warning: Although you can technically pass SHA-1 here, this is strongly discouraged as it is considered vulnerable. length Optional A Number representing the length in bits of the key. ...
...couraged as it is considered vulnerable. length Optional A Number representing the length in bits of the key. If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default. Examples See the examples for SubtleCrypto.importKey
(). Specifications Specification Status Comment Web Cryptography APIThe definition of 'SubtleCrypto.HmacImportParams' in that specification. Recommendation ...
IDBCursor.direction - Web APIs
ection of travel using the 2nd argument of IDBObjectStore.openCursor. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. ...
... Recommendation Indexed Database API DraftThe definition of 'direction' in that specification. Recommendation Browser compatibility The ...
IDBDatabase: abort event - Web APIs
ours', 'hours', { unique: false }); objectStore.createIndex('minutes', 'minutes', { unique: false }); objectStore.createIndex('day', 'day', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; dBOpenRequest.onsuccess = (event) => { const db = dBOpenRequest.result; db.addEventListener('abort',
() => { console.log('Transaction aborted'); }); // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); // abort the transaction transaction.abort
(); }; The same example, but assigning the event handler to the onabort property: // Open the database const dBOpenRequest = window.indexedDB.open('toDoList', 4); dBO...
...e.createIndex('hours', 'hours', { unique: false }); objectStore.createIndex('minutes', 'minutes', { unique: false }); objectStore.createIndex('day', 'day', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; dBOpenRequest.onsuccess = (event) => { const db = dBOpenRequest.result; db.onabort =
() => { console.log('Transaction aborted'); }; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); // abort the transaction transaction.abort
(); }; ...
IDBDatabase.onabort - Web APIs
object. Note: This feature is available in Web Workers. Syntax IDBDatabase.onabort = function(event) { ... }; Example This example shows an IDBOpenDBRequest.onupgradeneeded block that creates a new object store; it also includes onerror and onabort functions to handle non-success cases. ...
...tion(event) { ... }; Example This example shows an IDBOpenDBRequest.onupgradeneeded block that creates a new object store; it also includes onerror and onabort functions to handle non-success cases. ...
databases - Web APIs
The databases method of the IDBFactory interface returns a list represening all the available databases, including their names and versions. Note: This feature is available in Web Workers. Note: This method is introduced in a draft of a specifications and browser compatibility is limited. Syntax const promise = indexedDB.databases
() Parameters The method does not take in any parameters. Return value A promise that resolves either to an error or a list of dictionaries, each with two elements, name and version. name The database name. version The database version. Exceptions This method may raise a DOMException of the following types: Attribute Description SecurityError The method is called from an opaque origin. Other error Specifica...
... elements, name and version. name The database name. version The database version. Exceptions This method may raise a DOMException of the following types: Attribute Description SecurityError The method is called from an opaque origin. Other error Specification does not describe all possible errors. Example const promise = indexedDB.databases
() promise.then(databases => { console.log(databases) }) Specifications Specification Status Comment Indexed Database API DraftThe definition of 'databases
()' in that specification. Recommendation Initial definition. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, ple...
IDBKeyRange.lower - Web APIs
ect store, and open a Cursor with IDBObjectStore.openCursor, declaring keyRangeValue as its optional key range value. After declaring the key range, we log its lower property value to the console, which should appear as "F". ...
... Recommendation Indexed Database API DraftThe definition of 'lower' in that specification. Recommendation Browser compatibility The compat...
IDBKeyRange.lowerOpen - Web APIs
ing keyRangeValue as its optional key range value. After declaring the key range, we log its lowerOpen property value to the console, which should appear as "true": the lower bound is open, so won't be included in the range. ...
... Recommendation Indexed Database API DraftThe definition of 'lowerOpen' in that specification. Recommendation Browser compatibility The c...
IDBKeyRange.upper - Web APIs
ect store, and open a Cursor with IDBObjectStore.openCursor, declaring keyRangeValue as its optional key range value. After declaring the key range, we log its upper property value to the console, which should appear as "W". ...
... Recommendation Indexed Database API DraftThe definition of 'upper' in that specification. Recommendation Browser compatibility The compat...
IntersectionObserver.thresholds - Web APIs
If only one threshold ratio was provided when instanitating the object, this will be an array containing that single value. See Thresholds in Intersection Observer API to learn how thresholds work. Syntax var thresholds = IntersectionObserver.thresholds; Value An array of intersection thresholds, originally specified using the threshold property when instantiating the observer. ...
...thresholds, originally specified using the threshold property when instantiating the observer. If only one observer was specified, without being in an array, this value is a one-entry array containing that threshold. Regardless of the order your original threshold array was in, this one is always sorted in numerically increasing order. If no threshold option was included when IntersectionObserver
() was used to instantiate the observer, the value of thresholds is simply [0]. Be careful! Although the options object you can specify when creating an IntersectionObserver has a field named threshold, this property is called thresholds. Confusing? Yes. If you accidentally use thresholds as the name of the field in your options, the thresholds array will wind up being simply [0.0], which is likel...
IntersectionObserver - Web APIs
server is created, it's configured to watch for given ratios of visibility within the root. The configuration cannot be changed once the IntersectionObserver is created, so a given observer object is only useful for watching for specific changes in degree of visibility; however, you can watch multiple target elements with the same observer. Constructor IntersectionObserver.IntersectionObserver
() Creates a new IntersectionObserver object which will execute a specified callback function when it detects that a target element's visibility has crossed one or more thresholds. Properties IntersectionObserver.root Read only The Element or Document whose bounds are used as the bounding box when testing for intersection. If no root value was passed to the constructor or its value is null, ...
...px". IntersectionObserver.thresholds Read only A list of thresholds, sorted in increasing numeric order, where each threshold is a ratio of intersection area to bounding box area of an observed target. Notifications for a target are generated when any of the thresholds are crossed for that target. If no value was passed to the constructor, 0 is used. Methods IntersectionObserver.disconnect
() Stops the IntersectionObserver object from observing any target. IntersectionObserver.observe
() Tells the IntersectionObserver a target element to observe. IntersectionObserver.takeRecords
() Returns an array of IntersectionObserverEntry objects for all observed targets. IntersectionObserver.unobserve
() Tells the IntersectionObserver to stop observing a particular target element. Examples...
KeyboardEvent.key - Web APIs
press is now "2" because the modifier shift key is no longer active. The same goes for the InputEvent.data property of the beforeinput and input events. As we finally release the key 2, a keyup event is fired but the key property will be set to the string value 2 for both keyboard layouts because the modifier shift key is no longer active. Example This example uses EventTarget.addEventListener
() to listen for keydown events. When they occur, the key's value is checked to see if it's one of the keys the code is interested in, and if it is, it gets processed in some way (possibly by steering a spacecraft, perhaps by changing the selected cell in a spreadsheet). window.addEventListener("keydown", function (event) { if (event.defaultPrevented) { return; // Do nothing if the event was ...
...rrow" key press. break; case "Enter": // Do something for "enter" or "return" key press. break; case "Esc": // IE/Edge specific value case "Escape": // Do something for "esc" key press. break; default: return; // Quit when this doesn't handle the key event. } // Cancel the default action to avoid it being handled twice event.preventDefault
(); }, true); Specification Specification Status Comment UI EventsThe definition of 'KeyboardEvent.key' in that specification. Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'KeyboardEvent.key' in that specification. Obsolete Initial definition, included key values. ...
KeyboardLayoutMap - Web APIs
Map.keys Read only Returns a new Array Iterator object that contains the keys for each index in the array. KeyboardLayoutMap.size Read only Returns the number of elements in the KeyboardLayoutMap object. KeyboardLayoutMap.values Read only Returns a new Array Iterator object that contains the values for each index in the KeyboardLayoutMap object. Methods KeyboardLayoutMap.forEach
() Read only Executes a provided function once for each element of KeyboardLayoutMap. KeyboardLayoutMap.get
() Returns the element with the given key from the KeyboardLayoutMap object. KeyboardLayoutMap.has
() Returns a boolean indicating whether the KeyboardLayoutMap object has an element with the specified key. Examples The following example demonstrates how to get the location- or la...
...eyboardLayoutMap object. KeyboardLayoutMap.has
() Returns a boolean indicating whether the KeyboardLayoutMap object has an element with the specified key. Examples The following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'W' key on an English QWERTY keyboard. var keyboard = navigator.keyboard; keyboard.getLayoutMap
() .then(keyboardLayoutMap => { var upKey = keyboardLayoutMap.get('KeyW'); window.alert('Press ' + upKey + ' to move up.'); }) Specifications Specification Status Comment Keyboard MapThe definition of 'KeyboardLayoutMap' in that specification. Editor's Draft Initial definition. ...
Keyboard API - Web APIs
s for converting codes to keys. A list of valid code values is found in the Writing System Keys section of the UI Events KeyboardEvent code Values spec. The following example demonstrates how to get the location-specific or layout-specific string associated with the key labeled W on an English QWERTY keyboard. if (navigator.keyboard) { var keyboard = navigator.keyboard; keyboard.getLayoutMap
() .then(keyboardLayoutMap => { var upKey = keyboardLayoutMap.get('KeyW'); window.alert('Press ' + upKey + ' to move up.'); }); } else { // Do something else. } Keyboard locking Richly interactive web pages, games, and remote-streaming experiences often require access to special keys and keyboard shortcuts while in full-screen mode. Examples of such key/key combinations include Esca...
... and remote-streaming experiences often require access to special keys and keyboard shortcuts while in full-screen mode. Examples of such key/key combinations include Escape, Alt+Tab, and Ctrl+N. Those keys and key combinations are typically captured by the user agent or the underlying operating system, as illustrated in the following example. To capture the "W", "A", "S", and "D" keys, call lock
() with a list that contains the key code attribute value for each of these keys: navigator.keyboard.lock(["KeyW", "KeyA", "KeyS", "KeyD"]); This captures these keys regardless of which modifiers are used with the key press. Assuming a standard United States QWERTY layout, registering KeyW ensures that "W", Shift+"W", Control+"W", Control+Shift+"W", and all other key modifier combinations with "W"...
LinearAccelerationSensor - Web APIs
sor, the user must grant permission to the 'accelerometer' 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 LinearAccelerationSensor.LinearAccelerationSensor
() Creates a new LinearAccelerationSensor object. Properties LinearAccelerationSensor.x Read only Returns a double containing the linear acceleration of the device along the device's x axis. LinearAccelerationSensor.y Read only Returns a double containing the linear acceleration of the device along the device's y axis. LinearAccelerationSensor.z Read only Returns a double containing th...
...t callback. In the example below this occurs sixty times a second. let laSensor = new LinearAccelerationSensor({frequency: 60}); laSensor.addEventListener('reading', e => { console.log("Linear acceleration along the X-axis " + laSensor.x); console.log("Linear acceleration along the Y-axis " + laSensor.y); console.log("Linear acceleration along the Z-axis " + laSensor.z); }); laSensor.start
(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. AccelerometerThe definition of 'LinearAccelerationSensor' in that specification. Candidate Recommendation ...
LocalMediaStream - Web APIs
The LocalMediaStream interface was part of the Media Capture and Streams API, representing a stream of data being generated locally (such as by getUserMedia
(). However, getUserMedia
() now returns a MediaStream instead, and this interface has been removed from the specification. Warning: This interface is no longer available in any mainstream browser. Do not use LocalMediaStream; you need to update any code that does use it as soon as possible or your content or application will stop working. See Stopping a video stream in MediaStreamTrack to learn how. All other functionality is found in MediaStream. The primary reason for this interface to exist was to add a stop
() method to its MediaStream parent interface. However, control over playback of media has been moved to the indivi...
...a video stream in MediaStreamTrack to learn how. All other functionality is found in MediaStream. The primary reason for this interface to exist was to add a stop
() method to its MediaStream parent interface. However, control over playback of media has been moved to the individual MediaStreamTrack objects, so this is no longer necessary. Instead, media is stopped by calling MediaStreamTrack.stop
() on each track that needs to be stopped. The example for MediaStreamTrack.stop
() demonstrates how to stop a multi-track stream, which is what LocalMediaStream.stop
() used to be used for. Methods LocalMediaStream.stop
() Stops the stream. When the source of the stream is a connected device (such as a camera or microphone), capture of media from the device is halted. This method is no longer ava...
Locks.mode - Web APIs
LockManager is the object returned by navigator.locks. ...
...LockManager is the object returned by navigator.locks. ...
MIDIAccess - Web APIs
rns an instance of MIDIOutputMap which provides access to any available MIDI output ports. MIDIAccess.sysexEnabled Read only A boolean attribute indicating whether system exclusive support is enabled on the current MIDIAccess instance. Event Handlers MIDIAccess.onstatechange Called whenever a new MIDI port is added or an existing port changes state. ...
...d only A boolean attribute indicating whether system exclusive support is enabled on the current MIDIAccess instance. Event Handlers MIDIAccess.onstatechange Called whenever a new MIDI port is added or an existing port changes state. Examples navigator.requestMIDIAccess
() .then(function(access) { // Get lists of available MIDI controllers const inputs = access.inputs.values
(); const outputs = access.outputs.values
(); access.onstatechange = function(e) { // Print information about the (dis)connected MIDI controller console.log(e.port.name, e.port.manufacturer, e.port.state); }; }); Specifications Specification Status Comment Web MIDI API Working Draft Initial definition. ...
MSCandidateWindowShow - Web APIs
tRect method, and adjust your layout as needed to avoid any occlusions with the IME candidate window. Web applications need only register for this event once per element (the handler will remain valid for the lifetime of the element). ...
... (the handler will remain valid for the lifetime of the element). Example in IE11, developers can detect the opening of the IME candidate window by listening to MSCandidateWindowShow event, then call getCandidateWindowClientRect
() function to find out where the candidate window is and position the suggestion UI away from it: var context = document.getElementById("mySearchBox").msGetInputContext
(); context.addEventListener("MSCandidateWindowShow", candidateWindowShowHandler); function candidateWindowShowHandler(e) { var imeRect = context.getCandidateWindowClientRect
(); var suggestionRect = document.getElementById("mySuggestionList").getBoundingClientRect
(); // Check if the two rects intersect, and position them away from each other. } When the IME candidate window changes posit...
MSSiteModeEvent - Web APIs
nt provides event properties that are specific to pinned site events. This proprietary method is specific to Internet Explorer and Microsoft Edge. DOM Information Inheritance Hierarchy Event MSSiteModeEvent Methods Method Description initEvent Initializes a new generic event that the createEvent method created. *Note that as of Microsoft Edge, the createEvent
()/initEvent
() constructor pattern for synthetic events is deprecated. preventDefault Cancels the default action of an event. stopImmediatePropagation Prevents any further propagation of an event. stopPropagation Prevents propagation of an event beyond the current target. Properties Property Description actionURL Gets the URL of...
...event. timeStamp Gets the time, in milliseconds, when an event occurred. ...
Magnetometer - Web APIs
sensor. To use this sensor, the user must grant permission to the 'magnetometer' device sensor through the Permissions API. If a feature policy blocks use of a feature, it's 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 Magnetometer.Magnetometer
() Creates a new Magnetometer object. Properties Magnetometer.x Read only Returns a double containing the magnetic field around the device's x axis. Magnetometer.y Read only Returns a double containing the magnetic field around the device's y axis. Magnetometer.z Read only Returns a double containing the magnetic field around the device's z axis. Example The magnetometer is typicall...
...Sensor.onreading event callback. In the example below this occurs sixty times a second. let magSensor = new Magnetometer({frequency: 60}); magSensor.addEventListener('reading', e => { console.log("Magnetic field along the X-axis " + magSensor.x); console.log("Magnetic field along the Y-axis " + magSensor.y); console.log("Magnetic field along the Z-axis " + magSensor.z); }); magSensor.start
(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. MagnetometerThe definition of 'Magnetometer' in that specification. Candidate Recommendation ...
MediaCapabilities - Web APIs
be used to query the browser about the decoding abilities of the device based on codecs, profile, resolution, and bitrates. The information can be used to serve optimal media streams to the user and determine if playback should be smooth and power efficient. The information is accessed through the mediaCapabilities property of the Navigator interface. ...
...d be smooth and power efficient. The information is accessed through the mediaCapabilities property of the Navigator interface. Methods MediaCapabilities.encodingInfo
() When passed a valid media configuration, it returns a promise with information as to whether the media type is supported, and whether encoding such media would be smooth and power efficient. MediaCapabilities.decodingInfo
() When passed a valid media configuration, it returns a promise with information as to whether the media type is supported, and whether decoding such media would be smooth and power efficient. Specifications Specification Status Comment Media CapabilitiesThe definition of 'MediaCapabilities' in that specification. Draft Initial definition ...
MediaConfiguration - Web APIs
Properties A valid configuration includes a valid encoding configuration type or decoding configuration type and a valid audio configuration or video configuration. If you plan on querying encoding information, set the media type to record or transmission. For decoding, set the type to file or media-source. ...
...number of channels, the bitrate, and the sample rate. Video configurations mush include a valid video MIME type as contentType, the bitrate, and framerate, along with the width and the height of the video file. All of these must be present, as in the examples below, or a TypeError will occur. A valid media decoding configuration, to be submitted as the parameter for mediaCapabilities.decodingInfo
() method, has it's `type` set as: file: For plain playback file. media-source: For media source files. A valid media encoding configuration, to be submitted as the parameter for mediaCapabilities.encodingInfo
() method, has it's `type` set as: record: For recording media. transmission: For media to be electronically transmitted. A valid audio configuration includes: ...
MediaStreamTrack.onoverconstrained - Web APIs
The MediaStreamTrack.onoverconstrained event handler is a property called when the overconstrained event is received. Such an event is sent when the track is again able to send data. ...
...track is again able to send data. Syntax track.onoverconstrained = function; Values function is the name of a user-defined function, without the
() suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. ...
MediaStreamTrackAudioSourceOptions - Web APIs
Properties mediaStreamTrack The MediaStreamTrack from which to take audio data for this node's output. ...
... Properties mediaStreamTrack The MediaStreamTrack from which to take audio data for this node's output. ...
MediaTrackConstraints.deviceId - Web APIs
The MediaTrackConstraints dictionary's deviceId property is a ConstrainDOMString describing the requested or mandatory constraints placed upon the value of the deviceId constrainable property. If needed, you can determine whether or not this constraint is supported by checking the value of MediaTrackSupportedConstraints.deviceId as returned by a call to MediaDevices.getSupportedConstraints
(). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Because RTP doesn't include this information, tracks associated with a WebRTC RTCPeerConnection will never include this property. Syntax var constraintsObject = { deviceId: constraint }; constraintsObject.deviceId = constraint; Value An object based on ConstrainDOMString specifying ...
...ue for a given origin, and are guaranteed to be the same across browsing sessions on the same origin. However, the value of the deviceId is determined by the source of the track's content, and there's no particular format mandated by the specification (although some kind of GUID is recommended). That means that a given track will only return one value for the deviceId when you call getCapabilities
(). Because of this, there's no use for the device ID when calling MediaStreamTrack.applyConstraints
(), since there is only one possible value; however, you can record a deviceId and use it to ensure that you get the same source for multiple calls to getUserMedia
(). An exception to the rule that device IDs are the same across browsing sessions: private browsing mode will use a different ID, and w...
MediaTrackConstraints.groupId - Web APIs
The MediaTrackConstraints dictionary's groupId property is a ConstrainDOMString describing the requested or mandatory constraints placed upon the value of the groupId constrainable property. If needed, you can determine whether or not this constraint is supported by checking the value of MediaTrackSupportedConstraints.groupId as returned by a call to MediaDevices.getSupportedConstraints
(). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Syntax var constraintsObject = { groupId: constraint }; constraintsObject.groupId = constraint; Value An object based on ConstrainDOMString specifying one or more acceptable, ideal, and/or exact (mandatory) group IDs which are acceptable as the source of media content. Group IDs are un...
...trieving the group ID of the input device and specifying it when asking for an output device, perhaps. However, the value of the groupId is determined by the source of the track's content, and there's no particular format mandated by the specification (although some kind of GUID is recommended). That means that a given track will only return one value for the groupId when you call getCapabilities
(), and keep in mind that this value will change for each browsing session. Because of this, there's no use for the group ID when calling MediaStreamTrack.applyConstraints
(), since there is only one possible value, and you can't use it to ensure the same group is used across multiple browsing sessions when calling getUserMedia
(). Example See Example: Constraint exerciser in Capabilities, constrai...
MediaTrackSettings.autoGainControl - Web APIs
MediaTrackSettings dictionary's autoGainControl property is a Boolean value whose value indicates whether or not automatic gain control (AGC) is enabled on an audio track. This lets you determine what value was selected to comply with your specified constraints for this property's value as described in the MediaTrackConstraints.autoGainControl property you provided when calling either getUserMedia
() or MediaStreamTrack.applyConstraints
(). Automatic gain control is a feature in which a sound source automatically manages changes in the volume of its source media to maintain a steady overall volume level. This feature is typically used on microphones, although it can be provided by other input sources as well. If needed, you can determine whether or not this constraint is supported by checkin...
... changes in the volume of its source media to maintain a steady overall volume level. This feature is typically used on microphones, although it can be provided by other input sources as well. If needed, you can determine whether or not this constraint is supported by checking the value of MediaTrackSupportedConstraints.autoGainControl as returned by a call to MediaDevices.getSupportedConstraints
(). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Syntax var autoGainControl = MediaTrackSettings.autoGainControl; Value A Boolean value which is true if the track has automatic gain control enabled or false if AGC is disabled. Example See Example: Constraint exerciser in Capabilities, constraints, and settings for an example...
MediaTrackSettings.deviceId - Web APIs
gs dictionary's deviceId property is a DOMString which uniquely identifies the source for the corresponding MediaStreamTrack for the origin corresponding to the browsing session. This lets you determine what value was selected to comply with your specified constraints for this property's value as described in the MediaTrackConstraints.deviceId property you provided when calling either getUserMedia
(). If needed, you can determine whether or not this constraint is supported by checking the value of MediaTrackSupportedConstraints.deviceId as returned by a call to MediaDevices.getSupportedConstraints
(). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Because RTP doesn't include this information, tracks associated with a WebRTC R...
... for multiple sessions, for example. The actual value of the string, however, is determined by the source of the track, and there is no guarantee what form it will take, although the specification does recommend it be a GUID. Since there is a one-to-one pairing of ID with each source, all tracks with the same source will share the same ID for any given origin, so MediaStreamTrack.getCapabilities
() will always return exactly one value for deviceId. That makes the device ID not useful for any changes to constraints when calling MediaStreamTrack.applyConstraints
(). An exception to the rule that device IDs are the same across browsing sessions: private browsing mode will use a different ID, and will change it each browsing session. Example See Example: Constraint exerciser in Capabilities...
MediaTrackSettings.echoCancellation - Web APIs
The MediaTrackSettings dictionary's echoCancellation property is a Boolean value whose value indicates whether or not echo cancellation is enabled on an audio track. This lets you determine what value was selected to comply with your specified constraints for this property's value as described in the MediaTrackConstraints.echoCancellation property you provided when calling either getUserMedia
() or MediaStreamTrack.applyConstraints
(). Echo cancellation is a feature which attempts to prevent echo effects on a two-way audio connection by attempting to reduce or eliminate crosstalk between the user's output device and their input device. For example, it might apply a filter that negates the sound being produced on the speakers from being included in the input track generated from the microphon...
...device and their input device. For example, it might apply a filter that negates the sound being produced on the speakers from being included in the input track generated from the microphone. If needed, you can determine whether or not this constraint is supported by checking the value of MediaTrackSupportedConstraints.echoCancellation as returned by a call to MediaDevices.getSupportedConstraints
(). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Because RTP doesn't include this information, tracks associated with a WebRTC RTCPeerConnection will never include this property. Syntax var echoCancellation = MediaTrackSettings.echoCancellation; Value A Boolean value which is true if the track has echo cancellation functional...
MediaTrackSettings.groupId - Web APIs
e MediaTrackSettings dictionary's groupId property is a browsing-session unique DOMString which identifies the group of devices which includes the source for the MediaStreamTrack. This lets you determine what value was selected to comply with your specified constraints for this property's value as described in the MediaTrackConstraints.groupId property you provided when calling either getUserMedia
(). If needed, you can determine whether or not this constraint is supported by checking the value of MediaTrackSupportedConstraints.groupId as returned by a call to MediaDevices.getSupportedConstraints
(). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Because RTP doesn't include this information, tracks associated with a WebRTC RT...
... to ensure that the built-in camera and microphone on a phone are being used for video conferencing purposes. The actual value of the string, however, is determined by the source of the track, and there is no guarantee what form it will take, although the specification does recommend it be a GUID. Since this property isn't stable across browsing sessions, its usefulness when calling getUserMedia
() is generally limited to ensuring that tasks performed during the same browsing session use devices from the same group (or that they don't use devices from the same group). There is no situation in which the groupId is useful when calling applyConstraints
(), since the value can't be changed. Example See Example: Constraint exerciser in Capabilities, constraints, and settings for an example. Sp...
MediaTrackSettings.noiseSuppression - Web APIs
diaTrackSettings dictionary's noiseSuppression property is a Boolean value whose value indicates whether or not noise suppression technology is enabled on an audio track. This lets you determine what value was selected to comply with your specified constraints for this property's value as described in the MediaTrackConstraints.noiseSuppression property you provided when calling either getUserMedia
() or MediaStreamTrack.applyConstraints
(). Noise suppression automatically filters the audio to remove background noise, hum caused by equipment, and the like from the sound before delivering it to your code. This feature is typically used on microphones, although it is technically possible it could be provided by other input sources as well. If needed, you can determine whether or not this constr...
... like from the sound before delivering it to your code. This feature is typically used on microphones, although it is technically possible it could be provided by other input sources as well. If needed, you can determine whether or not this constraint is supported by checking the value of MediaTrackSupportedConstraints.noiseSuppression as returned by a call to MediaDevices.getSupportedConstraints
(). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Syntax var noiseSuppression = MediaTrackSettings.noiseSuppression; Value A Boolean value which is true if the input track has noise suppression enabled or false if AGC is disabled. Example See Example: Constraint exerciser in Capabilities, constraints, and settings for an exam...
MediaTrackSupportedConstraints.aspectRatio - Web APIs
The MediaTrackSupportedConstraints dictionary's aspectRatio property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints
() if and only if the user agent supports the aspectRatio constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax aspectConstraintSupported = supportedConstraintsDictionary.aspectRatio; Value This property is present in the dictionary (and its value is always true) if the user agent supports the aspectRatio constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and ...
...constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints
().aspectRatio) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'aspectRatio' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.autoGainControl - Web APIs
The MediaTrackSupportedConstraints dictionary's autoGainControl property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints
() if and only if the user agent supports the autoGainControl constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints
(). The autoGainControl constraint indicates whether or not the browser offers the ability to automatically control the gain (volume) on media tracks; this obviously is contingent on whether or not the individual device supports automatic gain control as well; it's typically a feature provided by microphones. Synt...
...dictionary, and you'll get undefined if you try to look at its value. Example This example simply displays whether or not your browser supports the autoGainControl constraint. HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints
().autoGainControl) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'autoGainControl' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.channelCount - Web APIs
The MediaTrackSupportedConstraints dictionary's channelCount property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints
() if and only if the user agent supports the channelCount constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax channelCountConstraintSupported = supportedConstraintsDictionary.channelCount; Value This property is present in the dictionary (and its value is always true) if the user agent supports the channelCount constraint. If the property isn't present, this property is missing from the supported constraints dictio...
...constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints
().channelCount) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'channelCount' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.deviceId - Web APIs
The MediaTrackSupportedConstraints dictionary's deviceId property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints
() if and only if the user agent supports the deviceId constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax deviceIdConstraintSupported = supportedConstraintsDictionary.deviceId; Value This property is present in the dictionary (and its value is always true) if the user agent supports the deviceId constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get...
...constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints
().deviceId) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'deviceId' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.echoCancellation - Web APIs
The MediaTrackSupportedConstraints dictionary's echoCancellation property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints
() if and only if the user agent supports the echoCancellation constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax echoCancellationConstraintSupported = supportedConstraintsDictionary.echoCancellation; Value This property is present in the dictionary (and its value is always true) if the user agent supports the echoCancellation constraint. If the property isn't present, this property is missing from the supporte...
...constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints
().echoCancellation) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'echoCancellation' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.facingMode - Web APIs
The MediaTrackSupportedConstraints dictionary's facingMode property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints
() if and only if the user agent supports the facingMode constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax facingModeConstraintSupported = supportedConstraintsDictionary.facingMode; Value This property is present in the dictionary (and its value is always true) if the user agent supports the facingMode constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and ...
...supports the facingMode constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML <div id="result"> </div> CSS #result { font: 14px "Arial", sans-serif; } JavaScript let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints
().facingMode) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'facingMode' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.frameRate - Web APIs
If the constraint isn't supported, it's not included in the list, so this value will never be false. The frameRate constraint can be used to establish acceptable upper and lower bounds on the video frame rate for a new video track, or to specify an exact frame rate that must be provided for the request to succeed. ...
...perty isn't present, the user agent doesn't allow specifying limits on the frame rate for video tracks. If this property is present, its value is always true. Example This simple example looks to see if your browser supports constraining the frame rate when requesting video tracks. JavaScript let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints
().frameRate) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } HTML <div id="result"> </div> CSS #result { font: 14px "Arial", sans-serif; } Result The output, showing if your browser supports the frameRate constraint, is: While this example is trivial, you can replace the simple output of "Supported" vs. "Not supported" with code to provide...
MediaTrackSupportedConstraints.groupId - Web APIs
The MediaTrackSupportedConstraints dictionary's groupId property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints
() if and only if the user agent supports the groupId constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax groupIdConstraintSupported = supportedConstraintsDictionary.groupId; Value This property is present in the dictionary (and its value is always true) if the user agent supports the groupId constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get unde...
...constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints
().groupId) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'groupId' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.height - Web APIs
The MediaTrackSupportedConstraints dictionary's height property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints
() if and only if the user agent supports the height constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax heightConstraintSupported = supportedConstraintsDictionary.height; Value This property is present in the dictionary (and its value is always true) if the user agent supports the height constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined...
...constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints
().height) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'height' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.latency - Web APIs
The MediaTrackSupportedConstraints dictionary's latency property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints
() if and only if the user agent supports the latency constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax latencyConstraintSupported = supportedConstraintsDictionary.latency; Value This property is present in the dictionary (and its value is always true) if the user agent supports the latency constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get unde...
...constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints
().latency) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'latency' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.noiseSuppression - Web APIs
The MediaTrackSupportedConstraints dictionary's noiseSuppression property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints
() if and only if the user agent supports the noiseSuppression constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints
(). The noiseSuppression constraint indicates whether or not the browser offers the ability to automatically control the gain (volume) on media tracks; this obviously is contingent on whether or not the individual device supports automatic gain control as well. Syntax noiseSuppressionSupported = supportedConstr...
...ictionary, and you'll get undefined if you try to look at its value. Example This example simply displays whether or not your browser supports the noiseSuppression constraint. HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints
().noiseSuppression) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'noiseSuppression' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.sampleRate - Web APIs
The MediaTrackSupportedConstraints dictionary's sampleRate property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints
() if and only if the user agent supports the sampleRate constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax sampleRateConstraintSupported = supportedConstraintsDictionary.sampleRate; Value This property is present in the dictionary (and its value is always true) if the user agent supports the sampleRate constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and ...
...constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints
().sampleRate) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'sampleRate' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.sampleSize - Web APIs
The MediaTrackSupportedConstraints dictionary's sampleSize property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints
() if and only if the user agent supports the sampleSize constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax sampleSizeConstraintSupported = supportedConstraintsDictionary.sampleSize; Value This property is present in the dictionary (and its value is always true) if the user agent supports the sampleSize constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and ...
...constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints
().sampleSize) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'sampleSize' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.volume - Web APIs
The MediaTrackSupportedConstraints dictionary's volume property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints
() if and only if the user agent supports the volume constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax volumeConstraintSupported = supportedConstraintsDictionary.volume; Value This property is present in the dictionary (and its value is always true) if the user agent supports the volume constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefin...
...constraint. ...
MediaTrackSupportedConstraints.width - Web APIs
The MediaTrackSupportedConstraints dictionary's width property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints
() if and only if the user agent supports the width constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints
(). Syntax widthConstraintSupported = supportedConstraintsDictionary.width; Value This property is present in the dictionary (and its value is always true) if the user agent supports the width constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if y...
...constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints
().width) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'width' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints - Web APIs
The MediaTrackSupportedConstraints dictionary establishes the list of constrainable properties recognized by the user agent or browser in its implementation of the MediaStreamTrack object. An object conforming to MediaTrackSupportedConstraints is returned by MediaDevices.getSupportedConstraints
(). Because of the way interface definitions in WebIDL work, if a constraint is requested but not supported, no error will occur. ...
... An actual constraint set is described using an object based on the MediaTrackConstraints dictionary. ...
MerchantValidationEvent - Web APIs
The MerchantValidationEvent interface of the the Payment Request API enables a merchant to verify themselves as allowed to use a particular payment handler. To learn more about merchant validation, see Merchant validation in Payment processing concepts. Constructor MerchantValidationEvent
() Secure context Creates a new MerchantValidationEvent object describing a merchantvalidation event that will be sent to the payment handler to request that it validate the merchant. Properties MerchantValidationEvent.methodName Secure context A DOMString providing a unique payment method identifier for the payment handler that's requiring validation. This may be either one of the standard payment method identifier strings or a URL that both identifies and handles requests for the payment han...
... or a URL that both identifies and handles requests for the payment handler, such as https://apple.com/apple-pay. MerchantValidationEvent.validationURL Secure context A USVString specifying a URL from which the site or app can fetch payment handler specific validation information. Once this data is retrieved, the data (or a promise resolving to the validation data) should be passed into complete
() to validate that the payment request is coming from an authorized merchant. Methods MerchantValidationEvent.complete
() Secure context Pass the data retrieved from the URL specified by validationURL into complete
() to complete the validation process for the PaymentRequest. Specifications Specification Status Comment Payment Request APIThe definition of 'MerchantVal...
MessageChannel.port2 - Web APIs
essageChannel.MessageChannel constructor. When the IFrame has loaded, we pass port2 to the IFrame using MessagePort.postMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. ...
...ge being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. var channel = new MessageChannel
(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded
() { otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } For a full working example, see our channel messaging basic demo on Github (run it live too). Specifications Specification Status Comment HTML Living StandardThe definition of 'port2' in t...
MimeTypeArray - Web APIs
The MimeTypeArray interface returns an array of MimeType instances, each of which contains information about a supported browser plugins. This object is returned by NavigatorPlugins.mimeTypes. Properties MimeTypeArray.length The number of items in the array. Methods MimeTypeArray.item
() Returns the MimeType object with the specified index. MimeTypeArray.namedItem
() Returns the MimeType object with the specified name. ...
...} else { // Notify the user that flash is being deprecated and they // should upgrade their browser. } Specifications Specification Status Comment HTML Living StandardThe definition of 'MimeTypeArray' in that specification. ...
MutationObserverInit.attributeOldValue - Web APIs
notifyUser("Attribute name " + mutation.attributeName + " changed to " + mutation.target[mutation.attributeName] + " (was " + mutation.oldValue + ")"); break; } }); } var targetNode = document.querySelector("#target"); var observer = new MutationObserver(callback); observer.observe(targetNode, { attributes: true, attributeOldValue: true }); The callback
() function--which will be passed into the observe
() method when starting the observer, looks at each item in the list of MutationRecord objects. For any items representing an attribute change (which can be detected by the value of MutationRecord.type being "attributes"), a function called notifyUser
() is used to tell the user the name of the attribute that changed as well as the attribute's new val...
...ch item in the list of MutationRecord objects. For any items representing an attribute change (which can be detected by the value of MutationRecord.type being "attributes"), a function called notifyUser
() is used to tell the user the name of the attribute that changed as well as the attribute's new value (mutation.target[mutation.attributeName]) and its old value (mutation.oldValue). When observe
() is called, the specified options are attributes and attributeOldValue, which means that changes to attribute values will be reported, and each mutation record will include the oldValue property specifying the attribute's previous value. Specifications Specification Status Comment DOMThe definition of 'MutationObserverInit.attributeOldValue' in that specification. ...
PaymentMethodChangeEvent - Web APIs
Syntax paymentMethodChangeEvent = new PaymentMethodChangeEvent(type, options); Parameters type A DOMString which must contain the string paymentmethodchange, the name of the only type of event which uses the PaymentMethodChangeEvent interface. options Optional An optional PaymentMethodChangeEventInit dictionary which may contain zero or more of the following properties: methodName Optional A DOMString containing the payment method identifier for the payment handler being used. This is an empty string by default. ...
...ame property. The type of the methodDetails property depends on the payment method. For example, if methodName is basic-card, indicating that the basic card payment method is being used for validation, the methodDetails field must be a BasicCardChangeDetails object. Specifications Specification Status Comment Payment Request APIThe definition of 'PaymentMethodChangeEvent
()' in that specification. Candidate Recommendation Initial definition. ...
PaymentRequest.onpaymentmethodchange - Web APIs
aymentRequest, indicating that the user has changed payment methods within the same payment handler. The paymentmethodchange event is triggered by a user-agent controlled interaction (i.e., the end-user switches from a debit to a credit card in the payment UI). To make sure you receive the event, you should add event listeners to PaymentRequest object after instantiation, but before you call show
(). Examples An example payment method change handler is shown below; this example handles changes made to the payment method when using Apple Pay, specifically: request.onpaymentmethodchange = ev => { const { type: cardType } = ev.methodDetails; const newStuff = {}; if (ev.methodName === "https://apple.com/apple-pay") { switch (cardType) { case "store": // do Apple Pay sp...
...s://apple.com/apple-pay") { switch (cardType) { case "store": // do Apple Pay specific handling for store card... // methodDetails contains the store card information const result = calculateDiscount(ev.methodDetails); Object.assign(newStuff, result); break; } } // finally... ev.updateWith(newStuff); }; const response = await request.show
(); Specifications Specification Status Comment Payment Request APIThe definition of 'onpaymentmethodchange' in that specification. Candidate Recommendation Initial definition. ...
PaymentRequest.onshippingaddresschange - Web APIs
ples The shippingaddresschange event is triggered by a user-agent controlled interaction. If the address stored by the user agent changes at any time during a payment process, the event is triggered. To make sure an updated address is included when sending payment information to the server, you should add event listeners for a PaymentRequest object after instantiation, but before the call to show
(). ...
...}).catch(function(err) { console.error("Uh oh, something bad happened", err.message); }); Specifications Specification Status Comment Payment Request APIThe definition of 'onshippingaddresschange' in that specification. ...
PaymentRequest.shippingAddress - Web APIs
t. Syntax var paymentAddress = PaymentRequest.shippingAddress; Example Generally, the user agent will fill the shippingAddress property value. You can trigger this by setting PaymentOptions.requestShipping to true when calling the PaymentRequest constructor. In the example below, the cost of shipping varies by geography. When the PaymentRequest.onshippingaddresschange is called, updateDetails
() is called to update the details of the PaymentRequest, using shippingAddress to set the correct shipping cost. // Initialization of PaymentRequest arguments are excerpted for the sake of // brevity. var payment = new PaymentRequest(supportedInstruments, details, options); payment.addEventListener('shippingaddresschange', function(evt) { evt.updateWith(new Promise(function(resolve) { upd...
...o set the correct shipping cost. // Initialization of PaymentRequest arguments are excerpted for the sake of // brevity. var payment = new PaymentRequest(supportedInstruments, details, options); payment.addEventListener('shippingaddresschange', function(evt) { evt.updateWith(new Promise(function(resolve) { updateDetails(details, request.shippingAddress, resolve); })); }); payment.show
().then(function(paymentResponse) { // Processing of paymentResponse exerpted for brevity. }).catch(function(err) { console.error("Uh oh, something bad happened", err.message); }); function updateDetails(details, shippingAddress, resolve) { if (shippingAddress.country === 'US') { var shippingOption = { id: '', label: '', amount: {currency: 'USD', value: '0.00'}, ...
PaymentRequest.shippingOption - Web APIs
g was false (or missing), shippingOption returns null, even the developer provides a selected a shipping option. Syntax // Returns the id of the selected PaymentShippingOption var shippingOption = request.shippingOption; Example In the example below, the PaymentRequest.onshippingoptionchange and the PaymentRequest.onshippingaoptionchange events are dispatched. In each calls to updateDetails
() are made, one using a promise, and the other with a plain JS object. This demotrates synchrounous and asynchronous updates to a payment sheet. const request = new PaymentRequest(methodData, details, options); // Async update to details request.onshippingaddresschange = ev => { ev.updateWith(checkShipping(request)); }; // Sync update to the total request.onshippingoptionchange = ev => { con...
...we can't ship to your address.` }; } } Specifications Specification Status Comment Payment Request APIThe definition of 'shippingOption' in that specificat...
PaymentRequest - Web APIs
Properties PaymentRequest.id Read only Secure context An unique identifier for a particular PaymentRequest, which can be set via details.id. When none is set, it defaults to a UUID. ...
...he selected shipping option. This property is only populated if the constructor is called with the requestShipping flag set to true. PaymentRequest.shippingType Read only Secure context Returns the type of shipping used to fulfill the transaction. This will be one of shipping, delivery, pickup, or null if a value was not provided in the constructor. Methods PaymentRequest.canMakePayment
() Secure context Indicates whether the PaymentRequest object can make a payment before calling show
(). PaymentRequest.show
() Secure context Causes the user agent to begin the user interaction for the payment request. PaymentRequest.abort
() Secure context Causes the user agent to end the payment request and to remove any user interface that might be shown. Events merchantvalidation Secu...
PaymentRequestEvent - Web APIs
Properties instrumentKeyRead only Returns a PaymentInstrument object reflecting the payment instrument selected by the user or an empty string if the user has not registered or chosen a payment instrument. ...
...s to payment details. paymentRequestIdRead only Returns the ID of the PaymentRequest object. paymentRequestOriginRead only Returns the origin where the PaymentRequest object was initialized. topOriginRead only Returns the top-level origin where the PaymentRequest object was initialized. totalRead only Returns the total amount being requested for payment. Methods openWindow
() Opens the specified URL in a new window, if and only if the given URL is on the same origin as the calling page. It returns a Promise that resolves with a reference to a WindowClient. respondWith
() Prevents the default event handling and allows you to provide a Promise for a PaymentResponse object yourself. Specifications Specification Status Comment Payment Handle...
PaymentRequestUpdateEvent - Web APIs
se events are: shippingaddresschange Secure context Dispatched whenever the user changes their shipping address. Also available using the onshippingaddresschange event handler property. shippingoptionchange Secure context Dispatched whenever the user changes a shipping option. Also available using the onshippingoptionchange event handler property. ...
...nchange event handler property. Constructor PaymentRequestUpdateEvent
() Secure context Creates a new PaymentRequestUpdateEvent object. Properties Provides only the properties inherited from its parent interface, Event. Methods In addition to methods inherited from the parent interface, Event, PaymentRequestUpdateEvent offers the following methods: PaymentRequestUpdateEvent.updateWith
() Secure context If the event handler determines that information included in the payment request needs to be changed, or that new information needs to be added, it calls updateWith
() with the information that needs to be replaced or added. Specifications Specification Status Comment Payment Request APIThe definition of 'PaymentRequestUpdateEvent' in that specification. ...
PaymentResponse.details - Web APIs
transaction and determine a successful funds transfer. This data is returned by the payment app that satisfies the payment request, and must conform to the structure defined in the BasicCardResponse dictionary. Syntax var detailsObject = PaymentResponse.details; Example The following example extracts the details from the PaymentResponse object to the promise returned from PaymentRequest.show
(). ...
...that satisfies the payment request, and must conform to the structure defined in the BasicCardResponse dictionary. Syntax var detailsObject = PaymentResponse.details; Example The following example extracts the details from the PaymentResponse object to the promise returned from PaymentRequest.show
(). In a real-world implementation this data would then be sent to a payment server. ...
PaymentResponse.methodName - Web APIs
ring uniquely identifying the payment handler being used to process the payment. This may be either a standardized identifier, or a URL used by the payment processor to handle payments. See Merchant validation in Payment processing concepts for more information. Example The following example extracts the method name from the PaymentResponse object to the promise returned from PaymentRequest.show
(). ...
...r a standardized identifier, or a URL used by the payment processor to handle payments. See Merchant validation in Payment processing concepts for more information. Example The following example extracts the method name from the PaymentResponse object to the promise returned from PaymentRequest.show
(). In a real-world implementation this data would then be sent to a payment server. ...
PaymentResponse.shippingAddress - Web APIs
details comprising the shipping address provided by the user. Example Generally, the user agent will fill the shippingAddress property for you. You can trigger this by setting PaymentOptions.requestShipping to true when calling the PaymentRequest constructor. In the example below, the cost of shipping varies by geography. When the PaymentRequest.onshippingaddresschange is called, updateDetails
() is called to update the details of the PaymentRequest, using shippingAddress to set the correct shipping cost. // Initialization of PaymentRequest arguments are excerpted for brevity. var payment = new PaymentRequest(supportedInstruments, details, options); request.addEventListener('shippingaddresschange', function(evt) { evt.updateWith(new Promise(function(resolve) { updateDetails(detai...
...hippingAddress to set the correct shipping cost. // Initialization of PaymentRequest arguments are excerpted for brevity. var payment = new PaymentRequest(supportedInstruments, details, options); request.addEventListener('shippingaddresschange', function(evt) { evt.updateWith(new Promise(function(resolve) { updateDetails(details, request.shippingAddress, resolve); })); }); payment.show
().then(function(paymentResponse) { // Processing of paymentResponse exerpted for the same of brevity. }).catch(function(err) { console.error("Uh oh, something bad happened", err.message); }); function updateDetails(details, shippingAddress, resolve) { if (shippingAddress.country === 'US') { var shippingOption = { id: '', label: '', amount: {currency: 'USD', value: '0.00...
PaymentResponse.shippingOption - Web APIs
nterface returns the ID attribute of the shipping option selected by the user. This option is only present when the requestShipping option is set to true in the PaymentOptions object passed to the PaymentRequest constructor. Syntax var shippingOption = PaymentRequest.shippingOption; Example In the example below, the PaymentRequest.onshippingaoptionchange event is called. It calls updateDetails
() to toggle the shipping method between "standard" and "express". // Initialization of PaymentRequest arguments are excerpted for brevity. var payment = new PaymentRequest(supportedInstruments, details, options); request.addEventListener('shippingoptionchange', function(evt) { evt.updateWith(new Promise(function(resolve, reject) { updateDetails(details, request.shippingOption, resolve, reje...
...d between "standard" and "express". // Initialization of PaymentRequest arguments are excerpted for brevity. var payment = new PaymentRequest(supportedInstruments, details, options); request.addEventListener('shippingoptionchange', function(evt) { evt.updateWith(new Promise(function(resolve, reject) { updateDetails(details, request.shippingOption, resolve, reject); })); }); payment.show
().then(function(paymentResponse) { // Processing of paymentResponse exerpted for the same of brevity. }).catch(function(err) { console.error("Uh oh, something bad happened", err.message); }); function updateDetails(details, shippingOption, resolve, reject) { var selectedShippingOption; var otherShippingOption; if (shippingOption === 'standard') { selectedShippingOption = details.ship...
Performance: resourcetimingbufferfull event - Web APIs
Bubbles Yes Cancelable Yes Interface Event Event handler property onresourcetimingbufferfull Examples The following example sets a callback function on the onresourcetimingbufferfull property. ...
... Examples The following example sets a callback function on the onresourcetimingbufferfull property. function buffer_full(event) { console.log("WARNING: Resource Timing Buffer is FULL!"); performance.setResourceTimingBufferSize(200); } function init
() { // Set a callback if the resource buffer becomes filled performance.onresourcetimingbufferfull = buffer_full; } <body onload="init
()"> Note that you could also set up the handler using the addEventListener
() function: performance.addEventListener('resourcetimingbufferfull', buffer_full); Specifications Specification Status Comment Resource Timing Level 1The definition of 'onresourcetimingbufferfull' in that specification. Candidate Recommendation Initial definition. ...
PerformanceMark - Web APIs
PerformanceMark is an abstract interface for PerformanceEntry objects with an entryType of "mark". Entries of this type are created by calling performance.mark
() to add a named DOMHighResTimeStamp (the mark) to the browser's performance timeline. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/PerformanceEntry" target="_top"><rect x="1" y="1" width="160" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="81" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill...
...rk</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties This interface has no properties but it extends the following PerformanceEntry properties by qualifying/constraining the properties as follows: PerformanceEntry.entryType Returns "mark". PerformanceEntry.name Returns the name given to the mark when it was created via a call to performance.mark
(). PerformanceEntry.startTime Returns the DOMHighResTimeStamp when performance.mark
() was called. PerformanceEntry.duration Returns "0". (A mark has no duration.) Methods This interface has no methods. Example See the example in Using the User Timing API. Specifications Specification Status Comment User Timing Level 2The definition of 'PerformanceMark' in that spe...
PerformanceMeasure - Web APIs
PerformanceMeasure is an abstract interface for PerformanceEntry objects with an entryType of "measure". Entries of this type are created by calling performance.measure
() to add a named DOMHighResTimeStamp (the measure) between two marks to the browser's performance timeline. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/PerformanceEntry" target="_top"><rect x="1" y="1" width="160" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="81" y="30" font-size="12px" font-family="Consolas,Mona...
.../a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties This interface has no properties but it extends the following PerformanceEntry properties by qualifying/constrainting the properties as follows: PerformanceEntry.entryType Returns "measure". PerformanceEntry.name Returns the name given to the measure when it was created via a call to performance.measure
(). PerformanceEntry.startTime Returns a timestamp given to the measure when performance.measure
() was called. PerformanceEntry.duration Returns a DOMHighResTimeStamp that is the duration of the measure (typically, the measure's end mark timestamp minus its start mark timestamp). Methods This interface has no methods. Example See the example in Using the User Timing API. Specifications ...
RTCDtlsTransport.state - Web APIs
l state when DTLS has not started negotiating yet. connecting DTLS is in the process of negotiating a secure connection and verifying the remote fingerprint. connected DTLS has completed negotiation of a secure connection and verified the remote fingerprint. closed The transport has been closed intentionally as the result of receipt of a close_notify alert, or calling RTCPeerConnection.close
(). failed The transport has failed as the result of an error (such as receipt of an error alert or failure to validate the remote fingerprint). Examples This example presents a function, tallySenders
(), which iterates over an RTCPeerConnection's RTCRtpSenders, tallying up how many of them are in various states. The function returns an object containing properties whose values indicate how many...
...tates. The function returns an object containing properties whose values indicate how many of the senders are in each state. let pc = new RTCPeerConnection({ bundlePolicy: "max-bundle" }); /* ... ...
RTCErrorEvent.error - Web APIs
Any other error i...
...yAlertMessage("Data Channel Error", alertMessage); } else { terminateMyConnection
(); } }); If the error is an SDP syntax error--indicated by its errorDetail property being sdp-syntax-error--, a message string is constructed to present the error message and the line number within the SDP at which the error occurred. This message is then displayed using a function called showMyAlertMessage
(), which stands in for whatever output mechanism this code might use. Any other error is treated as terminal, causing a terminateMyConnection
() function to be called. The above example uses addEventListener
() to add the handler for error events. You can also use the RTCDataChannel object's onerror event handler property, like this: dataChannel.onerror = (event) => { let error = event.error; ...
RTCIceCandidate.candidate - Web APIs
The read-only property candidate on the RTCIceCandidate interface returns a DOMString describing the candidate in detail. Most of the other properties of RTCIceCandidate are actually extracted from this string. This property can be configured by specifying the value of the candidate property when constructing the new candidate object using RTCIceCandidate
(). Syntax var candidate = RTCIceCandidate.candidate; Value A DOMString describing the properties of the candidate, taken directly from the SDP attribute "candidate". The candidate string specifies the network connectivity information for the candidate. If the candidate is an empty string (""), the end of the candidate list has been reached; this candidate is known as the "end-of-candidates" marker. The syntax of the candidate string ...
...3 type = "host" Example In this example, we see a function which receives as input an SDP string containing an ICE candidate received from the remote peer during the signaling process. function handleNewIceCandidate(candidateSDP) { var candidateObj = new RTCIceCandidate(candidateSDP); myPeerConnection.addIceCandidate(candidateObj).catch({ /* handle the error thrown by addIceCandidate
() */ }); } The handleNewIceCandidate
() function shown here passes the received candidate's SDP text into RTCIceCandidate
() to receive an RTCIceCanddiate object in return, which represents the candidate. The new candidate is then passed into RTCPeerConnection.addIceCandidate
() to add the candidate to the list of candidates for WebRTC to consider using for the connection being established. This ...
RTCIceCandidate.port - Web APIs
address given by ip at which the candidate's peer can be reached. As is the case with most of RTCIceCandidate's properties, the value of port is extracted from the candidate a-line string specified when creating the RTCIceCandidate. The a-line string is obtained either from the RTCIceCandidateInit property candidate or from a-line string passed into the constructor upon using new RTCIceCandidate
(). ...
...This applies only if the candidate implements port. Usage notes Consider this SDP attribute line (a-line) which describes an ICE candidate: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host The port number is found in the sixth field, which is "44323". In this case, the value of port will be 44323. ...
RTCIceCandidate.priority - Web APIs
this value is, the better the remote peer considers the candidate to be. As is the case with most of RTCIceCandidate's properties, the value of priority is extracted from the candidate a-line string specified when creating the RTCIceCandidate. The a-line string is obtained either from the RTCIceCandidateInit property candidate or from an a-line string passed into RTCPeerConnection.addIceCandidate
() instead of an RTCIceCandidate. Syntax var priority = RTCIceCandidate.priority; Value A long, unsigned integer value indicating the priority of the candidate according to the remote peer. The larger this value is, the more preferable the remote peer considers this candidate to be. priority is initialized to null if it is not specified in the candidate, or if the candidate string can't be pars...
...Value A long, unsigned integer value indicating the priority of the candidate according to the remote peer. The larger this value is, the more preferable the remote peer considers this candidate to be. priority is initialized to null if it is not specified in the candidate, or if the candidate string can't be parsed propertly. Note: If priority is null, passing the candidate to addIceCandidate
() will fail, throwing an OperationError exception. This applies only if the candidate implements the priority property. Usage notes Consider this SDP attribute line (a-line) which describes an ICE candidate: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host The priority is the number after the protocol, so it's the fourth field in the candidate string. In this example, the pr...
RTCIceCandidate.protocol - Web APIs
The RTCIceCandidate interface's read-only protocol property is a string which indicates whether the candidate uses UDP or TCP as its transport protocol. protocol is null by default if not specified properly in the SDP, but this is an error condition and will result in a thrown exception when you call RTCPeerConnection.addIceCandidate
(). The protocol property's value is set when the RTCIceCandidate
() constructor is used. The value is automatically extracted from the candidate a-line, if it's formatted properly. Syntax var protocol = RTCIceCandidate.protocol; Value A DOMString which indicates what network protocol the candidate uses, UDP or TCP. These values are defined by the enumerated type RTCIceProtocol: tcp The candidate, if selected, would use TCP as the transport protocol for ...
.... The tcpType property provides additional information about the kind of TCP candidate represented by the object. udp The candidate will use the UDP transport protocol for its data. This is the preferred protocol for media interactions because of its better performance profile. Note: If protocol is null -- and protocol is supported by the user agent -- passing the candidate to addIceCandidate
() will fail, throwing an OperationError exception. Usage notes Here's an example candidate a-line from an ICE transaction: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host The third field, "udp", is the protocol type, indicating that the candidate would use the UDP transport protocol. Example This code snippet examines the value of protocol to decide if it should look at t...
RTCIceCandidate.sdpMLineIndex - Web APIs
The read-only sdpMLineIndex property on the RTCIceCandidate interface is a zero-based index of the m-line describing the media associated with the candidate. This value is specified when creating the RTCIceCandidate by setting the corresponding sdpMLineIndex value in the RTCIceCandidateInit object when creating a new candidate with new RTCIceCandidate
(). If you instead call RTCIceCandidate
() with a string parameter containing the candidate m-line text, the value of sdpMLineIndex is extracted from the m-line. Syntax var sdpMLineIndex = RTCIceCandidate.sdpMLineIndex; Value A number containing a 0-based index into the set of m-lines providing media descriptions, indicating which media source is associated with the candidate, or null if no such association is available. Note: Attempting...
...te m-line text, the value of sdpMLineIndex is extracted from the m-line. Syntax var sdpMLineIndex = RTCIceCandidate.sdpMLineIndex; Value A number containing a 0-based index into the set of m-lines providing media descriptions, indicating which media source is associated with the candidate, or null if no such association is available. Note: Attempting to add a candidate (using addIceCandidate
()) that has a value of null for either sdpMid or sdpMLineIndex will throw a TypeError exception. Example ... Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCIceCandidate.sdpMLineIndex' in that specification. Candidate Recommendation Initial definition. ...
RTCIceCandidate.sdpMid - Web APIs
TCIceCandidate interface returns a DOMString specifying the media stream identification tag of the media component with which the candidate is associated. This ID uniquely identifies a given stream for the component with which the candidate is associated. This property can be configured by specifying the value of the sdpMid property when constructing the new candidate object using RTCIceCandidate
(). If you call the constructor with an m-line string instead of an RTCIceCandidateInit object, the value of sdpMid is extracted from the specified candidate m-line string. Syntax var sdpMid = RTCIceCandidate.sdpMid; Value A DOMString which uniquely identifies the source media component from which the candidate draws data, or null if no such association exists for the candidate. Note: Attempti...
... string instead of an RTCIceCandidateInit object, the value of sdpMid is extracted from the specified candidate m-line string. Syntax var sdpMid = RTCIceCandidate.sdpMid; Value A DOMString which uniquely identifies the source media component from which the candidate draws data, or null if no such association exists for the candidate. Note: Attempting to add a candidate (using addIceCandidate
()) that has a value of null for either sdpMid or sdpMLineIndex will throw a TypeError exception. Example ... Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCIceCandidate.sdpMid' in that specification. Candidate Recommendation Initial definition. ...
RTCIceCandidate - Web APIs
ber of candidates are proposed by each end of the connection, until they mutually agree upon one which describes the connection they decide will be best. WebRTC then uses that candidate's details to initiate the connection. For details on how the ICE process works, see Lifetime of a WebRTC session. The article WebRTC connectivity provides additional useful details. Constructor RTCIceCandidate
() Creates an RTCIceCandidate object to represent a single ICE candidate, optionally configured based on an object based on the RTCIceCandidateInit dictionary. Note: For backward compatibility, the constructor also accepts as input a string containing the value of the candidate property instead of a RTCIceCandidateInit object, since the candidate includes all of the information that RTCIceCandidat...
...enumerated type. usernameFragment Read only A DOMString containing a randomly-generated username fragment ("ice-ufrag") which ICE uses for message integrity along with a randomly-generated password ("ice-pwd"). You can use this string to verify generations of ICE generation; each generation of the same ICE process will use the same usernameFragment, even across ICE restarts. Methods toJSON
() Given the RTCIceCandidate's current configuration, toJSON
() returns a DOMString containing a JSON representation of that configuration in the form of a RTCIceCandidateInit object. Examples For examples, see the article Signaling and video calling, which demonstrates the entire process. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Be...
RTCIceCandidateStats.deleted - Web APIs
e of true indicates that the candidate's network resources have been released. This generally mean sthat any associated socket(s) have been closed and released. Remote (TURN) candidate A value of true means the candidate's TURN allocation is no longer active. The net result is the same; the candidate is no longer under consideration if this value is true. ...
...eans the candidate's TURN allocation is no longer active. The net result is the same; the candidate is no longer under consideration if this value is true. Example In this example, setInterval
() is used to set up a function that runs periodically to display the latest statistics for candidates. Only candidates which have not been deleted are included in the output. ...
RTCIceCandidateStats.networkType - Web APIs
lects the initial connection between the local peer and the next hop along the network toward reaching the remote peer. For example, if the networkType is wifi but the user is connected using a cellular hotspot, the connection will be bottlenecked by the underlying cellular network (and any other networks between the two peers). ...
... networkType is wifi but the user is connected using a cellular hotspot, the connection will be bottlenecked by the underlying cellular network (and any other networks between the two peers). Example This example sets up a periodic function using setInterval
() that outputs statistics reports for candidates that use or would use a cellular data network to a log view. ...
RTCIceCandidateStats - Web APIs
ed with the candidate correspondin to these statistics. url Optional For local candidates, the url property is the URL of the ICE server from which the candidate was received. This URL matches the one included in the RTCPeerConnectionIceEvent object representing the icecandidate event that delivered the candidate to the local peer. Example This example features a function, isUsableNetworkType
(), whose job it is to look at an RTCIceCandidateStats object's networkType and determine whether or not the type of network is acceptable for use. This function is then called for RTCStats objects whose type is local-candidate, indicating that the object is in fact an RTCIceCandidateStats with information about a local ICE candidate. const isUsableNetworkType = stats => { switch(stats.networkTy...
...ormation about a local ICE candidate. const isUsableNetworkType = stats => { switch(stats.networkType) { case "ethernet": case "vpn": return true; case "bluetooth": case "cellular": case "wimax": case "unknown": default: return false; } } if (rtcStats && rtcStats.type === "local-candidate") { if (!isUsableNetworkType(rtcStats)) { abortConnection
(); return; } } This code calls a function called abortConnection
() if the RTCStats object represents information about a local candidate is which would be using a network connection other than Ethernet or a VPN. Specifications Specification Status Comment Identifiers for WebRTC's Statistics APIThe definition of 'RTCIceCandidateStats' in that specification. C...
RTCIceParameters - Web APIs
Properties usernameFragment A DOMString specifying the value of the ICE session's username fragment field, ufrag. ...
... Properties usernameFragment A DOMString specifying the value of the ICE session's username fragment field, ufrag. ...
RTCIceTransport: selectedcandidatepairchange event - Web APIs
nformation about the progress of the ICE negotiation for an RTCPeerConnection called pc. let iceTransport = pc.getSenders[0].transport.iceTransport; let localProtoElem = document.getElementById("local-protocol"); let remoteProtoElem = document.getElementById("remote-protocol"); iceTransport.addEventListener("selectedcandidatepairchange", ev => { let pair = iceTransport.getSelectedCandidatePair
(); localProtoElem.innerText = pair.local.protocol.toUpperCase
(); remoteProtoElem.innerText = pair.remote.protocol.toUpperCase
(); }, false) This can also be done by setting the onselectedcandidatepairchange event handler property directly. let iceTransport = pc.getSenders[0].transport.iceTransport; let localProtoElem = document.getElementById("local-protocol"); let remoteProtoElem = document.g...
...se) This can also be done by setting the onselectedcandidatepairchange event handler property directly. let iceTransport = pc.getSenders[0].transport.iceTransport; let localProtoElem = document.getElementById("local-protocol"); let remoteProtoElem = document.getElementById("remote-protocol"); iceTransport.onselectedcandidatepairchange = ev => { let pair = iceTransport.getSelectedCandidatePair
(); localProtoElem.innerText = pair.local.protocol.toUpperCase
(); remoteProtoElem.innerText = pair.remote.protocol.toUpperCase
(); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'selectedcandidatepairchange' in that specification. Candidate Recommendation ...
RTCInboundRtpStreamStats - Web APIs
value containing the sum of the QP values for every frame decoded by this RTP receiver. You can determine the average QP per frame by dividing this value by framesDecoded. Valid only for video streams. receiverId A string indicating which identifies the RTCAudioReceiverStats or RTCVideoReceiverStats object associated with the stream's receiver. This ID is stable across multiple calls to getStats
(). remoteId A string which identifies the RTCRemoteOutboundRtpStreamStats object that provides statistics for the remote peer for this same SSRC. This ID is stable across multiple calls to getStats
(). sliCount An integer indicating the number of times the receiver sent a Slice Loss Indication (SLI) frame to the sender to tell it that one or more consecutive (in terms of scan order) video macrob...
...to tell it that one or more consecutive (in terms of scan order) video macroblocks have been lost or corrupted. Available only for video streams. trackId A string which identifies the statistics object representing the receiving track; this object is one of two types: RTCReceiverAudioTrackAttachmentStats or RTCReceiverVideoTrackAttachmentStats. This ID is stable across multiple calls to getStats
(). Examples Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCInboundRtpStreamStats' in that specification. Candidate Recommendation Initial specification. ...
RTCOfferOptions - Web APIs
This is useful if network conditions have changed in a way that make the current configuration untenable or impractical, for instance. ...
...This is useful if network conditions have changed in a way that make the current configuration untenable or impractical, for instance. ...
RTCPeerConnection: addstream event - Web APIs
ermine if the user's browser supports the track event. If it does, a track event listener is set up; otherwise, an addstream event listener is set up. pc is an RTCPeerConnection. ...
...RTCPeerConnection. ...
RTCPeerConnection: connectionstatechange event - Web APIs
eerConnectionState enumerated type. Bubbles No Cancelable No Interface Event Event handler onconnectionstatechange Examples For an RTCPeerConnection, pc, this example sets up a handler for connectionstatechange messages to handle changes to the connectivity of the WebRTC session. It simply calls an app-defined function called setOnlineStatus
() to update a status display. pc.onconnectionstatechange = ev => { switch(pc.connectionState) { case "new": case "checking": setOnlineStatus("Connecting..."); break; case "connected": setOnlineStatus("Online"); break; case "disconnected": setOnlineStatus("Disconnecting..."); break; case "closed": setOnlineStatus("Offline"); brea...
...*/ } }, false); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'connectionstatechange' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection.currentLocalDescription - Web APIs
s most recently successfully negotiated since the last time the RTCPeerConnection finished negotiating and connecting to a remote peer. Also included is a list of any ICE candidates that may already have been generated by the ICE agent since the offer or answer represented by the description was first instantiated. To change the currentLocalDescription, call RTCPeerConnection.setLocalDescription
(), which triggers a series of events which leads to this value being set. For details on what exactly happens and why the change isn't necessarily instantaneous, see Pending and current descriptions in WebRTC connectivity. Unlike RTCPeerConnection.localDescription, this value represents the actual current state of the local end of the connection; localDescription may specify a description which t...
...tax sessionDescription = RTCPeerConnection.currentLocalDescription; Return value The current description of the local end of the connection, if one has been set. If none has been successfully set, this value is null. Example This example looks at the currentLocalDescription and displays an alert containing the RTCSessionDescription object's type and sdp fields. var pc = new RTCPeerConnection
(); ... var sd = pc.currentLocalDescription; if (sd) { alert("Local session: type='" + sd.type + "'; sdp description='" + sd.sdp + "'"); } else { alert("No local session yet."); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.currentLocalDescription' in that speci...
RTCPeerConnection.currentRemoteDescription - Web APIs
most recently successfully negotiated since the last time the RTCPeerConnection finished negotiating and connecting to a remote peer. Also included is a list of any ICE candidates that may already have been generated by the ICE agent since the offer or answer represented by the description was first instantiated. To change the currentRemoteDescription, call RTCPeerConnection.setRemoteDescription
(), which triggers a series of events which leads to this value being set. For details on what exactly happens and why the change isn't necessarily instantaneous, see Pending and current descriptions in WebRTC connectivity. Unlike RTCPeerConnection.remoteDescription, this value represents the actual current state of the local end of the connection; remoteDescription may specify a description which...
... sessionDescription = RTCPeerConnection.currentRemoteDescription; Return value The current description of the remote end of the connection, if one has been set. If none has been successfully set, this value is null. Example This example looks at the currentRemoteDescription and displays an alert containing the RTCSessionDescription object's type and sdp fields. var pc = new RTCPeerConnection
(); ... var sd = pc.currentRemoteDescription; if (sd) { alert("Local session: type='" + sd.type + "'; sdp description='" + sd.sdp + "'"); } else { alert("No local session yet."); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.currentRemoteDescription' in that spe...
RTCPeerConnection.iceConnectionState - Web APIs
RTCIceConnectionState enum The RTCIceConnectionState enum defines the string constants used to describe the current state of the ICE agent and its connection to the ICE server (that is, the STUN or TURN server). Constant Description "new" The ICE agent is gathering addresses or is waiting to be given remote candidates through calls to RTCPeerConnection.addIceCandidate
() (or both). "checking" The ICE agent has been given one or more remote candidates and is checking pairs of local and remote candidates against one another to try to find a compatible match, but has not yet found a pair which will allow the peer connection to be made. It's possible that gathering of candidates is also still underway. "connected" A usable pairing of local and...
... less stringent test than "failed" and may trigger intermittently and resolve just as spontaneously on less reliable networks, or during temporary disconnections. When the problem resolves, the connection may return to the "connected" state. "closed" The ICE agent for this RTCPeerConnection has shut down and is no longer handling requests. Example var pc = new RTCPeerConnection
(); var state = pc.iceConnectionState; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.iceConnectionState' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection.ondatachannel - Web APIs
At the time this event is received, the RTCDataChannel it indicates may not yet actually be open. ...
...Channel before using it. Syntax RTCPeerConnection.ondatachannel = function; Value Set this property to be a function you provide which receives as input a single parameter: an RTCDataChannelEvent which provides in its channel property the RTCDataChannel which has been created. Example pc.ondatachannel = function(ev) { console.log('Data channel is created!'); ev.channel.onopen = function
() { console.log('Data channel is open and ready to be used.'); }; }; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.ondatachannel' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection.remoteDescription - Web APIs
ionDescription describing the session (which includes configuration and media information) for the remote end of the connection. If this hasn't been set yet, this is null. The returned value typically reflects a remote description which has been received over the signaling server (as either an offer or an answer) and then put into effect by your code calling RTCPeerConnection.setRemoteDescription
() in response. Syntax var sessionDescription = peerConnection.remoteDescription; On a more fundamental level, the returned value is the value of RTCPeerConnection.pendingRemoteDescription if that property isn't null; otherwise, the value of RTCPeerConnection.currentRemoteDescription is returned. See Pending and current descriptions in WebRTC connectivity for details on this algorithm and why it...
...ription if that property isn't null; otherwise, the value of RTCPeerConnection.currentRemoteDescription is returned. See Pending and current descriptions in WebRTC connectivity for details on this algorithm and why it's used. Example This example looks at the remoteDescription and displays an alert containing the RTCSessionDescription object's type and sdp fields. var pc = new RTCPeerConnection
(); ... var sd = pc.remoteDescription; if (sd) { alert("Remote session: type='" + sd.type + "'; sdp description='" + sd.sdp + "'"); } else { alert("No remote session yet."); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.remoteDescription' in that specification. ...
RTCRtpCapabilities - Web APIs
An RTCRtpCapabilities object contains an array of objects conforming to RTCRtpCodecCapability (each describing the capabilities of one codec) and an array of the supported RTP header extensions for that codec. ...
... An RTCRtpCapabilities object contains an array of objects conforming to RTCRtpCodecCapability (each describing the capabilities of one codec) and an array of the supported RTP header extensions for that codec. ...
RTCRtpParameters - Web APIs
The RTCRtpParameters dictionary is the basic object describing the parameters of an RTP transport. It is extended separately for senders and receivers in the form of the RTCRtpSendParameters and RTCRtpReceiveParameters dictionaries. To obtain the parameters of a sender or receiver, call its getParameters
() method: getParameters
() getParameters
() Properties codecs An array of RTCRtpCodecParameters objects describing the set of codecs from which the sender or receiver will choose. This parameter cannot be changed once initially set. headerExtensions An array of zero or more RTP header extensions, each identifying an extension supported by the sender or receiver. Header extensions are described in RFC 3550: 5.3.1. This parameter cannot be changed once initially set. rtcp An RTCR...
...annot be changed once initially set. rtcp An RTCRtcpParameters object providing the configuration parameters used for RTCP on the sender or receiver. This parameter cannot be changed once initially set. Examples This example obtains the canonical name (CNAME) being used for RTCP on an RTCRtpSender or RTCRtpReceiver. function getRtpCNAME(rtpObject) { let parameters = rtpObject.getParameters
(); return parameters.rtcp.cname; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpReceiveParameters' in that specification. Candidate Recommendation Initial definition. ...
RTCRtpReceiveParameters - Web APIs
The RTCRtpReceiveParameters dictionary, based upon the RTCRtpParameters dictionary, is returned by the the RTCRtpReceiver method getParameters
(). It describes the parameters being used by the receiver's RTP connection to the remote peer. Properties This dictionary currently has no properties of its own; it exists for future expansion. It inherits all of the properties of its parent, RTCRtpParameters. Examples This example obtains the canonical name (CNAME) being used for RTCP on an RTCRtpReceiver. ...
... by the receiver's RTP connection to the remote peer. Properties This dictionary currently has no properties of its own; it exists for future expansion. It inherits all of the properties of its parent, RTCRtpParameters. Examples This example obtains the canonical name (CNAME) being used for RTCP on an RTCRtpReceiver. function getRtcpCNAME(receiver) { let parameters = receiver.getParameters
(); return parameters.rtcp.cname; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpReceiveParameters' in that specification. Candidate Recommendation Initial definition. ...
RTCRtpSendParameters - Web APIs
Properties In addition to the properties below, RTCRtpSendParameters inherits the properties from the RTCRtpParameters interface. degradationPreference Specifies the preferred way the WebRTC layer should handle optimizing bandwidth against quality in constrained-bandwidth situations; the value comes from the RTCDegradationPreference enumerated string type, and the default is balanced. ...
...y of RTCRtpEncodingParameters objects, each specifying the parameters for a single codec that could be used to encode the track's media. priority A string from the RTCPriorityType enumerated type which indicates the encoding's priority. The default value is low. transactionId A string containing a unique ID for the last set of parameters applied; this value is used to ensure that setParameters
() can only be called to alter changes made by a specific previous call to getParameters
(). Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpSendParameters' in that specification. Candidate Recommendation Initial definition. ...
RTCRtpTransceiver.direction - Web APIs
Does not offer to send RTP data, and will not do so. Offers to receive RTP data, and will do so if the other peer offers. "inactive" Does not offer to send RTP data, and will not do so. Does not offer to receive RTP data and will not do so. [1] To determine if a sender has at least one active encoding, the user agent gets its parameters using RTCRtpSender.getParameters
(), then looks at the parameters' encodings property; if any of the listed encodings has its active property set to true, the sender has an active encoding. Exceptions When setting the value of direction, the following exceptions can occur: InvalidStateError Either the receiver's RTCPeerConnection is closed or the RTCRtpReceiver is stopped. Usage notes Setting the direction When you change...
...he value of direction, an InvalidStateError exception will occur if the connection is closed or the receiver is stopped. If the new value of direction is in fact different from the existing value, renegotiation of the connection is required, so a negotiationneeded event is sent to the RTCPeerConnection. Effect on offers and answers The value of direction is used by RTCPeerConnection.createOffer
() or RTCPeerConnection.createAnswer
() in order to generate the SDP generated by each of those methods. The SDP contains an a-line which specifies the directionality. For example, if the direction is specified as "sendrecv", the corresponding SDP a-line is: a=sendrecv Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe defini...
RTCStatsReport - Web APIs
The RTCStatsReport interface provides a statistics report obtained by calling one of the RTCPeerConnection.getStats
(), RTCRtpReceiver.getStats
(), and RTCRtpSender.getStats
() methods. This statistics report contains a mapping of statistic category string names to objects containing the corresponding statistics data. Calling getStats
() on an RTCPeerConnection lets you specify whether you wish to obtain statistics for outbound, inbound, or all streams on the connection. The RTCRtpReceiver and RTCRtpSender versions of getStats
() specifically only return statistics available to the incoming or outgoing stream on which you call them. The statistics objects For each category of statistic information, there is a dictionary whose properties provide the relevant information. Properties common t...
...tistics related to inbound data, without considering the local peer's state, any values that require knowledge of both, such as round-trip time, is not included. This report isn't available if there are no connected peers. local-candidate An RTCIceCandidateStats object giving statistics about an ICE local candidate; these candidates are found in the output from RTCIceTransport.getLocalCandidates
(). outbound-rtp The report is an RTCOutboundRtpStreamStats object providing statistics based on the local peer's outgoing data being sent to its peers. This information considers only the outbound RTP stream, so any data which requires information about the state of the remote peers (such as round-trip time) is unavailable, since those values can't be computed without knowing about the other peer...
RTCTrackEvent - Web APIs
ckEvent represents the track event, which is sent when a new MediaStreamTrack is added to an RTCRtpReceiver which is part of the RTCPeerConnection. The target is the RTCPeerConnection object to which the track is being added. This event is sent by the WebRTC layer to the web site or application, so you will not typically need to instantiate an RTCTrackEvent yourself. Constructor RTCTrackEvent
() Creates and returns a new RTCTrackEvent object, initialized with properties taken from the specified RTCTrackEventInit dictionary. You will probably not need to create new track events yourself, since they're typically created by the WebRTC infrastructure and sent to the connection's ontrack event handler. Properties Since RTCTrackEvent is based on Event, its properties are also available. ...
...operty). In addition, the MediaStreamTrack specified by the receiver's track is the same one specified by the event's track, and the track has been added to any associated remote MediaStream objects. You can add a track event listener to be notified when the new track is available so that you can, for example, attach its media to a <video> element, using either RTCPeerConnection.addEventListener
() or the ontrack event handler property. Note: It may be helpful to keep in mind that you receive the track event when a new inbound track has been added to your connection, and you call addTrack
() to add a track to the far end of the connection, thereby triggering a track event on the remote peer. Example This simple example creates an event listener for the track event which sets the srcObje...
Request.headers - Web APIs
The headers read-only property of the Request interface contains the Headers object associated with the request. Syntax var myHeaders = request.headers; Value A Headers object. ...
...) constructor (for an image file in the same directory as the script), then save the request headers in a variable: var myRequest = new Request('flowers.jpg'); var myHeaders = myRequest.headers; // Headers {} To add a header to the Headers object we use Headers.append; we then create a new Request along with a 2nd init parameter, passing headers in as an init option: var myHeaders = new Headers
(); myHeaders.append('Content-Type', 'image/jpeg'); var myInit = { method: 'GET', headers: myHeaders, mode: 'cors', cache: 'default' }; var myRequest = new Request('flowers.jpg', myInit); myContentType = myRequest.headers.get('Content-Type'); // returns 'image/jpeg' Specifications Specification Status Comment FetchThe definition of 'headers' in that specification...
Response.headers - Web APIs
The headers read-only property of the Response interface contains the Headers object associated with the response. Syntax var myHeaders = response.headers; Value A Headers object. Example In our Fetch Response example (see Fetch Response live) we create a new Request object using the Request
() constructor, passing it a JPG path. We then fetch this request using fetch
(), extract a blob from the response using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch
() block we log the response headers value to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.headers); // returns a Headers{} ...
...blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch
() block we log the response headers value to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.headers); // returns a Headers{} object response.blob
().then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); }); Specifications Specification Status Comment FetchThe definition of 'headers' in that specification. Living Standard Initial definition ...
Response.ok - Web APIs
The ok read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. Syntax var myOK = response.ok; Value A Boolean. Example In our Fetch Response example (see Fetch Response live) we create a new Request object using the Request
() constructor, passing it a JPG path. We then fetch this request using fetch
(), extract a blob from the response using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note: at the top of the fetch
() block we log the response ok value to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.ok); // returns tru...
... an object URL out of it using URL.createObjectURL, and display this in an <img>. Note: at the top of the fetch
() block we log the response ok value to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.ok); // returns true if the response returned successfully response.blob
().then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); }); Specifications Specification Status Comment FetchThe definition of 'ok' in that specification. Living Standard Initial definition ...
Response.status - Web APIs
The status read-only property of the Response interface contains the status code of the response (e.g., 200 for a success). Syntax var myStatus = response.status; Value A number (to be precise, an unsigned short). Example In our Fetch Response example (see Fetch Response live) we create a new Request object using the Request
() constructor, passing it a JPG path. We then fetch this request using fetch
(), extract a blob from the response using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch
() block we log the response status value to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.
...ponse using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch
() block we log the response status value to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.status); // returns 200 response.blob
().then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); }); Specifications Specification Status Comment FetchThe definition of 'status' in that specification. Living Standard Initial definition ...
Response.statusText - Web APIs
The statusText read-only property of the Response interface contains the status message corresponding to the status code (e.g., OK for 200). Syntax var myStatusText = response.statusText; Value A ByteString. The default value is "". Example In our Fetch Response example (see Fetch Response live) we create a new Request object using the Request
() constructor, passing it a JPG path. We then fetch this request using fetch
(), extract a blob from the response using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch
() block we log the response statusText value to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) {...
... of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch
() block we log the response statusText value to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.statusText); // returns "OK" if the response returned successfully response.blob
().then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); }); Specifications Specification Status Comment FetchThe definition of 'statusText' in that specification. Living Standard Initial definition ...
Response.url - Web APIs
The url read-only property of the Response interface contains the URL of the response. The value of the url property will be the final URL obtained after any redirects. Syntax var myURL = response.url; Value A USVString. Example In our Fetch Response example (see Fetch Response live) we create a new Request object using the Request
() constructor, passing it a JPG path. We then fetch this request using fetch
(), extract a blob from the response using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch
() block we log the response URL to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.u...
...ob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch
() block we log the response URL to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.url); // returns /docs/Web/API/Response/flowers.jpg response.blob
().then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); }); Specifications Specification Status Comment FetchThe definition of 'url' in that specification. Living Standard Initial definition ...
RsaHashedKeyGenParams - Web APIs
Properties name A DOMString. This should be set to RSASSA-PKCS1-v1_5, RSA-PSS, or RSA-OAEP, depending on the algorithm you want to use. modulusLength A Number. The length in bits of the RSA modulus. This should be at least 2048: see for example see NIST SP 800-131A Rev. 1. Some organizations are now recommending that it should be 4096. ...
...od reason to use something else, specify 65537 here ([0x01, 0x00, 0x01]). hash A DOMString representing the name of the digest function to use. You can pass any of SHA-256, SHA-384, or SHA-512 here. Warning: Although you can technically pass SHA-1 as a value here, this is strongly discouraged as SHA-1 is considered vulnerable. Examples See the examples for SubtleCrypto.generateKey
(). Specifications Specification Status Comment Web Cryptography APIThe definition of 'SubtleCrypto.RsaHashedKeyGenParams' in that specification. Recommendation ...
RsaPssParams - Web APIs
Properties name A DOMString. This should be set to RSA-PSS. saltLength A long integer representing the length of the random salt to use, in bytes. RFC 3447 says that "Typical salt lengths" are either 0 or the length of the output of the digest algorithm that was selected when this key was generated. For example, if you use SHA-256 as the digest algorithm, this could be 32. ...
...digest algorithm that was selected when this key was generated. For example, if you use SHA-256 as the digest algorithm, this could be 32. The maximum size of saltLength is given by: Math.ceil((keySizeInBits - 1)/8) - digestSizeInBytes - 2 So for a key length of 2048 bits and a digest output size of 32 bytes, the maximum size would be 222. Examples See the examples for SubtleCrypto.sign
() and SubtleCrypto.verify
(). Specifications Specification Status Comment Web Cryptography APIThe definition of 'SubtleCrypto.RsaPssParams' in that specification. Recommendation ...
SVGAnimationElement: beginEvent event - Web APIs
ion path="M 0 0 H 300 Z" dur="5s" repeatCount="indefinite" /> </circle> </svg> <hr> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgElem = document.querySelector('svg'); let animateElem = document.querySelector('animateMotion'); let list = document.querySelector('ul'); animateElem.addEventListener('beginEvent',
() => { let listItem = document.createElement('li'); listItem.textContent = 'beginEvent fired'; list.appendChild(listItem); }) animateElem.addEventListener('repeatEvent', (e) => { let listItem = document.createElement('li'); let msg = 'repeatEvent fired'; if(e.detail) { msg += '; repeat number: ' + e.detail; } listItem.textContent = msg; list.appendChild(listItem); }) Even...
... Candidate Recommendation Initial definition ...
SVGAnimationElement: endEvent event - Web APIs
</circle> </svg> <hr> <button>Stop animation</button> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgElem = document.querySelector('svg'); let animateElem = document.querySelector('animateMotion'); let list = document.querySelector('ul'); let btn = document.querySelector('button'); animateElem.addEventListener('beginEvent',
() => { let listItem = document.createElement('li'); listItem.textContent = 'beginEvent fired'; list.appendChild(listItem); }) animateElem.addEventListener('endEvent',
() => { let listItem = document.createElement('li'); listItem.textContent = 'endEvent fired'; list.appendChild(listItem); }) animateElem.addEventListener('repeatEvent', (e) => { let listItem = document.createElement('l...
...= document.createElement('li'); listItem.textContent = 'endEvent fired'; list.appendChild(listItem); }) animateElem.addEventListener('repeatEvent', (e) => { let listItem = document.createElement('li'); let msg = 'repeatEvent fired'; if(e.detail) { msg += '; repeat number: ' + e.detail; } listItem.textContent = msg; list.appendChild(listItem); }) btn.addEventListener('click',
() => { btn.disabled = true; animateElem.setAttribute('repeatCount', '1'); }) Event handler property equivalent Note that you can also create an event listener for the end event using the onend event handler property: animateElem.onend =
() => { console.log('endEvent fired'); } Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The defini...
SVGAnimationElement: repeatEvent event - Web APIs
tion path="M 0 0 H 300 Z" dur="5s" repeatCount="indefinite" /> </circle> </svg> <hr> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgElem = document.querySelector('svg'); let animateElem = document.querySelector('animateMotion'); let list = document.querySelector('ul'); animateElem.addEventListener('beginEvent',
() => { let listItem = document.createElement('li'); listItem.textContent = 'beginEvent fired'; list.appendChild(listItem); }) animateElem.addEventListener('repeatEvent', (e) => { let listItem = document.createElement('li'); let msg = 'repeatEvent fired'; if(e.detail) { msg += '; repeat number: ' + e.detail; } listItem.textContent = msg; list.appendChild(listItem); }) Even...
... Candidate Recommendation Initial definition ...
SVGEllipseElement - Web APIs
erty returns a SVGAnimatedLength reflecting the ry attribute of the given <ellipse> element. Methods This interface doesn't implement any specific methods, but inherits methods from its parent interface, SVGGeometryElement. ...
...ribute of the given <ellipse> element. Methods This interface doesn't implement any specific methods, but inherits methods from its parent interface, SVGGeometryElement. ...
getTrackById - Web APIs
This lets you find a specified track if you know its ID string. Syntax var theTrack = VideoTrackList.getTrackById(id); Paramters id A DOMString indicating the ID of the track to locate within the track list. Return value A VideoTrack object indicating the first track found within the VideoTrackList whose id matches the specified string. If no match is found, this method returns null. The tracks are searched in their natural order; that is, in the order defined by the media resource itself, or, if the resource doesn't define an order, the relative order in which the tracks are declared by the media resource. ...
...und, this method returns null. The tracks are searched in their natural order; that is, in the order defined by the media resource itself, or, if the resource doesn't define an order, the relative order in which the tracks are declared by the media resource. Specifications Specification Status Comment HTML Living StandardThe definition of 'VideoTrackList.getTrackById
()' in that specification. Living Standard ...
VideoTrackList.onaddtrack - Web APIs
an event handler which is called when the addtrack event occurs, indicating that a new video track has been added to the media element whose video tracks the VideoTrackList represents. The event is passed into the event handler in the form of a TrackEvent object, whose track property identifies the newly-added track. Note: You can also add a handler for the addtrack event using addEventListener
(). Syntax VideoTrackList.onaddtrack = eventHandler; Value Set onaddtrack to a function that accepts as input a TrackEvent object which indicates in its track property which video track has been added to the media. Usage notes The addtrack event is called whenever a new track is added to the media element whose video tracks are represented by the VideoTrackList object. This happens when track...
...alled whenever a new track is added to the media element whose video tracks are represented by the VideoTrackList object. This happens when tracks are added to the element when the media is first attached to the element; one addtrack event will occur for each video track in the media resource. Example This snippet establishes a handler for the addtrack event that calls a function, addToTrackList
(), passing in the VideoTrack object representing the newly-added track. In this scenario, that function's role is to add the new track to a list of video tracks available to choose from. document.querySelector("video").videoTracks.onaddtrack = function(event) { addToTrackList(event.track); }; Specifications Specification Status Comment HTML Living StandardThe defin...
VideoTrackList.onchange - Web APIs
ge event occurs, indicating that a VideoTrack in the VideoTrackList has been made active. The event is passed into the event handler in the form of an Event object; the event doesn't provide any additional information. To determine the new state of media's tracks, you'll have to look at their VideoTrack.selected flags. Note: You can also add a handler for the change event using addEventListener
(). Syntax VideoTrackList.onchange = eventHandler; Value Set onchange to a function that should be called whenever a track is made active. Example This snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track. var trackList = document.queryS...
...nt that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track. var trackList = document.querySelector("video").videoTracks; trackList.onchange = function(event) { trackList.forEach(function(track) { updateTrackSelectedButton(track.id, track.selected); }); }; The updateTrackSelectedButton
(), in this example, should be a function that finds a user interface control using the track's id (perhaps the app uses the track ID as the control element's ID) and the track's selected flag to determine which state the control should be in now. Specifications Specification Status Comment HTML Living StandardThe definition of 'VideoTrackList: onchange' in that specifi...
VideoTrackList - Web APIs
Properties This interface also inherits properties from its parent interface, EventTarget. ...
...the change event occurs -- that is, when the value of the selected property for a track has changed, due to the track being made active or inactive. onremovetrack An event handler to call when the removetrack event is sent, indicating that a video track has been removed from the media element. Methods This interface also inherits methods from its parent interface, EventTarget. getTrackById
() Returns the VideoTrack found within the VideoTrackList whose id matches the specified string. If no match is found, null is returned. Events addtrack Fired when a new video track has been added to the media element. Also available via the onaddtrack property. change Fired when a video track has been made active or inactive. Also available via the onchange property. removetrack Fired ...
WEBGL_color_buffer_float - Web APIs
For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is available to WebGL 1 contexts only. For WebGL 2, use the EXT_color_buffer_float extension. The OES_texture_float extension implicitly enables this extension. Constants ext.RGBA32F_EXT RGBA 32-bit floating-point color-renderable format. ...
...xtension. The OES_texture_float extension implicitly enables this extension. Constants ext.RGBA32F_EXT RGBA 32-bit floating-point color-renderable format. ext.RGB32F_EXT ( ) RGB 32-bit floating-point color-renderable format. ext.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT ? ext.UNSIGNED_NORMALIZED_EXT ? Extended methods This extension extends WebGLRenderingContext.renderbufferStorage
(): The internalformat parameter now accepts ext.RGBA32F_EXT and ext.RGB32F_EXT ( ). Examples var ext = gl.getExtension('WEBGL_color_buffer_float'); gl.renderbufferStorage(gl.RENDERBUFFER, ext.RBGA32F_EXT, 256, 256); Specifications Specification Status Comment WEBGL_color_buffer_floatThe definition of 'WEBGL_color_buffer_float' in that specification. Recommendati...
WEBGL_compressed_texture_etc - Web APIs
The WEBGL_compressed_texture_etc extension is part of the WebGL API and exposes 10 ETC/EAC compressed texture formats. Compressed textures reduce the amount of memory needed to store a texture on the GPU, allowing for higher resolution textures or more of the same resolution textures. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is available to both, WebGL1 and WebGL2 contexts. Constants The compressed texture formats are exposed by 10 constants and can be used in two functions: compressedTexImage2D
() and compressedTexSubImage2D
(). ext.COMPRESSED_R11_EAC One-channel (red) unsigned format compression. ext.COMPRESSED_SIGNED_R11_EAC One-chann...
...B8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent. ext.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 Similar to SRGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent. Examples var ext = gl.getExtension('WEBGL_compressed_texture_etc'); var texture = gl.createTexture
(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.compressedTexImage2D(gl.TEXTURE_2D, 0, ext.COMPRESSED_RGBA8_ETC2_EAC, 512, 512, 0, textureData); Specifications Specification Status Comment WEBGL_compressed_texture_etcThe definition of 'WEBGL_compressed_texture_etc' in that specification. Draft Initial definition. ...
WEBGL_compressed_texture_etc1 - Web APIs
The WEBGL_compressed_texture_etc1 extension is part of the WebGL API and exposes the ETC1 compressed texture format. Compressed textures reduce the amount of memory needed to store a texture on the GPU, allowing for higher resolution textures or more of the same resolution textures. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is available to both, WebGL1 and WebGL2 contexts. Constants The compressed texture format is exposed by a constant and can be used with the compressedTexImage2D
() method (note that ETC1 is not supported with the compressedTexSubImage2D
() method). ext.COMPRESSED_RGB_ETC1_WEBGL Compresses 24-bit RGB data with no alpha ch...
...L2 contexts. Constants The compressed texture format is exposed by a constant and can be used with the compressedTexImage2D
() method (note that ETC1 is not supported with the compressedTexSubImage2D
() method). ext.COMPRESSED_RGB_ETC1_WEBGL Compresses 24-bit RGB data with no alpha channel. Examples var ext = gl.getExtension('WEBGL_compressed_texture_etc1'); var texture = gl.createTexture
(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.compressedTexImage2D(gl.TEXTURE_2D, 0, ext.COMPRESSED_RGB_ETC1_WEBGL, 512, 512, 0, textureData); Specifications Specification Status Comment WEBGL_compressed_texture_etc1The definition of 'WEBGL_compressed_texture_etc1' in that specification. Draft Initial definition. ...
WEBGL_compressed_texture_s3tc - Web APIs
The WEBGL_compressed_texture_s3tc extension is part of the WebGL API and exposes four S3TC compressed texture formats. Compressed textures reduce the amount of memory needed to store a texture on the GPU, allowing for higher resolution textures or more of the same resolution textures. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is available to both, WebGL1 and WebGL2 contexts. Constants The compressed texture formats are exposed by four constants and can be used in two functions: compressedTexImage2D
() and compressedTexSubImage2D
(). ext.COMPRESSED_RGB_S3TC_DXT1_EXT A DXT1-compressed image in an RGB image format. ext.COMPRESSED_RGBA_S3TC_DX...
...TC_DXT5_EXT A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3 compression in how the alpha compression is done. ...
WEBGL_compressed_texture_s3tc_srgb - Web APIs
The WEBGL_compressed_texture_s3tc_srgb extension is part of the WebGL API and exposes four S3TC compressed texture formats for the sRGB colorspace. Compressed textures reduce the amount of memory needed to store a texture on the GPU, allowing for higher resolution textures or more of the same resolution textures. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is available to both WebGL1 and WebGL2 contexts. Constants The compressed texture formats are exposed by four constants and can be used in two functions: compressedTexImage2D
() and compressedTexSubImage2D
(). ext.COMPRESSED_SRGB_S3TC_DXT1_EXT A DXT1-compressed image in an sRGB image format...
...SRGB_ALPHA_S3TC_DXT1_EXT A DXT1-compressed image in an sRGB image format with a simple on/off alpha value. ext.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT A DXT3-compressed image in an sRGBA image format. ext.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT A DXT5-compressed image in an sRGBA image format. ...
WEBGL_depth_texture - Web APIs
The WEBGL_depth_texture extension is part of the WebGL API and defines 2D depth and depth-stencil textures. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default. The constant in WebGL2 is gl.UNSIGNED_INT_24_8. Constants This extension adds a new constant: ext.UNSIGNED_INT_24_8_WEBGL Unsigned integer type for 24-bit depth texture data. Extended methods This extension extends WebGLRenderingContext.texImage2D
(): The format and internalformat parameters now accept gl.DEPTH_COMPONENT and gl.DEPTH_STENCIL. The type param...
... Incorrectly stated as the target parameter in the specification, see https://www.khronos.org/bugzilla/show_bug.cgi?id=674. ...
WEBGL_lose_context - Web APIs
The WEBGL_lose_context extension is part of the WebGL API and exposes functions to simulate losing and restoring a WebGLRenderingContext. WebGL extensions are available using the WebGLRenderingContext.getExtension
() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is available to both, WebGL1 and WebGL2 contexts. Methods WEBGL_lose_context.loseContext
() Simulates losing the context. WEBGL_lose_context.restoreContext
() Simulates restoring the context. Examples With this extension, you can simulate the webglcontextlost and webglcontextrestored events: const canvas = document.getElementById('canvas'); const gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextlost', (event) => { console.log(event); })...
... Specifications Specification Status Comment WEBGL_lose_contextThe definition of 'WEBGL_lose_context' in that specification. ...
WaveShaperNode.curve - Web APIs
ny signal value of 0, the first one to signal values of -1, and the last to signal values of 1; values lower than -1 or greater than 1 are treated like -1 or 1 respectively. If necessary, intermediate values of the distortion curve are linearly interpolated. Note: The array can be a null value: in that case, no distortion is applied to the input signal. Syntax var audioCtx = new AudioContext
(); var distortion = audioCtx.createWaveShaper
(); distortion.curve = myCurveDataArray; // myCurveDataArray is a Float32Array Value A Float32Array. Example The following example shows basic usage of an AudioContext to create a wave shaper node. For applied examples/information, check out our Voice-change-O-matic demo (see app.js for relevant code). Note: Sigmoid functions are commonly used for...
...d examples/information, check out our Voice-change-O-matic demo (see app.js for relevant code). Note: Sigmoid functions are commonly used for distortion curves because of their natural properties. Their S-shape, for instance, helps create a smoother sounding result. We found the below distortion curve code on Stack Overflow. var audioCtx = new (window.AudioContext || window.webkitAudioContext)
(); var distortion = audioCtx.createWaveShaper
(); ... function makeDistortionCurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve = new Float32Array(n_samples), deg = Math.PI / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( Math.PI + k * Math.abs(x) ); } ret...
WaveShaperNode - Web APIs
eside obvious distortion effects, it is often used to add a warm feeling to the signal. A WaveShaperNode always has exactly one input and one output. Number of inputs 1 Number of outputs 1 Channel count mode "max" Channel count 2 (not used in the default count mode) Channel interpretation "speakers" Constructor WaveShaperNode
() Creates a new instance of an WaveShaperNode object. Properties Inherits properties from its parent, AudioNode. WaveShaperNode.curve Is a Float32Array of numbers describing the distortion to apply. WaveShaperNode.oversample Is an enumerated value indicating if oversampling must be used. Oversampling is a technique for creating more samples (up-sampling) before applying the distortion eff...
...d examples/information, check out our Voice-change-O-matic demo (see app.js for relevant code). Note: Sigmoid functions are commonly used for distortion curves because of their natural properties. Their S-shape, for instance, helps create a smoother sounding result. We found the below distortion curve code on Stack Overflow. var audioCtx = new (window.AudioContext || window.webkitAudioContext)
(); var distortion = audioCtx.createWaveShaper
(); ... function makeDistortionCurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve = new Float32Array(n_samples), deg = Math.PI / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( Math.PI + k * Math.abs(x) ); } ret...
WebGLFramebuffer - Web APIs
interface is part of the WebGL API and represents a collection of buffers that serve as a rendering destination. Description The WebGLFramebuffer object does not define any methods or properties of its own and its content is not directly accessible. ...
...resents a collection of buffers that serve as a rendering destination. Description The WebGLFramebuffer object does not define any methods or properties of its own and its content is not directly accessible. When working with WebGLFramebuffer objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.bindFramebuffer
() WebGLRenderingContext.createFramebuffer
() WebGLRenderingContext.deleteFramebuffer
() WebGLRenderingContext.isFramebuffer
() Examples Creating a frame buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createFramebuffer
(); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLFramebuffer' in that specification. Recommendation ...
WebGLProgram - Web APIs
The WebGLProgram is part of the WebGL API and is a combination of two compiled WebGLShaders consisting of a vertex shader and a fragment shader (both written in GLSL). To create a WebGLProgram, call the GL context's createProgram
() function. After attaching the shader programs using attachShader
(), you link them into a usable program. This is shown in the code below. var program = gl.createProgram
(); // Attach pre-existing shaders gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); if ( !gl.getProgramParameter( program, gl.LINK_STATUS) ) { var info = gl.getProgramInfoLog(program); throw 'Could not compile WebGL program. \n\n' + info; } See WebGLShader for information on creating the vertexShader and fragmentShader in the above...
...This frees the memory of the linked program. gl.deleteProgram(program); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLProgram' in that specification. Recommendation Initial definition. ...
WebGLRenderbuffer - Web APIs
L API and represents a buffer that can contain an image, or can be source or target of an rendering operation. Description The WebGLRenderbuffer object does not define any methods or properties of its own and its content is not directly accessible. ...
...in an image, or can be source or target of an rendering operation. Description The WebGLRenderbuffer object does not define any methods or properties of its own and its content is not directly accessible. When working with WebGLRenderbuffer objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.bindRenderbuffer
() WebGLRenderingContext.createRenderbuffer
() WebGLRenderingContext.deleteRenderbuffer
() WebGLRenderingContext.isRenderbuffer
() Examples Creating a render buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createRenderbuffer
(); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLRenderbuffer' in that specification. Recommenda...
WebGLTexture - Web APIs
erface is part of the WebGL API and represents an opaque texture object providing storage and state for texturing operations. Description The WebGLTexture object does not define any methods or properties of its own and its content is not directly accessible. ...
...resents an opaque texture object providing storage and state for texturing operations. Description The WebGLTexture object does not define any methods or properties of its own and its content is not directly accessible. When working with WebGLTexture objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.bindTexture
() WebGLRenderingContext.createTexture
() WebGLRenderingContext.deleteTexture
() WebGLRenderingContext.isTexture
() Examples Creating a texture var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture
(); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLTexture' in that specification. Recommendation Initial definitio...
Boilerplate 1 - Web APIs
ifically, the HTML has a <p> element that contains some descriptive text about the page and may also hold error messages; a <canvas> element; and optionally a <button>. The CSS contains rules for body, canvas, and button. Any additional non-trivial CSS and HTML will be displayed on the pages of specific examples. In following examples, we will use a JavaScript helper function, getRenderingContext
(), to initialize the WebGL rendering context. By now, you should be able to understand what the function does. Basically, it gets the WebGL rendering context from the canvas element, initializes the drawing buffer, clears it black, and returns the initialized context. In case of error, it displays an error message and returns null. Finally, all JavaScript code will run within an immediate function...
...nt. ...
Clearing with colors - Web APIs
est graphical WebGL program. Set up the rendering context and then just clear it solid green. Note that CSS sets the background color of the canvas to black, so when the canvas turns green we know that WebGL's magic has worked. In addition, you may notice that clearing the drawing buffer with a solid color is a two-stage process. First, we set the clear color to green, using the method clearColor
(). This only changes some internal state of WebGL, but does not draw anything yet. Next, we actually do the drawing by calling the clear
() method. This is typical of how drawing is done with WebGL. There is only a handful of methods for actual drawing (clear
() is one of them). All other methods are for setting and querying WebGL state variables (such as the clear color). There are many "dials" and...
...machine. By tweaking those "dials" and "switches" you can modify the internal state of the WebGL machine, which in turn changes how input (in this case, a clear command) translates into output (in this case, all pixels are set to green). Finally, we note that color in WebGL is usually in RGBA format, that is four numerical components for red, green, blue and alpha (opacity). Therefore, clearColor
() takes four arguments. <p>A very simple WebGL program that shows some color.</p> <!-- Text within a canvas element is displayed only if canvas is not supported. --> <canvas>Your browser 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; backgro...
Data in WebGL - Web APIs
vec4( 0.0, 0.0, 0.0, 1.0 ), // black vec4( 1.0, 0.0, 0.0, 1.0 ), // red vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow vec4( 0.0, 1.0, 0.0, 1.0 ), // green vec4( 0.0, 0.0, 0.0, 1.0 ), // black vec4( 1.0, 0.0, 0.0, 1.0 ), // red vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow vec4( 0.0, 1.0, 0.0, 1.0 ), // green ]; var cBuffer = gl.createBuffer
(); //continued //create buffer to store colors and reference it to "vColor" which is in GLSL gl.bindBuffer( gl.ARRAY_BUFFER, cBuffer ); gl.bufferData( gl.ARRAY_BUFFER, flatten(vertexColors), gl.STATIC_DRAW ); var vColor = gl.getAttribLocation( program, "vColor" ); gl.vertexAttribPointer( vColor, 4, gl.FLOAT, false, 0, 0 ); gl.enableVertexAttribArray( vColor ); //glsl at...
...This is commonly used to share a vertex's normal vector after it has been computed by the vertex shader. <<how to use>> Uniforms Uniforms are set by the JavaScript code and are available to both the vertex and fragment shaders. ...
WebSocket.bufferedAmount - Web APIs
Syntax var bufferedAmount = aWebSocket.bufferedAmount; Value An unsigned long. ...
... Syntax var bufferedAmount = aWebSocket.bufferedAmount; Value An unsigned long. ...
WebSocket - Web APIs
Constructor WebSocket(url[, protocols]) Returns a newly created WebSocket object. Constants Constant Value WebSocket.CONNECTING 0 WebSocket.OPEN 1 WebSocket.CLOSING 2 WebSocket.CLOSED 3 Properties WebSocket.binaryType The binary data type used by the connection. ...
... is opened. WebSocket.protocol Read only The sub-protocol selected by the server. WebSocket.readyState Read only The current state of the connection. WebSocket.url Read only The absolute URL of the WebSocket. Methods WebSocket.close([code[, reason]]) Closes the connection. WebSocket.send(data) Enqueues data to be transmitted. Events Listen to these events using addEventListener
() or by assigning an event listener to the oneventname property of this interface. close Fired when a connection with a WebSocket is closed. Also available via the onclose property error Fired when a connection with a WebSocket has been closed because of an error, such as when some data couldn't be sent. Also available via the onerror property. message Fired when data is received through ...
WebXR performance guide - Web APIs
ber of vectors and matrices and other structures that are used to build each frame of a 3D scene means the memory management becomes a problem eventually if you keep allocating and de-allocating memory objects. Consider the following function drawScene(gl, view, programInfo, buffers, texture, deltaTime) { ... for (object in scene) { let vertexList = ... let normalMatrix = mat4.create
(); let modelViewMatrix = mat4.create
(); let objectMatrix = mat4. // Apply rotation updates to the object if needed mat4.rotate( } } This renders a scene. But it's inefficient, because it allocates as local variables a number of things, including at least two matrices, an array of vertices, and more. That means that for every frame, the JavaScript runtime has to allocate memory ...
..., including at least two matrices, an array of vertices, and more. That means that for every frame, the JavaScript runtime has to allocate memory for those and set them up--possibly triggering garbage collection--and then when each interaction of the loop is completed, the memory is released. A simple change can optimize this significantly: const vertexList = ... const normalMatrix = mat4.create
(); const modelViewMatrix = mat4.create
(); function drawScene(gl, view, programInfo, buffers, texture, deltaTime) { ... for (object in scene) { ... } } Now, instead of allocating variables every loop iteration, we're using global constants(or class member constants). This has multiple benefits: The memory allocated for each value or structure will not need to be reallocated every fram...
Keyframe Formats - Web APIs
element.animate([ { // from opacity: 0, color: "#fff" }, { // to opacity: 1, color: "#000" } ], 2000); Offsets for each keyframe can be specified by providing an offset value. ...
... element.animate([ { // from opacity: 0, color: "#fff" }, { // to opacity: 1, color: "#000" } ], 2000); Offsets for each keyframe can be specified by providing an offset value. ...
Web Workers API - Web APIs
s makes it possible to run a script operation in a background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually 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...
... worker, or use some default methods and properties of the window object. But you can use a large number of items available under window, including WebSockets, and data storage mechanisms like IndexedDB. See Functions and classes available to workers for more details. Data is sent between workers and the main thread via a system of messages -- both sides send their messages using the postMessage
() method, and respond to messages via the onmessage event handler (the message is contained within the Message event's data property). The data is copied rather than shared. Workers may in turn spawn new workers, as long as those workers are hosted within the same origin as the parent page. In addition, workers may use XMLHttpRequest for network I/O, with the exception that the responseXML and ch...
Window.customElements - Web APIs
The customElements read-only property of the Window interface returns a reference to the CustomElementRegistry object, which can be used to register new custom elements and get information about previously registered custom elements. ...
...y being used is to get access to the CustomElementRegistry.define
() method to define and register a new custom element, e.g.: let customElementRegistry = window.customElements; customElementRegistry.define('my-custom-element', MyCustomElement); However, it is usually shortened to something like the following: customElements.define('element-details', class extends HTMLElement { constructor
() { super
(); const template = document .getElementById('element-details-template') .content; const shadowRoot = this.attachShadow({mode: 'open'}) .appendChild(template.cloneNode(true)); } } ); See our web-components-examples repo for more usage examples. Specification Specification Status Comment HTML Living StandardThe defi...
Window: hashchange event - Web APIs
hashchange event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol). ...
...# symbol). Bubbles Yes Cancelable No Interface HashChangeEvent Event handler onhashchange Examples You can use the hashchange event in an addEventListener method: window.addEventListener('hashchange', function
() { console.log('The hash has changed!') }, false); Or use the onhashchange event handler property: function locationHashChanged
() { if (location.hash === '#cool-feature') { console.log("You're visiting a cool feature!"); } } window.onhashchange = locationHashChanged; Specifications Specification Status Comment HTML Living StandardThe definition of 'hashchange' in that specification. Living Standard Initial definition ...
Window.history - Web APIs
The Window.history read-only property returns a reference to the History object, which provides an interface for manipulating the browser session history (pages visited in the tab or frame that the current page is loaded in). See Manipulating the browser history for examples and details. In particular, that article explains security features of the pushState
() and replaceState
() methods that you should be aware of before using them. Example history.back
(); // equivalent to clicking back button history.go(-1); // equivalent to history.back
(); Notes For top-level pages you can see the list of pages in the session history, accessible via the History object, in the browser's dropdowns next to the back and forward buttons. For security reasons the History object doesn't allow the ...
...owns next to the back and forward buttons. For security reasons the History object doesn't allow the non-privileged code to access the URLs of other pages in the session history, but it does allow it to navigate the session history. There is no way to clear the session history or to disable the back/forward navigation from unprivileged code. The closest available solution is the location.replace
() method, which replaces the current item of the session history with the provided URL. Specifications Specification Status Comment HTML Living StandardThe definition of 'The History interface' in that specification. Living Standard HTML5The definition of 'The History interface' in that specification. Recommendation ...
Window.localStorage - Web APIs
es a policy decision, or the origin is not a valid scheme/host/port tuple (this can happen if the origin uses the file: or data: scheme, for example). For example, the user may have their browser configured to deny permission to persist data for the specified origin. Example The following snippet accesses the current domain's local Storage object and adds a data item to it using Storage.setItem
(). ...
...local Storage object and adds a data item to it using Storage.setItem
(). localStorage.setItem('myCat', 'Tom'); The syntax for reading the localStorage item is as follows: const cat = localStorage.getItem('myCat'); The syntax for removing the localStorage item is as follows: localStorage.removeItem('myCat'); The syntax for removing all the localStorage items is as follows: localStorage.clear
(); Note: Please refer to the Using the Web Storage API article for a full example. Specifications Specification Status Comment HTML Living StandardThe definition of 'localStorage' in that specification. Living Standard ...
XMLHttpRequest: load event - Web APIs
Listeners(xhr) { xhr.addEventListener('loadstart', handleEvent); xhr.addEventListener('load', handleEvent); xhr.addEventListener('loadend', handleEvent); xhr.addEventListener('progress', handleEvent); xhr.addEventListener('error', handleEvent); xhr.addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest
(); addListeners(xhr); xhr.open("GET", url); xhr.send
(); return xhr; } xhrButtonSuccess.addEventListener('click',
() => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.addEventListener('click',
() => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.addEventListener('click',
() => { runXHR('https://mdn.mozil...
... xhr.send
(); return xhr; } xhrButtonSuccess.addEventListener('click',
() => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.addEventListener('click',
() => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.addEventListener('click',
() => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort
(); }); Result Specifications Specification Status Comment XMLHttpRequest Living Standard ...
XMLHttpRequest: loadend event - Web APIs
Listeners(xhr) { xhr.addEventListener('loadstart', handleEvent); xhr.addEventListener('load', handleEvent); xhr.addEventListener('loadend', handleEvent); xhr.addEventListener('progress', handleEvent); xhr.addEventListener('error', handleEvent); xhr.addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest
(); addListeners(xhr); xhr.open("GET", url); xhr.send
(); return xhr; } xhrButtonSuccess.addEventListener('click',
() => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.addEventListener('click',
() => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.addEventListener('click',
() => { runXHR('https://mdn.mozil...
... xhr.send
(); return xhr; } xhrButtonSuccess.addEventListener('click',
() => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.addEventListener('click',
() => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.addEventListener('click',
() => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort
(); }); Result Specifications Specification Status Comment XMLHttpRequest Living Standard ...
XMLHttpRequest: loadstart event - Web APIs
Listeners(xhr) { xhr.addEventListener('loadstart', handleEvent); xhr.addEventListener('load', handleEvent); xhr.addEventListener('loadend', handleEvent); xhr.addEventListener('progress', handleEvent); xhr.addEventListener('error', handleEvent); xhr.addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest
(); addListeners(xhr); xhr.open("GET", url); xhr.send
(); return xhr; } xhrButtonSuccess.addEventListener('click',
() => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.addEventListener('click',
() => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.addEventListener('click',
() => { runXHR('https://mdn.mozil...
... xhr.send
(); return xhr; } xhrButtonSuccess.addEventListener('click',
() => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.addEventListener('click',
() => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.addEventListener('click',
() => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort
(); }); Result Specifications Specification Status Comment XMLHttpRequest Living Standard ...
XMLHttpRequest: progress event - Web APIs
Listeners(xhr) { xhr.addEventListener('loadstart', handleEvent); xhr.addEventListener('load', handleEvent); xhr.addEventListener('loadend', handleEvent); xhr.addEventListener('progress', handleEvent); xhr.addEventListener('error', handleEvent); xhr.addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest
(); addListeners(xhr); xhr.open("GET", url); xhr.send
(); return xhr; } xhrButtonSuccess.addEventListener('click',
() => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.addEventListener('click',
() => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.addEventListener('click',
() => { runXHR('https://mdn.mozil...
... xhr.send
(); return xhr; } xhrButtonSuccess.addEventListener('click',
() => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.addEventListener('click',
() => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.addEventListener('click',
() => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort
(); }); Result Specifications Specification Status Comment XMLHttpRequest Living Standard ...
XMLHttpRequest.responseURL - Web APIs
The read-only XMLHttpRequest.responseURL property returns the serialized URL of the response or the empty string if the URL is null. If the URL is returned, any URL fragment present in the URL will be stripped away. The value of responseURL will be the final URL obtained after any redirects. ...
...d-only XMLHttpRequest.responseURL property returns the serialized URL of the response or the empty string if the URL is null. If the URL is returned, any URL fragment present in the URL will be stripped away. The value of responseURL will be the final URL obtained after any redirects. ...
XMLHttpRequest.responseXML - Web APIs
both HTML and XML. Usually, the response is parsed as "text/xml". If the responseType is set to "document" and the request was made asynchronously, instead the response is parsed as "text/html". responseXML is null for any other types of data, as well as for data: URLs. If the server doesn't specify the Content-Type as "text/xml" or "application/xml", you can use XMLHttpRequest.overrideMimeType
() to parse it as XML anyway. This property isn't available to workers. Syntax var data = XMLHttpRequest.responseXML; Value A Document from parsing the XML or HTML received using XMLHttpRequest, or null if no data was received or if the data is not XML/HTML. Exceptions InvalidStateError The responseType isn't either "document" or an empty string. Example var xhr = new XMLHttpRequest; x...
...ceived or if the data is not XML/HTML. Exceptions InvalidStateError The responseType isn't either "document" or an empty string. Example var xhr = new XMLHttpRequest; xhr.open('GET', '/server'); // If specified, responseType must be empty string or "document" xhr.responseType = 'document'; // Force the response to be parsed as XML xhr.overrideMimeType('text/xml'); xhr.onload = function
() { if (xhr.readyState === xhr.DONE && xhr.status === 200) { console.log(xhr.response, xhr.responseXML); } }; xhr.send
(); Specifications Specification Status Comment XMLHttpRequestThe definition of 'responseXML' in that specification. Living Standard WHATWG living standard ...
XMLHttpRequestEventTarget.onabort - Web APIs
The XMLHttpRequestEventTarget.onabort is the function called when an XMLHttpRequest transaction is aborted, such as when the XMLHttpRequest.abort
() function is called. Syntax XMLHttpRequest.onabort = callback; Values callback is the function to be executed when the transaction is aborted. Example var xmlhttp = new XMLHttpRequest
(), method = 'GET', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url, true); xmlhttp.onabort = function
() { console.log('** The request was aborted'); }; xmlhttp.send
(); //.. ...
...ction is called. Syntax XMLHttpRequest.onabort = callback; Values callback is the function to be executed when the transaction is aborted. Example var xmlhttp = new XMLHttpRequest
(), method = 'GET', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url, true); xmlhttp.onabort = function
() { console.log('** The request was aborted'); }; xmlhttp.send
(); //.. ...
XPathEvaluator - Web APIs
The XPathEvaluator interface allows to compile and evaluate XPath expressions. It is implemented by the Document interface. Methods XPathEvaluator.createExpression
() Creates a parsed XPath expression with resolved namespaces. XPathEvaluator.createNSResolver
() Adapts any DOM node to resolve namespaces allowing the XPath expression to be evaluated relative to the context of the node where it appeared within the document. XPathEvaluator.evaluate
() Evaluates an XPath expression string and returns a result of the specified type if possible. Example The following example shows the use of the XPathEvaluator interface. ...
... node where it appeared within the document. XPathEvaluator.evaluate
() Evaluates an XPath expression string and returns a result of the specified type if possible. Example The following example shows the use of the XPathEvaluator interface. ...
XPathResult.booleanValue - Web APIs
The read-only booleanValue property of the XPathResult interface returns the boolean value of a result with XPathResult.resultType being BOOLEAN_TYPE. Note: This feature is available in Web Workers. Syntax var value = result.booleanValue; Return value The return value is the boolean value of the XPathResult returned by Document.evaluate
(). ...
...turn value is the boolean value of the XPathResult returned by Document.evaluate
(). Exceptions TYPE_ERR In case XPathResult.resultType is not BOOLEAN_TYPE, an XPathException of type TYPE_ERR is thrown. Example The following example shows the use of the booleanValue property. HTML <div>XPath example</div> <p>Text is 'XPath example': <output></output></p> JavaScript var xpath = "//div/text
() = 'XPath example'"; var result = document.evaluate(xpath, document, null, XPathResult.BOOLEAN_TYPE, null); document.querySelector("output").textContent = result.booleanValue; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathResult.booleanValue' in that specification. Recommendation ...
XPathResult.singleNodeValue - Web APIs
ngleNodeValue property of the XPathResult interface returns a Node value or null in case no node was matched of a result with XPathResult.resultType being ANY_UNORDERED_NODE_TYPE or FIRST_ORDERED_NODE_TYPE. Note: This feature is available in Web Workers. Syntax var value = result.singleNodeValue; Return value The return value is the Node value of the XPathResult returned by Document.evaluate
(). Exceptions TYPE_ERR In case XPathResult.resultType is not ANY_UNORDERED_NODE_TYPE or FIRST_ORDERED_NODE_TYPE, an XPathException of type TYPE_ERR is thrown. Example The following example shows the use of the singleNodeValue property. HTML <div>XPath example</div> <div>Tag name of the element having the text content 'XPath example': <output></output></div> JavaScript var xpath = "//*[tex...
... Exceptions TYPE_ERR In case XPathResult.resultType is not ANY_UNORDERED_NODE_TYPE or FIRST_ORDERED_NODE_TYPE, an XPathException of type TYPE_ERR is thrown. Example The following example shows the use of the singleNodeValue property. ...
XPathResult.stringValue - Web APIs
The read-only stringValue property of the XPathResult interface returns the string value of a result with XPathResult.resultType being STRING_TYPE. Note: This feature is available in Web Workers. Syntax var value = result.stringValue; Return value The return value is the string value of the XPathResult returned by Document.evaluate
(). Exceptions TYPE_ERR In case XPathResult.resultType is not STRING_TYPE, an XPathException of type TYPE_ERR is thrown. ...
...he string value of the XPathResult returned by Document.evaluate
(). Exceptions TYPE_ERR In case XPathResult.resultType is not STRING_TYPE, an XPathException of type TYPE_ERR is thrown. Example The following example shows the use of the stringValue property. HTML <div>XPath example</div> <div>Text content of the <div> above: <output></output></div> JavaScript var xpath = "//div/text
()"; var result = document.evaluate(xpath, document, null, XPathResult.STRING_TYPE, null); document.querySelector("output").textContent = result.stringValue; Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe definition of 'XPathResult.stringValue' in that specification. Recommendation Initial definition ...
XPathResult - Web APIs
ype of the result, as defined by the type constants. XPathResult.singleNodeValueRead only A Node representing the value of the single node result, which may be null. XPathResult.snapshotLengthRead only The number of nodes in the result snapshot. XPathResult.stringValueRead only A string representing the value of the result if resultType is STRING_TYPE. Methods XPathResult.iterateNext
() If the result is a node set, this method iterates over it and returns the next node from it or null if there are no more nodes. XPathResult.snapshotItem
() Returns an item of the snapshot collection or null in case the index is not within the range of nodes. Unlike the iterator result, the snapshot does not become invalid, but may not correspond to the current document if it is mutated. Const...
...ype Defined Constant Value Description ANY_TYPE 0 A result set containing whatever type naturally results from evaluation of the expression. Note that if the result is a node-set then UNORDERED_NODE_ITERATOR_TYPE is always the resulting type. NUMBER_TYPE 1 A result containing a single number. This is useful for example, in an XPath expression using the count
() function. STRING_TYPE 2 A result containing a single string. BOOLEAN_TYPE 3 A result containing a single boolean value. This is useful for example, in an XPath expression using the not
() function. UNORDERED_NODE_ITERATOR_TYPE 4 A result node-set containing all the nodes matching the expression. The nodes may not necessarily be in the same order that th...
XRFrame - Web APIs
A WebXR Device API XRFrame object is passed into the requestAnimationFrame
() callback function and provides access to the information needed in order to render a single frame of animation for an XRSession describing a VR or AR sccene. Events which communicate the tracking state of objects also provide an XRFrame reference as part of their structure. In addition to providing a reference to the XRSession for which this frame is to be rendered, the getViewerPose
() method is provided to obtain the XRViewerPose describing the viewer's position and orientation in space, and getPose
() can be used to create an XRPose describing the relative position of one XRSpace relative to another. Properties session Read only The XRSession that for which this XRFrame describes the tracking det...
...r's position and orientation in space, and getPose
() can be used to create an XRPose describing the relative position of one XRSpace relative to another. Properties session Read only The XRSession that for which this XRFrame describes the tracking details for all objects. The information about a specific object can be obtained by calling one of the methods on the object. Methods getPose
() Returns an XRPose object representing the spatial relationship between the two specified XRSpace objects. getViewerPose
() Returns an XRViewerPose describing the viewer's position and orientation in a given XRReferenceSpace. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRFrame' in that specification. Working Draft Initial de...
XRInputSource.targetRayMode - Web APIs
Space. Inputs which have a value for this property represent inputs that project a target ray outward from the user. For each such input, this example looks for inputs whose targetRayMode is tracked-pointer, indicating that the input is in fact intended to represent a targeting device rather than a gazing device, screen tap, or mouse click. For tracked pointers, a function myRenderTargetRayAsBeam
() is called to render a beam from the input controller's virtual position outward in the direction it's pointing. The code should continue to perform tasks such as drawing controllers or any objects representative of the user's hands' positions in the virtual space, as well as any other input-related tasks. function updateInputSources(session, frame, refSpace) { for (let source of session.getIn...
... to render a beam from the input controller's virtual position outward in the direction it's pointing. The code should continue to perform tasks such as drawing controllers or any objects representative of the user's hands' positions in the virtual space, as well as any other input-related tasks. function updateInputSources(session, frame, refSpace) { for (let source of session.getInputSources
()) { let targetRayPose = frame.getPose(inputSource.targetRaySpace, refSpace); if (targetRayPose) { if (source.targetRayMode == "tracked-pointer") { myRenderTargetRayAsBeam(targetRayPose); } } /* ... */ } } See the article Inputs and input sources for more details and a more complete example. Specifications Specification Status Comment ...
XRInputSourceArray.length - Web APIs
Specifications Specification Status Comment We...
... { label: "Quit" handler: quitGame } ]); } Here, if length is 0, a hypothetical showAlertDialog
() function is called with a prompt string explaining the need for a controller, and an array of objects, each describing a button and what should happen when it's clicked. The first takes the user to an Amazon.com search for VR controllers, and the second calls a quitGame
() function to start shutting the game program down. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRInputSourceArray.length' in that specification. Working Draft Initial definition. ...
XRInputSourceEvent.frame - Web APIs
ting the event frame at which the user input event described by the object took place. Usage notes The event frame does not correspond to a visual frame as is delivered to the frame rendering callback function (see Rendering and the WebXR frame rendering callback for details on the callback). Instead, the XRFrame specified by the frame property is simply a method to provide access to the getPose
() method, which you can use to get the relative positions of the objects in the scene at the time the event occurred. However, since the event frame isn't an animation frame, there is no viewer pose available to represent the viewer's current point of view; the results of calling getViewerPose
() will be an XRViewerPose with an empty views list. Examples This code shows a handler for the selects...
...e
() will be an XRViewerPose with an empty views list. Examples This code shows a handler for the selectstart event which gets the target ray's pose from the frame, mapping the pose representing the ray (event.inputSource.targetRaySpace) to the overall reference space myRefSpace. Then, if the result isn't null, the target ray pose's transform is passed into a function called myCheckAndHandleHit
() to see if the ray was pointing at anything when the select was triggered. xrSession.onselectstart = event => { let targetRayPose = event.frame.getPose(event.inputSource.targetRaySpace, myRefSpace); if (targetRayPose) { checkAndHandleHit(targetRayPose.transform); } }; Specifications Specification Status Comment WebXR Device APIT...
XRInputSourceEvent - Web APIs
ebXR Device API's XRInputSourceEvent interface describes an event which has occurred on a WebXR user input device such as a hand controller, gaze tracking system, or motion tracking system. More specifically, they represent a change in the state of an XRInputSource. To learn more about handling inputs in a WebXR project, see the article Inputs and input sources. Constructor XRInputSourceEvent
() Creates and returns a new XRInputSourceEvent object whose properties match those provided in the eventInitDict dictionary provided. Properties frame Read only An XRFrame object providing the needed information about the event frame during which the event occurred. This frame may have been rendered in the past rather than being a current frame. Because this is an event frame, not an animat...
... properties match those provided in the eventInitDict dictionary provided. Properties frame Read only An XRFrame object providing the needed information about the event frame during which the event occurred. This frame may have been rendered in the past rather than being a current frame. Because this is an event frame, not an animation frame, you cannot call the XRFrame method getViewerPose
() on it; instead, use getPose
(). inputSource Read only An XRInputSource object indicating which input source generated the input event. Methods The XRInputSourceEvent interface doesn't define any methods; however, several methods are inherited from the parent interface, Event. Event types select Sent to an XRSession when the sending input source has fully completed a primary action. sel...
XRPermissionDescriptor.optionalFeatures - Web APIs
dicating set of features that your app would like to use, but can operate without if permission to use them isn't available. While further features may be defined in future editions of WebXR, currently all permitted values come from the XRReferenceSpaceType enumerated type, indicating reference spaces the app rquires to be available. The reference space returned by XRSession.requestReferenceSpace
() is either XRReferenceSpace or XRBoundedReferenceSpace. The "Interface" column in the table below indicates which of the two types is returned for each reference space type constant.. Reference space descriptors The types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. XRReferenceSpaceType ...
.... Otherwise, typically, one of the other reference space types will be used more often. XRReferenceSpace Usage notes Examples let xrPermissionDesc = { name: "xr", mode: "immersive-vr", optionalFeatures: [ "bounded-floor" ] }; if (navigator.permissions) { navigator.permissions.query(xrPermissionDesc).then(({state}) => { switch(state) { case "granted": setupXR
(); break; case "prompt": promptAndSetupXR
(); break; default: /* do nothing otherwise */ break; } .catch(err) { console.log(err); } } else { setupXR
(); } Specifications Specification Status Comment WebXR Device APIThe definition of 'XRPermissionDescriptor.optionalFeatures' in that specification. Working ...
XRPermissionDescriptor.requiredFeatures - Web APIs
This ensures that permissions are checked as applicable to ensure that those features are available upon request. ...
...r app to use immersive augmented reality mode with the local-floor reference space (presumably since the user is unlikely to start to fly). let xrPermissionDesc = { name: "xr", mode: "immersive-ar", requiredFeatures: [ "local-floor" ] }; if (navigator.permissions) { navigator.permissions.query(xrPermissionDesc).then(({state}) => { switch(state) { case "granted": setupXR
(); break; case "prompt": promptAndSetupXR
(); break; default: /* do nothing otherwise */ break; } .catch(err) { console.log(err); } } else { setupXR
(); } Specifications Specification Status Comment WebXR Device APIThe definition of 'XRPermissionDescriptor.requiredFeatures' in that specification. Working ...
XRReferenceSpace: reset event - Web APIs
ed by the XR device to introduce movement). However, if that kind of "teleportation" is being used, you actually want to avoid jumping the user's position after tracking recovery, this can introduce additional and potentially jarring jumping. Instead of allowing this to happen, you can integrate the emulatedPosition into the teleportation offset calculated prior to calling getOffsetReferenceSpace
() to create a new reference space whose updated effective origin is adjusted by the distance the viewer's position jumped since the previous frame. This way, the user's position only changes once rather than twice. The effect of discontinuity size The reset event won't be fired when the discontinuity is small enough that the device is able to regain tracking within the same tracking area. Nor wil...
... regain tracking within the same tracking area. Nor will be be fired at an unbounded reference space as it makes small adjustments to its native origin over time to maintain the space's stability in the vicinity of the user; only large discontinuities will trigger a reset. Examples To add a handler for the reset event, you can use either of two approaches. ...
XRReferenceSpaceType - Web APIs
The "Interface" column in the table below indicates which of the two types is returned for each reference space type constant.. ...
...The "Interface" column in the table below indicates which of the two types is returned for each reference space type constant.. ...
XRRenderStateInit - Web APIs
All distances are specified as floating-point values in meters; you can specify a value of 50 centimeters using a value of 0.5, for example. Properties baseLayer Optional An XRWebGLLayer object from which the WebXR compositor will obtain imagery. This is null by default. ...
...XRSession. The projection matrix calculation also takes into account the output canvas's aspect ratio. This property must not be specified for immersive sessions, so the value is null by default for immersive sessions. The default value is otherwise ? * 0.5 (half of the value of pi). Usage notes Any properties not specified in the XRRenderStateInit compliant object passed into updateRenderState
() are left at their current values. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRRenderStateInit' in that specification. Working Draft Initial definition. ...
XRRigidTransform.position - Web APIs
level is 1.5 meters): function onSessionStarted(xrSession) { xrSession.addEventListener("end", onSessionEnded); gl = initGraphics(xrSession); let glLayer = new XRWebGLLayer(xrSession, gl); xrSession.updateRenderState({ baseLayer: glLayer }); if (immersiveSession) { xrSession.requestReferenceSpace("bounded-floor").then((refSpace) => { refSpaceCreated(refSpace); }).catch(
() => { session.requestReferenceSpace("local-floor").then(refSpaceCreated); }); } else { session.requestReferenceSpace("viewer").then(refSpaceCreated); } } function refSpaceCreated(refSpace) { if (immersiveSession) { xrReferenceSpace = refSpace; } else { xrReferenceSpace = refSpace.getOffsetReferenceSpace( new XRRigidTransform({y: -1.5}); ); } xrSession.r...
...by looking to see if a variable immersiveSession is true; if so, we first request a bounded-floor reference space. if that fails (probably because bounded-floor isn't supported), we try requesting a local-floor reference space. If we're not in an immersive session, we instead request a viewer reference space. In all cases, once the space has been obtained, it gets passed into the refSpaceCreated
() function. For immersive spaces, the specified space is simply saved for future use. However, for inline sesions, we know we're in a space not automatically adjusted for floor level, so we request an offset reference space to shift the viewer's height to 1.5 meters above the presumed floor level of 0 meters. That new reference space is used instead of the one initially received. Finally, an anima...
XRSession: visibilitychange event - Web APIs
ty to determine the new visibility state. Bubbles Yes Cancelable No Interface XRSessionEvent Event handler property onvisibilitychange When the XRSession receives this event, the visibility state has already been changed. ...
... You can also create the event handler by assigning it to the XRSession's onvisibilitychange event handler property, like this: xrSession.onvisibilitychange = (e) => { /* event handled here */ }; Specifications Specification Status Comment WebXR Device APIThe ...
XRSessionEvent - Web APIs
The WebXR Device API's XRSessionEvent interface describes an event which indicates the change of the state of an XRSession. These events occur, for example, when the session ends or the visibility of its context changes. Constructor XRSessionEvent
() Creates and returns a new XRSessionEvent object configured using the specified XRSessionEventInit object's values as available. Properties In addition to properties inherited from its parent interface, Event, XRSessionEvent provides the folllowing: session Read only The XRSession to which the event refers. Methods While XRSessionEvent defines no methods, it inherits methods from its parent interface, Event. Session event types The following events are represented using the XRSessionEvent interface, and are permitted values for ...
...rface, and are permitted values for its type property. end Fired at the session when it has ended, after being terminated by the application or the user agent. visibilitychange Fired at the session whenever its visibility state changes. Examples This example creates a listiener that watches for the visibility state of the session to change. It reacts by calling a function mySessionVisible
() with a Boolean indicating whether or not the session is visible; this function might, for instance, spin up or reconfigure a worker that handles rendering the scene. xrSession.addEventListener("visibilitystate", e => { switch(e.session.visibilitystate) { case "visible": case "visible-blurred": mySessionVisible(true); break; case "hidden": mySessionVisible(false); ...
XRTargetRayMode - Web APIs
Space. Inputs which have a value for this property represent inputs that project a target ray outward from the user. For each such input, this example looks for inputs whose targetRayMode is tracked-pointer, indicating that the input is in fact intended to represent a targeting device rather than a gazing device, screen tap, or mouse click. For tracked pointers, a function myRenderTargetRayAsBeam
() is called to render a beam from the input controller's virtual position outward in the direction it's pointing. The code should continue to perform tasks such as drawing controllers or any objects representative of the user's hands' positions in the virtual space, as well as any other input-related tasks. function updateInputSources(session, frame, refSpace) { for (let source of session.getIn...
... to render a beam from the input controller's virtual position outward in the direction it's pointing. The code should continue to perform tasks such as drawing controllers or any objects representative of the user's hands' positions in the virtual space, as well as any other input-related tasks. function updateInputSources(session, frame, refSpace) { for (let source of session.getInputSources
()) { let targetRayPose = frame.getPose(inputSource.targetRaySpace, refSpace); if (targetRayPose) { if (source.targetRayMode == "tracked-pointer") { myRenderTargetRayAsBeam(targetRayPose); } } /* ... */ } } See the article Inputs and input sources for more details and a more complete example. Specifications Specification Status Comment ...
XRView.eye - Web APIs
If the result is false, indicating that the eye is now healthy, we render the scene for that eye. Otherwise, we don't. S...
...gl, view); } } For each of the views, the value of eye is checked and if it's either left or right, we check to see if the body.leftEye.injured or body.rightEye.injured property is true; if so, we call a function updateInjury
() on that eye to do things such as allow a bit of healing to occur, track the progress of a poison effect, or the like, as appropriate for the game's needs. updateInjury
() returns true if the eye is still injured or false if the eye has been restored to health by the function,. If the result is false, indicating that the eye is now healthy, we render the scene for that eye. Otherwise, we don't. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRView.eye' in that specification. Working Draft Initial d...
XRViewerPose.views - Web APIs
yntax let viewList = xrViewerPose.views; Value An array of XRView objects, one for each view available as part of the scene for the current viewer pose. This array's length may potentially vary over the lifetime of the XRSession (for example, if the viewer enables or disables stereo mode on their XR output device). Examples In this example--part of the code to render an XRFrame, getViewerPose
() is called to get an XRViewerPose using the same reference space the code is using as its base reference space. If a valid pose is returned, the frame is rendered by clearing the backbuffer and then rendering each of the views in the pose; these are most likely the views for the left and right eyes. let pose = frame.getViewerPose(xrReferenceSpace); if (pose) { let glLayer = xrSession.renderSta...
... This code is derived from Drawing a frame in Movement, orientation, and motion: A WebXR example. You can see more context and see much more on that page. Specifications Specification Status Comment ...
XRWebGLLayerInit.antialias - Web APIs
If this property is missing or is false, anti-aliasing is not desired. There is no way to request a specific anti-aliasing format or level; this decision is left up to the user agent. ...
...e new WebGL rendering layer. If false, anti-aliasing is not desired. Usage notes The state of anti-aliasing for the context after being created can be read from the XRWebGLLayer property antialias. Example In this example, before creating a new XRWebGLLayer to use for rendering, the value of a user preference from a configuration interface is obtained using a function called getPreferenceValue
() to determine whether the user has enabled or disabled anti-aliasing support; this is passed into the constructor. let options = { antialias: getPreferenceValue("antialiasing") }; let glLayer = new XRWebGLLayer(xrSession, gl, options); if (glLayer) { xrSession.updateRenderState({ baseLayer: glLayer }); } Offering the user features such as the ability to enable or disable things like anti-a...
XRWebGLLayerInit.framebufferScaleFactor - Web APIs
For example, a value of 1.0 indicates that the frame buffer should be the same resolution as the actual display, while a value of 0.5 indicates that the frame buffer should be half the resolution of the display. ...
...nd, creates a frame buffer whose resolution is double that of the actual display buffer. There are valid use cases for all of these kinds of scaling. See Managing rendering quality in WebXR performance guide for more information. You can determine the scaling factor that you would need to apply to match the default frame buffer resolution by using the XRWebGLLayer.getNativeFramebufferScaleFactor
() static function. Syntax let layerInit = { framebufferScaleFactor: scaleFactor }; let glLayer = new XRWebGLLayer(xrSession, gl, layerInit); let glLayer = new XRWebGLLayer(xrSession, gl, { framebufferScaleFactor: scaleFactor }); Value A floating-point value indicating a multiplier to apply to the default frame buffer resolution in order to determine the resolution of the frame buffer for th...
XRWebGLLayerInit.ignoreDepthValues - Web APIs
The depth buffer is typically used to assist in ordering vertices and, by extension, polygons while compositing, to ensure that the scene is correctly composited, with objects the correct distance away and with clipping and other distance-related computations performed as accurately as possible. Without the depth buffer, these computations must rely entirely on the coordinates of each pixel. ...
...thValues merely asks that the depth layer be ignored. Syntax let layerInit = { ignoreDepthValues: boolValue }; let glLayer = new XRWebGLLayer(xrSession, gl, layerInit); let glLayer = new XRWebGLLayer(xrSession, gl, { ignoreDepthValues: boolValue }); Value A Boolean value which can be set to true to disable the use of the depth buffer by the WebGL rendering layer created by the XRWebGLLayer
() constructor. The default value, false, means the depth buffer will be used, if available. Usage notes If ignoreDepthValues is true, the WebXR compositor will ignore the contents of the depth buffer, if it exists, while compositing and rendering the scene. If false, the depth buffer's contents are used, if one is present. Using a depth buffer while compositing allows the XR compositor to help e...
XRWebGLLayerInit - Web APIs
The constructor's optional layerInit parameter takes an object which must conform to this dictionary. Properties alpha Optional The frame buffer's color buffer will be established with an alpha channel if the alpha Boolean property is true. Otherwise, the color buffer will not have an alpha channel. The default value is true. antialias Optional A Boolean value which is true if anti-aliasing is to be used when rendering in the context; otherwise false. ...
...lean value which, if true, requests that the new layer have a depth buffer; otherwise, no depth layer is allocated. The default is true. framebufferScaleFactor Optional A floating-point value which is used to scale the image during compositing, with a value of 1.0 represents the default pixel size for the frame buffer. The static XRWebGLLayer function XRWebGLLayer.getNativeFramebufferScaleFactor
() returns the scale that would result in a 1:1 pixel ratio, thereby ensuring that the rendering is occurring at the device's native resolution. The default is 1.0. ignoreDepthValues Optional A Boolean value which indicates whether or not to ignore the contents of the depth buffer while compositing the scene. The default is false. stencil Optional A Boolean value which, if true, requests that th...
Generating HTML - Web APIs
cument the transformation creates. Figure 5 : Final 3 Templates XSL Stylesheet(example2.xsl): ... <xsl:template match="myNS:Author"> -- <xsl:value-of select="." /> <xsl:if test="@company"> :: <b> <xsl:value-of select="@company" /> </b> </xsl:if> <br /> </xsl:template> <xsl:template match="myNS:Body"> <xsl:copy> <xsl:apply-templates select="@*|node
()"/> </xsl:copy> </xsl:template> <xsl:template match="@*|node
()"> <xsl:copy> <xsl:apply-templates select="@*|node
()"/> </xsl:copy> </xsl:template> ... The final XSLT stylesheet looks as follows: Figure 6 : final XSLT Stylesheetview example | view source XSL Stylesheet: <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http:/...
.../myNS:Body"/> </p> </body> </html> </xsl:template> <xsl:template match="myNS:Author"> -- <xsl:value-of select="." /> <xsl:if test="@company"> :: <b> <xsl:value-of select="@company" /> </b> </xsl:if> <br /> </xsl:template> <xsl:template match="myNS:Body"> <xsl:copy> <xsl:apply-templates select="@*|node
()"/> </xsl:copy> </xsl:template> <xsl:template match="@*|node
()"> <xsl:copy> <xsl:apply-templates select="@*|node
()"/> </xsl:copy> </xsl:template> </xsl:stylesheet> ...
msCapsLockWarningOff - Web APIs
arning to be disabled. Syntax document.msCapsLockWarningOff = true; Value Type: boolean False: Default. Automatic caps lock warning is turned on. True: Automatic caps lock warning is turned off. ...
...LockWarningOff = true; document.getElementById("caps").innerHTML = "Warning off"; } else { document.msCapsLockWarningOff = false; document.getElementById("caps").innerHTML = "Warning on"; } } </script> </head> <body> <label>Type a password: <input type="password" /></label><br /> <button id="caps" onclick="capsOff
();">Warning off</button> </body> </html> ...
msthumbnailclick - Web APIs
nterface for the current event. ...
...external.msSiteModeClearIconOverlay
(); // pinned icons on your taskbar can be instructed to trigger specific events on your site from the taskbar // add an event handlerdocument.addEventListener('msthumbnailclick', onButtonClicked, false); // add the buttons var btnPlay = window.external.msSiteModeAddThumbBarButton(iconUri, toolTip); // refresh the taskbar window.external.msSiteModeShowThumbBar
(); // call a javascript function when the button is pressed function onButtonClicked(e) { switch (e.buttonID) { case btnPlay: play
(); break;} } See also Microsoft API extensions ...
Using the link role - Accessibility
Screen magnifiers may enlarge links. Note: Opinons may differ on how assistive technology should handle this technique. The information provided above is one of those opinions and therefore not normative. Examples This example shows how to implement a fake link using a <span> element. This includes JavaScript to grab the location and handle navigating to the new location using window.open
() via clicking, and using keyboard, CSS to give the desired visuals of a link, the tabindex="0" attribute to make it keyboard-focussable, and role="link" to make it recognised as a link by assistive technology. This is a huge amount of work just to recreate something you've get for free using the <a> element, so you should really use that if possible. But this shows that it can be done. You shoul...
...get for free using the <a> element, so you should really use that if possible. But this shows that it can be done. You should however note that there are still problems with this approach: It is very difficult to detect whether the target of the fake link has been visited before, and therefore use :visited styles (e.g. the default purple color for visited links). Opening a page using the open
() method counts as being a popup, and certain browsers may issue a warning when you try to activate it, or make you explicitly agree to allowing popups form the domain it exists on. HTML <h1>role="link" example</h1> <span data-href="https://mozilla.org" tabindex="0" id="link1" role="link" class="link"> Fake accessible link created using a span </span> <p><a href="https://mozilla.org" target=...
ARIA: tab role - Accessibility
ia-selected=true inside the parent element and sets it to false, then sets the triggering element's aria-selected to true. After that, we find all tabpanel elements in the grandparent element, make them all hidden, and finally select the element whose id is equal to the triggering tab's aria-controls and removes the hidden attribute, making it visible. ...
... If we're at the end, go to the start if (tabFocus >= tabs.length) { tabFocus = 0; } // Move left } else if (e.keyCode === 37) { tabFocus--; // If we're at the start, move to the end if (tabFocus < 0) { tabFocus = tabs.length - 1; } } tabs[tabFocus].setAttribute("tabindex", 0); tabs[tabFocus].focus
(); } }); }); function changeTabs(e) { const target = e.target; const parent = target.parentNode; const grandparent = parent.parentNode; // Remove all current selected tabs parent .querySelectorAll('[aria-selected="true"]') .forEach(t => t.setAttribute("aria-selected", false)); // Set this tab as selected target.setAttribute("aria-selected", true); // Hide all tab p...
Architecture - Accessibility
ch is the subset of children from the nsIAccessible hierarchy that are not text or whitespace. ATK: Same as nsIAccessible, except that text and whitespace leaf nodes are not exposed. The children of any Hypertext object are an exact match to the links it exposes. The implementation simply doesn't create AtkObjects for a whitespace or text leaf nsIAccessibles. See the ATK uses of IsEmbeddedObject
() for more information on how we do this. IAccessible2: Same as nsIAccessible. Text and whitespace leaf nodes are exposed, but are redundant with the information in the parent object's nsIAccessibleText. This is done for backward compatibility with older MSAA clients which didn't have access to a text interface. The children of a Hypertext object are a superset of the links it exposes. The new sy...
...offset in the parent text for a given embedded object: QI/QA to IAHyperLink If not successful, then it is not embedded in text, so it's position in parent should be determined just by IA2::indexInParent, which will return its child offset within the parent. Examples of objects not embedded in text are the child options in list boxes and combo boxes. otherwise, use IAHyperLink::getStartIndex
() to find the index in parent. In Firefox, the results of getEndIndex will always be the startIndex + 1, because links are always just represented by a single embedded object character (C) To get the next char fom a given offset in an accessible text: If current char is 0 (end of string), then we are on a hard line break: get next node (typical depth first search), and set the current offset = ...
Web accessibility for seizures and physical reactions - Accessibility
the example below from the section on New in Chrome 74. button { animation: vibrate 0.3s linear infinite both; } @media (prefers-reduced-motion: reduce) { button { animation: none; } } prefers-color-scheme This can be useful if the ambient light API is not available. Support is emerging. @media (prefers-color-scheme: dark) { /* adust styles for dark mode */ } Window.matchMedia
() There is a powerful tool available to developers via Window.matchMedia
(). A great resource is MDN's document on Window.matchMedia
() media update feature The more often the screen is refreshed, the more stable it appears to the human eye, and the less it "flickers". The vast majority of modern technology refreshes at a rate that does not cause problems with photosensitivity. However, not everyb...
...model is intended to provide the features necessary for expressing CSS Transitions [CSS-TRANSITIONS-1], CSS Animations [CSS-ANIMATIONS-1], and SVG [SVG11]. See Also MDN Accessibility: What users can to to browse more safely Accessibility: Understanding color and luminance Applying SVG effects to HTML Content Basic Animations (Canvas Tutorial) Canvas API CanvasRenderingContext2D.drawImage
() <color> Document Object Model MediaQueryList Using dynamic styling information WebGL: 2D and 3D graphics for the web Color Color Tutorial: describing color Tom Jewett. Formula to Determine Brightness of RGB color Stack Exchange Discussion Thread How the Color Red Influences Our Behavior Scientific American By Susana Martinez-Conde, Stephen L. Macknik on November 1, 2014 Discussions ...
-moz-outline-radius-bottomleft - CSS: Cascading Style Sheets
Values <length> The radius of the circle defining the curvature of the bottom and left edges of the element, specified as a CSS <length>. ...
...s a CSS <length>. <percentage> The radius of the circle defining the rounding of the bottom-left corner of the element, specified as the percentages of the bottom and left sides of the border box. Formal definition Initial value0Applies toall elementsInheritednoPercentagesrefer to the corresponding dimension of the border boxComputed valueas specifiedAnimation typea length, percentage or calc
(); Formal syntax <outline-radius>where <outline-radius> = <length> | <percentage> Examples Rounding a outline Since this is a Firefox-only property, this example will not display the desired effect if you are viewing this in a browser other than Firefox. HTML <p>Look at this paragraph's bottom-left corner.</p> CSS p { margin: 10px; border: solid cyan; outline: dotted green; -moz-ou...
-moz-outline-radius-bottomright - CSS: Cascading Style Sheets
Values <length> The radius of the circle defining the curvature of the bottom and right edges of the element, specified as a CSS <length>. ...
...a CSS <length>. <percentage> The radius of the circle defining the rounding of the bottom-right corner of the element, specified as the percentages of the bottom and right sides of the border box. Formal definition Initial value0Applies toall elementsInheritednoPercentagesrefer to the corresponding dimension of the border boxComputed valueas specifiedAnimation typea length, percentage or calc
(); Formal syntax <outline-radius>where <outline-radius> = <length> | <percentage> Examples HTML <p>Look at this paragraph's bottom-right corner.</p> CSS p { margin: 5px; border: solid cyan; outline: dotted red; -moz-outline-radius-bottomright: 2em; } Result The example above will not display the desired effect if you are viewing this in a browser other than Firefox. Specificat...
-moz-outline-radius-topleft - CSS: Cascading Style Sheets
Values <length> The radius of the circle defining the curvature of the top and left edges of the element, specified as a CSS <length>. ...
...fied as a CSS <length>. <percentage> The radius of the circle defining the rounding of the top-left corner of the element, specified as the percentages of the top and left sides of the border box. Formal definition Initial value0Applies toall elementsInheritednoPercentagesrefer to the corresponding dimension of the border boxComputed valueas specifiedAnimation typea length, percentage or calc
(); Formal syntax <outline-radius>where <outline-radius> = <length> | <percentage> Examples The example below will not display the desired effect if you are viewing this in a browser other than Firefox. HTML <p>Look at this paragraph's top-left corner.</p> CSS p { margin: 5px; border: solid cyan; outline: dotted red; -moz-outline-radius-topleft: 2em; } Result Specifications Not ...
-moz-outline-radius-topright - CSS: Cascading Style Sheets
Values <length> The radius of the circle defining the curvature of the top and right edges of the element, specified as a CSS <length>. ...
...ed as a CSS <length>. <percentage> The radius of the circle defining the rounding of the top-right corner of the element, specified as the percentages of the top and right sides of the border box. Formal definition Initial value0Applies toall elementsInheritednoPercentagesrefer to the corresponding dimension of the border boxComputed valueas specifiedAnimation typea length, percentage or calc
(); Formal syntax <outline-radius>where <outline-radius> = <length> | <percentage> Examples HTML <p>Look at this paragraph's top-right corner.</p> CSS p { margin: 5px; border: solid cyan; outline: dotted red; -moz-outline-radius-topright: 2em; } Result The example above will not display the desired effect if you are viewing this in a browser other than Firefox. Specifications ...
aspect-ratio - CSS: Cascading Style Sheets
Candidate Recommendation No change. Media Quer...
... Candidate Recommendation No change. Media QueriesThe definition of 'aspect-ratio' in that specification. Recommendation Initial definition. ...
Using CSS animations - CSS: Cascading Style Sheets
things up. var element = document.getElementById("watchme"); element.addEventListener("animationstart", listener, false); element.addEventListener("animationend", listener, false); element.addEventListener("animationiteration", listener, false); element.className = "slidein"; This is pretty standard code; you can get details on how it works in the documentation for eventTarget.addEventListener
(). The last thing this code does is set the class on the element we'll be animating to "slidein"; we do this to start the animation. Why? Because the animationstart event fires as soon as the animation starts, and in our case, that happens before our code runs. So we'll start the animation ourselves by setting the class of the element to the style that gets animated after the fact. Receiving the ...
... on the element we'll be animating to "slidein"; we do this to start the animation. Why? Because the animationstart event fires as soon as the animation starts, and in our case, that happens before our code runs. So we'll start the animation ourselves by setting the class of the element to the style that gets animated after the fact. Receiving the events The events get delivered to the listener
() function, which is shown below. function listener(event) { var l = document.createElement("li"); switch(event.type) { case "animationstart": l.innerHTML = "Started: elapsed time is " + event.elapsedTime; break; case "animationend": l.innerHTML = "Ended: elapsed time is " + event.elapsedTime; break; case "animationiteration": l.innerHTML = "New loop s...
Basic Concepts of grid layout - CSS: Cascading Style Sheets
grid-template-columns: 2fr 1fr 1fr; } In this final example, we mix absolute sized tracks with fraction units. The first track is 500 pixels, so the fixed width is taken away from the available space. The remaining space is divided into three and assigned in proportion to the two flexible tracks. .wrapper { display: grid; grid-template-columns: 500px 1fr 2fr; } Track listings with repeat
() notation Large grids with many tracks can use the repeat
() notation, to repeat all or a section of the track listing. For example the grid definition: .wrapper { display: grid; grid-template-columns: 1fr 1fr 1fr; } Can also be written as: .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); } Repeat notation can be used for a part of the track listing. In this next exam...
...rid or defining the sizing for automatically created rows or columns we may want to give tracks a minimum size, but also ensure they expand to fit any content that is added. For example, I may want my rows to never collapse smaller than 100 pixels, but if my content stretches to 300 pixels in height, then I would like the row to stretch to that height. Grid has a solution for this with the minmax
() function. In this next example I am using minmax
() in the value of grid-auto-rows. This means automatically created rows will be a minimum of 100 pixels tall, and a maximum of auto. Using auto means that the size will look at the content size and will stretch to give space for the tallest item in a cell, in this row. .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-aut...
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
hree</div> </div> .wrapper { display: grid; grid-template-columns: repeat(3,1fr); align-items: end; grid-auto-rows: 200px; } .box1 { align-self: stretch; } .box2 { align-self: start; } The fr unit and flex-basis We have already seen how the fr unit works to assign a proportion of available space in the grid container to our grid tracks. The fr unit, when combined with the minmax
() function can give us very similar behavior to the flex properties in flexbox while still enabling the creation of a layout in two dimensions. If we look back at the example where I demonstrated the difference between one and two-dimensional layouts, you can see there is a difference between the way of the two layouts work responsively. With the flex layout, if we drag our window wider and smalle...
...0f; } <div class="wrapper"> <div>One</div> <div>Two</div> <div>Three</div> </div> .wrapper { display: grid; grid-template-columns: repeat(auto-fill, 200px); } A flexible number of tracks This isn't quite the same as flexbox. In the flexbox example, the items are larger than the 200 pixel basis before wrapping. We can achieve the same in grid by combining auto-fit and the minmax
() function. In this next example, I create auto filled tracks with minmax. I want my tracks to be a minimum of 200 pixels, so I set the maximum to be 1fr. Once the browser has worked out how many times 200 pixels will fit into the container-also taking account of grid gaps-it will treat the 1fr maximum as an instruction to share out the remaining space between the items. * {box-sizing: border-box...
CSS Images - CSS: Cascading Style Sheets
CSS Images is a module of CSS that defines what types of images can be used (the <image> type, containing URLs, gradients and other types of images), how to resize them and how they, and other replaced content, interact with the different layout models. Reference Properties image-orientation image-rendering image-resolution object-fit object-position Functions linear-gradient
() radial-gradient
() repeating-linear-gradient
() repeating-radial-gradient
() conic-gradient
() repeating-conic-gradient
() url
() element
() image
() cross-fade
() Data types <gradient> <image> Guides Using CSS gradients Presents a specific type of CSS images, gradients, and how to create and use these. Implementing image sprites in CSS Describes the common technique grouping several...
... of CSS images, gradients, and how to create and use these. Implementing image sprites in CSS Describes the common technique grouping several images in one single document to save download requests and speed up the availability of a page. Specifications Specification Status Comment CSS Images Module Level 4 Working Draft Added image-resolution, conic-gradient
(), and image
() CSS Images Module Level 3 Candidate Recommendation Added image-orientation, image-rendering, object-fit and object-position Compatibility StandardThe definition of 'CSS Gradients' in that specification. Living Standard Standardizes the -webkit prefixed gradient value functions CSS Values and Units Module Level 3The definition of '<url>' in that ...
Overview of CSS Shapes - CSS: Cascading Style Sheets
side-effect of creating a simple fallback for many cases. If you do not have Shapes support in the browser, the user will see content flowing around the sides of a rectangular box as before. If they do have Shapes support then the visual display is enhanced. Basic Shapes The value circle(50%) is an example of a Basic Shape. The specification defines four <basic-shape> values, which are: inset
() circle
() ellipse
() polygon
() Using the value inset
() wraps text around a rectangular shape however you are able to add offset values, thus pulling the line boxes of any wrapping content closer to the object than would otherwise happen. We have already seen how circle
() creates a circular shape. An ellipse
() is essentially a squashed circle. If none of these simple shapes do the trick you ca...
... In our Guide to Basic Shapes we explore each of the possible Basic Shapes and how to create them. ...
Using media queries - CSS: Cascading Style Sheets
s. screen) or specific characteristics and parameters (such as screen resolution or browser viewport width). Media queries are used for the following: To conditionally apply styles with the CSS @media and @import at-rules. To target specific media for the <style>, <link>, <source>, and other HTML elements with the media= attribute. To test and monitor media states using the Window.matchMedia
() and MediaQueryList.addListener
() JavaScript methods. Note: The examples on this page use CSS's @media for illustrative purposes, but the basic syntax remains the same for all types of media queries. Syntax A media query is composed of an optional media type and any number of media feature expressions. Multiple queries can be combined in various ways by using logical operators. Media queries...
...edia (width <= 30em) { ... } Using min- and max- we might test for a width between two values like so: @media (min-width: 30em) and (max-width: 50em) { ... } This would convert to the Level 4 syntax as: @media (30em <= width <= 50em ) { ... } Media Queries Level 4 also adds ways to combine media queries using full boolean algebra with and, not, and or. Negating a feature with not Using not
() around a media feature negates that feature in the query. For example, not(hover) would match if the device had no hover capability: @media (not(hover)) { ... } Testing for multiple features with or You can use or to test for a match among more than one feature, resolving to true if any of the features are true. For example, the following query tests for devices that have a monochrome display ...
Pseudo-elements - CSS: Cascading Style Sheets
pseudo-classes from pseudo-elements. However, since this distinction was not present in older versions of the W3C spec, most browsers support both syntaxes for the original pseudo-elements. ...
... since this distinction was not present in older versions of the W3C spec, most browsers support both syntaxes for the original pseudo-elements. ...
WebKit CSS extensions - CSS: Cascading Style Sheets
cated -webkit- properties The following properties were once supported with the -webkit- prefix but are no longer supported in evergreen browsers, with or without the -webkit- prefix. ...
...break-after -webkit-region-break-before -webkit-region-break-inside -webkit-region-fragment -webkit-shape-inside -webkit-touch-callout (See touch-action) background-origin-x (unprefixed!) background-origin-y (unprefixed!) * Still supported in the Safari Technology Preview, but not in a generally released browser. Pseudo-classes :-webkit-animating-full-screen-transition :-webkit-any
() :-webkit-any-link* :-webkit-autofill :-webkit-autofill-strong-password :-webkit-drag :-webkit-full-page-media :-webkit-full-screen* :-webkit-full-screen-ancestor :-webkit-full-screen-document :-webkit-full-screen-controls-hidden * Now standard. Note: If there is an invalid pseudo-class within in a chain or group of selectors, the whole selector list is invalid. Pseudo-elements Fo...
<angle-percentage> - CSS: Cascading Style Sheets
The <angle-percentage> CSS data type represents a value that can be either a <angle> or a <percentage>. Syntax Refer to the documentation for <angle> and <percentage> for details of the individual syntaxes allowed by this type. Use in calc
() Where an <angle-percentage> is specified as an allowable type, this means that the percentage resolves to an angle and therefore can be used in a calc
() expression. ...
... be used in a calc
() expression. Specifications Specification Status Comment CSS Values and Units Module Level 4The definition of '<angle-percentage>' in that specification. Editor's Draft CSS Values and Units Module Level 3The definition of '<angle-percentage>' in that specification. Candidate Recommendation Defines <angle-percentage>. ...
background-size - CSS: Cascading Style Sheets
dimensions and proportions. A vector image (such as SVG) does not necessarily have intrinsic dimensions. If it has both horizontal and vertical intrinsic dimensions, it also has intrinsic proportions. If it has no dimensions or only one dimension, it may or may not have proportions. CSS <gradient>s have no intrinsic dimensions or intrinsic proportions. Background images created with the element
() function use the intrinsic dimensions and proportions of the generating element. Note: The behavior of <gradient>s changed in Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5). Before this, they were treated as images with no intrinsic dimensions, but with intrinsic proportions identical to that of the background positioning area. Note: In Gecko, background images created using the ...
...on use the intrinsic dimensions and proportions of the generating element. Note: The behavior of <gradient>s changed in Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5). Before this, they were treated as images with no intrinsic dimensions, but with intrinsic proportions identical to that of the background positioning area. Note: In Gecko, background images created using the element
() function are currently treated as images with the dimensions of the element, or of the background positioning area if the element is SVG, with the corresponding intrinsic proportion. This is non-standard behavior. Based on the intrinsic dimensions and proportions, the rendered size of the background image is computed as follows: If both components of background-size are specified and are not...
block-size - CSS: Cascading Style Sheets
tically oriented, the value of block-size relates to the width of the element; otherwise, it relates to the height of the element. A related property is inline-size, which defines the other dimension of the element. ...
...ntaining blockComputed valuesame as width and heightAnimation typea length, percentage or calc
(); Syntax Values The block-size property takes the same values as the width and height properties. Formal definition Initial valueautoApplies tosame as width and heightInheritednoPercentagesblock-size of containing blockComputed valuesame as width and heightAnimation typea length, percentage or calc
(); Formal syntax <'width'> Examples Block size with vertical text HTML <p class="exampleText">Example text</p> CSS .exampleText { writing-mode: vertical-rl; background-color: yellow; block-size: 200px; } Result Specifications Specification Status Comment CSS Logical Properties and Values Level 1The definition of 'block-size' in that specification. ...
display - CSS: Cascading Style Sheets
Specifications Specification Status Comment CSS Display Module Level 3The definition of 'display' in tha...
...in: 1px; } article, span { padding: 10px; border-radius: 7px; } article, div { margin: 20px; } JavaScript const articles = document.querySelectorAll('.container'); const select = document.querySelector('select'); function updateDisplay
() { articles.forEach((article) => { article.style.display = select.value; }); } select.addEventListener('change', updateDisplay); updateDisplay
(); Result Note: You can find more examples in the pages for each separate display data type, linked above. Specifications Specification Status Comment CSS Display Module Level 3The definition of 'display' in that specification. Candidate Recommendation Added run-in, flow, flow-root, contents, and multi-keyword values. CSS Ruby Layout Module Level 1...
flex - CSS: Cascading Style Sheets
| <'flex-basis'> ] Examples Setting flex: auto HTML <div id="flex-container"> <div class="flex-item" id="flex">Flex box (click to toggle raw box)</div> <div class="raw-item" id="raw">Raw box</div> </div> CSS #flex-container { display: flex; flex-direction: row; } #flex-container > .flex-item { flex: auto; } #flex-containe...
..."block" : "none"; }); #flex-container { width: 100%; font-family: Consolas, Arial, sans-serif; } #flex-container > div { border: 1px solid #f00; padding: 1rem; } #flex-container > .raw-item { border: 1px solid #000; } Result Specifications Specification Status Comment CSS Flexible Box Layout Mod...
font-style - CSS: Cascading Style Sheets
MDN Understanding WCAG, Guidel...
...; } JavaScript let slantLabel = document.querySelector('label[for="slant"]'); let slantInput = document.querySelector('#slant'); let sampleText = document.querySelector('.sample'); function update
() { let slant = `oblique ${slantInput.value}deg`; slantLabel.textContent = `font-style: ${slant};`; sampleText.style.fontStyle = slant; } slantInput.addEventListener('input', update); update
(); Accessibility concerns Large sections of text set with a font-style value of italic may be difficult for people with cognitive concerns such as Dyslexia to read. MDN Understanding WCAG, Guideline 1.4 explanations W3C Understanding WCAG 2.1 Formal definition Initial valuenormalApplies toall elements. It also applies to ::first-letter and ::first-line.InheritedyesComputed valueas specif...
<frequency-percentage> - CSS: Cascading Style Sheets
The <frequency-percentage> CSS data type represents a value that can be either a <frequency> or a <percentage>. Frequency values, e.g. the pitch of a speaking voice, are not currently used in any CSS properties. Syntax The value of a <frequency-percentage> is either a <frequency> or a <percentage>; see their individual reference pages for details about their syntaxes. Description Use in calc
() Where a <frequency-percentage> is specified as an allowable type, this means that the percentage resolves to a frequency and therefore can be used in a calc
() expression. Examples Valid percentage values 90% Positive percentage +90% Positive percentage with leading + -90% Negative percentage -- not valid for all properties that use percentages Invalid percentage values 90 % No space is allo...
...invalid <frequency>. Specifications Specification Status Comment CSS Values and Units Module Level 4The definition of '<frequency-percentage>' in that specification. Editor's Draft CSS Values and Units Module Level 3The definition of '<frequency-percentage>' in that specification. Candidate Recommendation Defines <frequency-percentage>. Adds calc
() ...
<gradient> - CSS: Cascading Style Sheets
ient has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. Its concrete size will match the size of the element to which it applies. Syntax The <gradient> data type is defined with one of the function types listed below. Linear gradient Linear gradients transition colors progressively along an imaginary line. They are generated with the linear-gradient
() function. Radial gradient Radial gradients transition colors progressively from a center point (origin). They are generated with the radial-gradient
() function. Repeating gradient Repeating gradients duplicate a gradient as much as necessary to fill a given area. They are generated with the repeating-linear-gradient
() and repeating-radial-gradient
() functions. Conic gradient Conic gra...
... Interpolation As with any interpolation involving colors, gradients are calculated in the alpha-premultiplied color space. This prevents unexpected shades of gray from appearing when both the color and the opacity are changing. ...
grid-auto-flow - CSS: Cascading Style Sheets
definition Initial valuerowApplies togrid containersInheritednoComputed valueas specifiedAnimation typediscrete Formal syntax [ row | column ] | dense Examples Setting grid auto-placement HTML <div id="grid"> <div id="item1"></div> <div id="item2"></div> <div id="item3"></div> <div id="item4"></div> <div id="item5"></div> </div> <select id="direction" onchange="changeGridAutoFlow
()"> <option value="column">column</option> <option value="row">row</option> </select> <input id="dense" type="checkbox" onchange="changeGridAutoFlow
()"> <label for="dense">dense</label> CSS #grid { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); grid-auto-flow: column; /* or 'row', 'row dense', 'column dense' */ } #ite...
..."row" : "column"; if (dense.checked) { gridAutoFlow += " dense"; } grid.style.gridAutoFlow = gridAutoFlow; } Result Specifications Specification Status Comment ...
grid-auto-rows - CSS: Cascading Style Sheets
auto-placement algorithm creating additional rows. ...
... a non-negative <percentage> value relative to the block size of the grid container. If the block size of the grid container is indefinite, the percentage value is treated like auto. <flex> Is a non-negative dimension with the unit fr specifying the track's flex factor. Each <flex>-sized track takes a share of the remaining space in proportion to its flex factor. When appearing outside a minmax
() notation, it implies an automatic minimum (i.e. minmax(auto, <flex>)). max-content Is a keyword representing the largest maximal content contribution of the grid items occupying the grid track. min-content Is a keyword representing the largest minimal content contribution of the grid items occupying the grid track. minmax(min, max) Is a functional notation that defines a size range greate...
offset-distance - CSS: Cascading Style Sheets
. Syntax /* Default value */ offset-distance: 0; /* the middle of the offset-path */ offset-distance: 50%; /* a fixed length positioned along the path */ offset-distance: 40px; <length-percentage> A length that specifies how far the element is along the path (defined with offset-path). ...
...far the element is along the path (defined with offset-path). 100% represents the total length of the path (when the offset-path is defined as a basic shape or path
()). Formal definition Initial value0Applies totransformable elementsInheritednoPercentagesrefer to the total path lengthComputed valuefor <length> the absolute value, otherwise a percentageAnimation typea length, percentage or calc
(); Formal syntax <length-percentage>where <length-percentage> = <length> | <percentage> Examples Using offset-distance in an animation The motion aspect in CSS Motion Path typically comes from animating the offset-distance property. If you want to animate an element along its full path, you would define its offset-path and then set up an animation that takes the offset-distance from 0% to 100%...
rotate - CSS: Cascading Style Sheets
y. Syntax /* Keyword values */ rotate: none; /* Angle value */ rotate: 90deg; rotate: 0.25turn; rotate: 1.57rad; /* x, y, or z axis name plus angle */ rotate: x 90deg; rotate: y 0.25turn; rotate: z 1.57rad; /* Vector plus angle value */ rotate: 1 1 1 90deg; Values angle value An <angle> specifying the angle to rotate the affected element through, around the Z axis. Equivalent to a rotate
() (2D rotation) function. x, y, or z axis name plus angle value The name of the axis you want to rotate the affected element around ("x", "y", or "z"), plus an <angle> specifying the angle to rotate the element through. Equivalent to a rotateX
()/rotateY
()/rotateZ
() (3D rotation) function. vector plus angle value Three <number>s representing an origin-centered vector that defines a line around w...
... none Specifies that no rotation should be applied. ...
scale - CSS: Cascading Style Sheets
scale: none; /* Single values */ /* values of more than 1 make the element grow */ scale: 2; /* values of less than 1 make the element shrink */ scale: 0.5; /* Two values */ scale: 2 0.5; /* Three values */ scale: 2 0.5 2; Values Single number value A <number> specifying a scale factor to make the affected element scale by the same factor along both the X and Y axes. ...
...ree values */ scale: 2 0.5 2; Values Single number value A <number> specifying a scale factor to make the affected element scale by the same factor along both the X and Y axes. Equivalent to a scale
() (2D scaling) function with a single value specified. Two length/percentage values Two <number>s that specify the X and Y axis scaling values (respectively) of a 2D scale. Equivalent to a scale
() (2D scaling) function with two values specified. Three length/percentage values Three <number>s that specify the X, Y, and Z axis scaling values (respectively) of a 3D scale. Equivalent to a scale3d
() (3D scaling) function. none Specifies that no scaling should be applied. Formal definition Initial valuenoneApplies totransformable elementsInheritednoComputed valueas specifiedAnimation type...
text-overflow - CSS: Cascading Style Sheets
is given, it specifies overflow behavior for the end of the line (the right end for left-to-right text, the left end for right-to-left text). If two values are given, the first specifies overflow behavior for the left end of the line, and the second specifies it for the right end of the line. Each value is specified as one of: one of the keyword values: clip, ellipsis, fade the function fade
(), which is passed a <length> or a <percentage> to control the fade distance a <string>. Values clip The default for this property. This keyword value will truncate the text at the limit of the content area, therefore the truncation can happen in the middle of a character. To clip at the transition between characters you can specify text-overflow as an empty string, if that is supported in y...
...7890 ,4321 1234567890 text-overflow: ',' ellipsis ,34... 1234567890 ,43... 1234567890 text-overflow: ',' '.' ,34. 1234567890 ,43. 1234567890 Specifications Specification Status Comment CSS Overflow Module Level 4 Added the values <string> and fade and the fade
() function CSS Overflow Module Level 3The definition of 'text-overflow' in that specification. Working Draft Initial definition A previous version of this interface reached the Candidate Recommendation status. As some not-listed-at-risk features needed to be removed, the spec was demoted to the Working Draft level, explaining why browsers implemented this property unprefixed, ...
<time-percentage> - CSS: Cascading Style Sheets
The <time-percentage> CSS data type represents a value that can be either a <time> or a <percentage>. Syntax Refer to the documentation for <time> and <percentage> for details of the individual syntaxes allowed by this type. Examples Use in calc
() Where a <time-percentage> is specified as an allowable type, this means that the percentage resolves to a time and therefore can be used in a calc
() expression. Valid percentages 50% +50% Optional plus sign -50% Negative percentages are not valid for all properties that accept percentages Invalid percentages 50 % Space not allowed between the space and the percentage sign Valid times 12s Positive integer -456ms Negative integer 4.3ms Non-integer 14mS The unit is case-insensitive, although c...
...d between the number and the unit. Specifications Specification Status Comment CSS Values and Units Module Level 4The definition of '<time-percentage>' in that specification. Editor's Draft CSS Values and Units Module Level 3The definition of '<time-percentage>' in that specification. Candidate Recommendation Defines <time-percentage>. Adds calc
() ...
translate - CSS: Cascading Style Sheets
Syntax /* Keyword values */ translate: none; /* Single values */ translate: 100px; translate: 50%; /* Two values */ translate: 100px 200px; translate: 50% 105px; /* Three values */ translate: 50% 105px 5rem; Values Single <length-percentage> value A <length> or <percentage> that specifies a 2D translation, with the same translation along both the X and Y axes. Equivalent to a translate
() (2D translation) function with a single value specified. Two <length-percentage> values Two <length> or <percentage> that specify the X and Y axis translation values (respectively) of a 2D translation. Equivalent to a translate
() (2D translation) function with two values specified. Three values Two <length-percentage> and single <length> values that specify the X, Y, and Z axis translation va...
... none Specifies that no translation should be applied. ...
Sets (set) - EXSLT
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The EXSLT Sets package offers functions that let you perform set manipulation. The namespace for these functions is http://exslt.org/sets. set:difference
()set:difference
() returns the difference between two node-sets. In other words, it returns a node-set whose nodes are in one node-set but not in the other.set:distinct
()set:distinct
() returns a subset of the nodes in the specified node-set, returning only nodes with unique string values.set:has-same-node
()set:has-same-node
() determines whether two node-sets have any nodes in common.set:intersection
()set:intersection
() returns the intersection of two node-sets. In other words, it returns a node-set containing all the nodes that exits in both nod...
...t
() returns a subset of the nodes in the specified node-set, returning only nodes with unique string values.set:has-same-node
()set:has-same-node
() determines whether two node-sets have any nodes in common.set:intersection
()set:intersection
() returns the intersection of two node-sets. In other words, it returns a node-set containing all the nodes that exits in both nodeSet1 and nodeSet2.set:leading
()set:leading
() returns the nodes in one node-set that come before the first node in the other node-set.set:trailing
()set:trailing
() returns the nodes in one node-set that come after the first node in the other node-set. ...
Adding captions and subtitles to HTML5 video - Developer guides
we need to build the menu that goes with it. This menu is built dynamically, so that languages can be added or removed later by simply editing the <track> elements within the video's markup. ...
...videoContainer.appendChild(subtitlesMenu); } This code creates a documentFragment, which is used to hold an unordered list containing our subtitles menu. First of all an option is added to allow the user to switch all subtitles off, and then buttons are added for each text track, reading the language and label from each one. ...
Media events - Developer guides
irefox. Other browsers might not fire this event. durationchange The metadata has loaded or changed, indicating a change in duration of the media. This is sent, for example, when the media has loaded enough that the duration is known. emptied The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load
() method is called to reload it. encrypted The user agent has encountered initialization data in the media data. ended Sent when playback completes. error Sent when an error occurs. The element's error attribute contains more information. See HTMLMediaElement.error for details. loadeddata The first frame of the media has finished loading. ...
...olume changes (both when the volume is set and when the muted attribute is changed). waiting Sent when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek). You can easily watch for these events, using code such as the following: var v = document.getElementsByTagName("video")[0]; v.addEventListener("seeked", function
() { v.play
(); }, true); v.currentTime = 10.0; This example fetches the first video element in the document and attaches an event listener to it, watching for the seeked event, which is sent whenever a seek operation completes. The listener simply calls the element's play
() method, which starts playback. Then, in line 3, the example sets the element's currentTime attribute to 10.0, which initiat...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
lue as "#0000ff" or "#00f". To make it 25% opaque, you can use "#0000ff44" or "#00f4". RGB functional notation RGB (Red/Green/Blue) functional notation, like hexadecimal string notation, represents colors using their red, green, and blue components (as well as, optionally, an alpha channel component for opacity). However, instead of using a string, the color is defined using the CSS function rgb
(). This function accepts as its input parameters the values of the red, green, and blue components and an optional fourth parameter, the value for the alpha channel. Legal values for each of these parameters are: red, green, and blue Each must be an <integer> value between 0 and 255 (inclusive), or a <percentage> from 0% to 100%. alpha The alpha channel is a number between 0.0 (fully transpa...
...n also specify a percentage where 0% is the same as 0.0 and 100% is the same as 1.0. For example, a bright red that's 50% opaque can be represented as rgb(255, 0, 0, 0.5) or rgb(100%, 0, 0, 50%). HSL functional notation Designers and artists often prefer to work using the HSL (Hue/Saturation/Luminosity) color method. On the web, HSL colors are represented using HSL functional notation. The hsl
() CSS function is very similar to the rgb
() function in usage otherwise. Figure 1. An HSL color cylinder. Hue defines the actual color based on the position along a circular color wheel representing the colors of the visible spectrum. Saturation is a percentage of how much of the way between being a shade of gray and having the maximum possible amount of the given hue. As the value of luminance ...
<a>: The Anchor element - HTML: Hypertext Markup Language
ref The URL that the hyperlink points to. Links are not restricted to HTTP-based URLs -- they can use any URL scheme supported by browsers: Sections of a page with fragment URLs Pieces of media files with media fragments Telephone numbers with tel: URLs Email addresses with mailto: URLs While web browsers may not support other URL schemes, web sites can with registerProtocolHandler
() hreflang Hints at the human language of the linked URL. No built-in functionality. Allowed values are the same as the global lang attribute. ping A space-separated list of URLs. When the link is followed, the browser will send POST requests with the body PING to the URLs. Typically for tracking. referrerpolicy How much of the referrer to send when following the link. See Referrer-Polic...
...canvas width="300" height="300"></canvas> CSS html { font-family: sans-serif; } canvas { background: #fff; border: 1px dashed; } a { display: inline-block; background: #69c; color: #fff; padding: 5px 10px; } JavaScript var canvas = document.querySelector('canvas'), c = canvas.getContext('2d'); c.fillStyle = 'hotpink'; function draw(x, y) { if (isDrawing) { c.beginPath
(); c.arc(x, y, 10, 0, Math.PI*2); c.closePath
(); c.fill
(); } } canvas.addEventListener('mousemove', event => draw(event.offsetX, event.offsetY) ); canvas.addEventListener('mousedown',
() => isDrawing = true); canvas.addEventListener('mouseup',
() => isDrawing = false); document.querySelector('a').addEventListener('click', event => event.target.href = canvas.toDataURL
() ); Resu...
<input type="number"> - HTML: Hypertext Markup Language
n/interactive-examples and send us a pull request. On browsers that don't support inputs of type number, a number input falls back to type text. Value Any floating-point number, or empty. Events change and input Supported common attributes autocomplete, list, placeholder, readonly IDL attributes list, value, valueAsNumber Methods select
(), stepUp
(), stepDown
() Value Any floating-point number, or empty. You can set a default value for the input by including a number inside the value attribute, like so: <input id="number" type="number" value="42"> Additional attributes In addition to the attributes commonly supported by all <input> types, inputs of type number support these attributes: Attribute Description...
...t: let metersInputGroup = document.querySelector('.metersInputGroup'); let feetInputGroup = document.querySelector('.feetInputGroup'); let metersInput = document.querySelector('#meters'); let feetInput = document.querySelector('#feet'); let inchesInput = document.querySelector('#inches'); let switchBtn = document.querySelector('input[type="button"]'); switchBtn.addEventListener('click', function
() { if(switchBtn.getAttribute('class') === 'meters') { switchBtn.setAttribute('class', 'feet'); switchBtn.value = 'Enter height in meters'; metersInputGroup.style.display = 'none'; feetInputGroup.style.display = 'block'; feetInput.setAttribute('required', ''); inchesInput.setAttribute('required', ''); metersInput.removeAttribute('required'); metersInput.value = ...
<input type="radio"> - HTML: Hypertext Markup Language
es on and off. Where multiple controls exist, radio buttons allow one to be selected out of them all, whereas checkboxes allow multiple values to be selected. Value A DOMString representing the value of the radio button. Events change and input Supported common attributes checked and value IDL attributes checked and value Methods select
() Value The value attribute is a DOMString containing the radio button's value. The value is never shown to the user by their user agent. Instead, it's used to identify which radio button in a group is selected. Defining a radio group A radio group is defined by giving each of radio buttons in the group the same name. Once a radio group is established, selecting any radio button in that g...
... Additional attributes In addition to the common attributes shared by all <input> elements, radio inputs support the following attributes: Attribute Description checked A Boolean indicating whether or not this radio button is the currently-selected item in the gr...
<input type="tel"> - HTML: Hypertext Markup Language
e tel fall back to being a standard text input. Value A DOMString representing a telephone number, or empty Events change and input Supported common attributes autocomplete, list, maxlength, minlength, pattern, placeholder, readonly, and size IDL attributes list, selectionStart, selectionEnd, selectionDirection, and value Methods select
(), setRangeText
(), setSelectionRange
() Value The <input> element's value attribute contains a DOMString that either represents a telephone number or is an empty string (""). Additional attributes In addition to the attributes that operate on all <input> elements regardless of their type, telephone number inputs support the following attributes: Attribute Description ...
...> </form> The JavaScript is relatively simple -- it contains an onchange event handler that, when the <select> value is changed, updates the <input> element's pattern, placeholder, and aria-label to suit the format of telephone numbers in that country/territory. ...
<input type="week"> - HTML: Hypertext Markup Language
s value. The Edge week control is somewhat more elaborate, opening up week and year pickers with sliding reels. Value A DOMString representing a week and year, or empty Events change and input Supported common attributes autocomplete, list, readonly, and step IDL attributes value, valueAsDate, valueAsNumber, and list. Methods select
(), stepDown
(), and stepUp
() Value A DOMString representing the value of the week/year entered into the input. The format of the date and time value used by this input type is described in Format of a valid week string in Date and time formats used in HTML. You can set a default value for the input by including a value inside the value attribute, like so: <label for="week">What week would ...
...year'); var weekSelect = document.querySelector('#fallbackWeek'); // hide fallback initially fallbackPicker.style.display = 'none'; fallbackLabel.style.display = 'none'; // test whether a new date input falls back to a text input or not var test = document.createElement('input'); try { test.type = 'week'; } catch (e) { console.log(e.description); } // if it does, run the code inside the if
() {} block if(test.type === 'text') { // hide the native picker and show the fallback nativePicker.style.display = 'none'; fallbackPicker.style.display = 'block'; fallbackLabel.style.display = 'block'; // populate the weeks dynamically populateWeeks
(); } function populateWeeks
() { // Populate the week select with 52 weeks for(var i = 1; i <= 52; i++) { var option = document.cr...
Access-Control-Allow-Credentials - HTTP
ials. Note that simple GET requests are not preflighted, and so if a request is made for a resource with credentials, if this header is not returned with the resource, the response is ignored by the browser and not returned to web content. The Access-Control-Allow-Credentials header works in conjunction with the XMLHttpRequest.withCredentials property or with the credentials option in the Request
() constructor of the Fetch API. For a CORS request with credentials, in order for browsers to expose the response to frontend JavaScript code, both the server (using the Access-Control-Allow-Credentials header) and the client (by setting the credentials mode for the XHR, Fetch, or Ajax request) must indicate that they're opting in to including credentials. Header type Response header ...
... Forbidden header name no Syntax Access-Control-Allow-Credentials: true Directives true The only valid value for this header is true (case-sensitive). If you don't need credentials, omit this header entirely (rather than setting its value to false). Examples Allow credentials: Access-Control-Allow-Credentials: true Using XHR with credentials: var xhr = new XMLHttpRequest
(); xhr.open('GET', 'http://example.com/', true); xhr.withCredentials = true; xhr.send(null); Using Fetch with credentials: fetch(url, { credentials: 'include' }) Specifications Specification Status Comment FetchThe definition of 'Access-Control-Allow-Credentials' in that specification. Living Standard Initial definition ...
CSP: style-src - HTTP
be used as a content source. 'self' Refers to the origin from which the protected document is being served, including the same URL scheme and port number. You must include the single quotes. Some browsers specifically exclude blob and filesystem from source directives. Sites needing to allow these content types can specify them using the Data attribute. 'unsafe-eval' Allows the use of eval
() and similar methods for creating code from strings. You must include the single quotes. 'unsafe-hashes' Allows enabling specific inline event handlers. If you only need to allow inline event handlers and not inline <script> elements or javascript: URLs, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' Allows the use of inline resources, such as inline <script> e...
...itespace matter, including leading or trailing whitespace. <style>#inline-style { background: red; }</style> Unsafe style expressions The 'unsafe-eval' source expression controls several style methods that create style declarations from strings. If 'unsafe-eval' isn't specified with the style-src directive, the following methods are blocked and won't have any effect: CSSStyleSheet.insertRule
() CSSGroupingRule.insertRule
() CSSStyleDeclaration.cssText Specifications Specification Status Comment Content Security Policy Level 3The definition of 'style-src' in that specification. Working Draft No changes. Content Security Policy Level 2The definition of 'style-src' in that specification. Recommendation Initial definition. ...
Feature-Policy: display-capture - HTTP
Syntax Feature-Policy: display-capture <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. ...
... Syntax Feature-Policy: display-capture <allowlist>; <allowlist> An allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: The feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. ...
Large-Allocation - HTTP
loaded at the top level of an user-opened or noopener-opened tab or window. It can occur in these situations: The document with the Large-Allocation header was loaded in an <iframe>. Firefox cannot move an iframe into a new process currently, so the document must load in the current process. ...
...This is for the same reason as above, namely that they can communicate and thus we cannot allow them to switch processes. A Large-Allocation header was ignored due to the document not being loaded out of process. ...
Protocol upgrade mechanism - HTTP
is to use WebSockets, which are always implemented by upgrading an HTTP or HTTPS connection. Keep in mind that if you're opening a new connection using the WebSocket API, or any library that does WebSockets, most or all of this is done for you. For example, opening a WebSocket connection is as simple as: webSocket = new WebSocket("ws://destination.server.ext", "optionalProtocol"); The WebSocket
() constructor does all the work of creating an initial HTTP/1.1 connection then handling the handshaking and upgrade process for you. You can also use the "wss://" URL scheme to open a secure WebSocket connection. If you need to create a WebSocket connection from scratch, you'll have to handle the handshaking process yourself. After creating the initial HTTP/1.1 session, you need to request the...
...ication, so this does not provide security. Instead, it helps to prevent non-WebSocket clients from inadvertently, or through misuse, requesting a WebSocket connection. In essence, then, this key simply confirms that "Yes, I really mean to open a WebSocket connection." This header is automatically added by clients that choose to use it; it cannot be added using the XMLHttpRequest.setRequestHeader
() method. Sec-WebSocket-Key: key key The key for this request to upgrade. The client adds this if it wishes to do so, and the server will include in the response a key of its own, which the client will validate before delivering the upgrade response to you. The server's response's Sec-WebSocket-Accept header will have a value computed based upon the specified key. Sec-WebSocket-Protocol Th...
CSS Houdini
has a style map which is accessible via its StylePropertyMap. A feature of CSS Houdini is the Worklet. With worklets, you can create modular CSS, requiring a single line of JavaScript to import configureable components: no pre-processors, post-processors or JavaScript frameworks needed. <script> CSS.paintWorklet.addModule('csscomponent.js'); </script> This added module contains registerPaint
() functions, which register completely configurable worklets. The CSS paint
() function parameters include the name of the worklet, along with optional parameters. The worklet also has access to the element's custom properties: they don't need to be passed as function arguments. li { background-image: paint(myComponent, stroke, 10px); --highlights: blue; --lowlights: green; } Note: With...
... API enables developers to write their own layout algorithms, like masonry or line snapping. It is not yet natively available. No guide or reference has currently been written for this API. CSS Painting API Developed to improve the extensibility of CSS -- allows developers to write JavaScript functions that can draw directly into an element's background, border, or content via the paint
() CSS function. CSS Painting API reference CSS Painting API guide Worklets An API for running scripts in various stages of the rendering pipeline independent of the main JavaScript execution environment. Worklets are conceptually similar to Web Workers, and are called by and extend the rendering engine. Worklets reference Other topics Related topics which may be of interest...
Expressions and operators - JavaScript
typeof (operand) The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional. ...
...te } Operator precedence The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses. The following table describes the precedence of operators, from highest to lowest. Operator precedence Operator type Individual operators member . ...
Introduction - JavaScript
-line input mode of the Web Console is great for quick testing of JavaScript expressions, but although you can execute multiple lines, it's not very convenient for that. For more complex JavaScript, you can use the multi-line line input mode. ...
...r that. For more complex JavaScript, you can use the multi-line line input mode. Hello world To get started with writing JavaScript, open the Web Console in multi-line mode, and write your first "Hello world" JavaScript code: (function
(){ "use strict"; /* Start of your code */ function greetMe(yourName) { alert('Hello ' + yourName); } greetMe('World'); /* End of your code */ })
(); Press Cmd+Enter or Ctrl+Enter (or click the Run button) to watch it unfold in your browser! In the following pages, this guide introduces you to the JavaScript syntax and language features, so that you will be able to write more complex applications. But for now, remember to always include the (function
(){"use strict"; before your code, and add })
(); to the end of your code. You will learn wh...
Loops and iteration - JavaScript
A do...while statement looks as follows: do statement while (condition); statement is always executed once before the condition is checked. (To execute multiple statements, use a block sta...
...rrupt the loop or continue its execution. The syntax of the labeled statement looks like the following: label : statement The value of label may be any JavaScript identifier that is not a reserved word. The statement that you identify with a label may be any statement. Example In this example, the label markLoop identifies a while loop. markLoop: while (theMark === true) { doSomething
(); } break statement Use the break statement to terminate a loop, switch, or in conjunction with a labeled statement. When you use break without a label, it terminates the innermost enclosing while, do-while, for, or switch immediately and transfers control to the following statement. When you use break with a label, it terminates the specified labeled statement. The syntax of the break sta...
Text formatting - JavaScript
mal digits following \u. '\u00A9' // "(C)" Unicode code point escapes New in ECMAScript 2015. With Unicode code point escapes, any character can be escaped using hexadecimal numbers so that it is possible to use Unicode code points up to 0x10FFFF. With simple Unicode escapes it is often necessary to write the surrogate halves separately to achieve the same result. See also String.fromCodePoint
() or String.prototype.codePointAt
(). '\u{2F804}' // the same with simple Unicode escapes '\uD87E\uDC04' String objects The String object is a wrapper around the string primitive data type. const foo = new String('foo'); // Creates a String object console.log(foo); // Displays: [String: 'foo'] typeof foo; // Returns 'object' You can call any of the methods of the String object on a string lit...
... string containing the single character U+1F600 "Emoji grinning face" will have length 2. Accessing the individual code units in such a string using brackets may have undesirable consequences such as the formation of strings with unmatched surrogate code units, in violation of the Unicode standard. (Examples should be added to this page after MDN bug 857438 is fixed.) See also String.fromCodePoint
() or String.prototype.codePointAt
(). A String object has a variety of methods: for example those that return a variation on the string itself, such as substring and toUpperCase. The following table summarizes the methods of String objects. Methods of String Method Description charAt, charCodeAt, codePointAt Return the character or character code at the specified ...
TypeError: property "x" is non-configurable and can't be deleted - JavaScript
urable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed. This error happens only in strict mode code. In non-strict code, the operation returns false. ...
...ntrols whether the property can be deleted from the object and whether its attributes (other than writable) can be changed. This error happens only in strict mode code. In non-strict code, the operation returns false. Examples Attempting to delete non-configurable properties Non-configurable properties are not super common, but they can be created using Object.defineProperty
() or Object.freeze
(). 'use strict'; var obj = Object.freeze({name: 'Elsa', score: 157}); delete obj.score; // TypeError 'use strict'; var obj = {}; Object.defineProperty(obj, 'foo', {value: 2, configurable: false}); delete obj.foo; // TypeError 'use strict'; var frozenArray = Object.freeze([0, 1, 2]); frozenArray.pop
(); // TypeError There are also a few non-configurable properties built into JavaScript. Maybe...
RangeError: repeat count must be non-negative - JavaScript
It has a count parameter indicating the number of times to repeat the string. It must be between 0 and less than positive Infinity and cannot be a negative number. The range of allowed values can be described like this: [0, +?). ...
...It has a count parameter indicating the number of times to repeat the string. It must be between 0 and less than positive Infinity and cannot be a negative number. The range of allowed values can be described like this: [0, +?). ...
TypeError: "x" is not a non-null object - JavaScript
null object (Firefox) TypeError: Property description must be an object: "x" (Chrome) TypeError: Invalid value used in weak set (Chrome) Error type TypeError What went wrong? An object is expected somewhere and wasn't provided. null is not an object and won't work. You must provide a proper object in the given situation. Examples Property descriptor expected When methods like Object.create
() or Object.defineProperty
() and Object.defineProperties
() are used, the optional descriptor parameter expects a property descriptor object. Providing no object (like just a number), will throw an error: Object.defineProperty({}, 'key', 1); // TypeError: 1 is not a non-null object Object.defineProperty({}, 'key', null); // TypeError: null is not a non-null object A valid property descriptor obj...
...ror: 1 is not a non-null object Object.defineProperty({}, 'key', null); // TypeError: null is not a non-null object A valid property descriptor object might look like this: Object.defineProperty({}, 'key', { value: 'foo', writable: false }); WeakMap and WeakSet objects require object keys WeakMap and WeakSet objects store object keys. You can't use other types as keys. var ws = new WeakSet
(); ws.add('foo'); // TypeError: "foo" is not a non-null object Use objects instead: ws.add({foo: 'bar'}); ws.add(window); ...
TypeError: can't delete non-configurable array element - JavaScript
rtening an array, the elements beyond the new array length will be deleted, which failed in this situation. The configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed. Usually, properties in an object created by an array initializer are configurable. However, for example, when using Object.defineProperty
(), the property isn't configurable by default. Examples Non-configurable properties created by Object.defineProperty The Object.defineProperty
() creates non-configurable properties by default if you haven't specified them as configurable. var arr = []; Object.defineProperty(arr, 0, {value: 0}); Object.defineProperty(arr, 1, {value: "1"}); arr.length = 1; // TypeError: can't delete non-configur...
...ject.defineProperty(arr, 1, {value: "1"}); arr.length = 1; // TypeError: can't delete non-configurable array element You will need to set the elements as configurable, if you intend to shorten the array. var arr = []; Object.defineProperty(arr, 0, {value: 0, configurable: true}); Object.defineProperty(arr, 1, {value: "1", configurable: true}); arr.length = 1; Seal-ed Arrays The Object.seal
() function marks all existing elements as non-configurable. var arr = [1,2,3]; Object.seal(arr); arr.length = 1; // TypeError: can't delete non-configurable array element You either need to remove the Object.seal
() call, or make a copy of it. In case of a copy, shortening the copy of the array does not modify the original array length. var arr = [1,2,3]; Object.seal(arr); // Copy the initial ...
TypeError: "x" is read-only - JavaScript
Error type TypeError What went wrong? The global variable or object property that was assigned to is a read-only property. (Technically, it is a non-writable data property.) This error happens only in strict mode code. In non-strict code, the assignment is silently ignored. Examples Invalid cases Read-only properties are not super common, but they can be created using Object.defineProperty
() or Object.freeze
(). 'use strict'; var obj = Object.freeze({name: 'Elsa', score: 157}); obj.score = 0; // TypeError 'use strict'; Object.defineProperty(this, 'LUNG_COUNT', {value: 2, writable: false}); LUNG_COUNT = 3; // TypeError 'use strict'; var frozenArray = Object.freeze([0, 1, 2]); frozenArray[0]++; // TypeError There are also a few read-only properties built into JavaScript. Maybe y...
...1, 2]); frozenArray[0]++; // TypeError There are also a few read-only properties built into JavaScript. Maybe you tried to redefine a mathematical constant. 'use strict'; Math.PI = 4; // TypeError Sorry, you can't do that. ...
TypeError: Reduce of empty array with no initial value - JavaScript
The JavaScript exception "reduce of empty array with no initial value" occurs when a reduce function is used. Message TypeError: reduce of empty array with no initial value Error type TypeError What went wrong? In JavaScript, there are several reduce functions: Array.prototype.reduce
(), Array.prototype.reduceRight
() and TypedArray.prototype.reduce
(), TypedArray.prototype.reduceRight
()). These functions optionally take an initialValue (which will be used as the first argument to the first call of the callback). However, if no initial value is provided, it will use the first element of the Array or TypedArray as the initial value. This error is raised when an empty array is provided because no initial value can be returned in that case. Examples Invalid cases This problem app...
...sed as the first argument to the first call of the callback). However, if no initial value is provided, it will use the first element of the Array or TypedArray as the initial value. This error is raised when an empty array is provided because no initial value can be returned in that case. Examples Invalid cases This problem appears frequently when combined with a filter (Array.prototype.filter
(), TypedArray.prototype.filter
()) which will remove all elements of the list. Thus leaving none to be used as the initial value. var ints = [0, -1, -2, -3, -4, -5]; ints.filter(x => x > 0) // removes all elements .reduce((x, y) => x + y) // no more elements to use for the initial value. Similarly, the same issue can happen if there is a typo in a selector, or an unexpected number o...
RangeError: repeat count must be less than infinity - JavaScript
It has a count parameter indicating the number of times to repeat the string. It must be between 0 and less than positive Infinity and cannot be a negative number. The range of allowed values can be described like this: [0, +?). ...
...It has a count parameter indicating the number of times to repeat the string. It must be between 0 and less than positive Infinity and cannot be a negative number. The range of allowed values can be described like this: [0, +?). ...
SyntaxError: "use strict" not allowed in function with non-simple parameters - JavaScript
directive outside of the function: 'use strict'; function sum(a = 1, b = 2) { return a + b; } Function expression A function expression can use yet another workaround: var sum = function sum([a, b]) { // SyntaxError: "use strict" not allowed in function with destructuring parameter 'use strict'; return a + b; }; This can be converted to the following expression: var sum = (function
() { 'use strict'; return function sum([a, b]) { return a + b; }; })
(); Arrow function If an arrow function needs to access the this variable, you can use the arrow function as the enclosing function: var callback = (...args) => { // SyntaxError: "use strict" not allowed in function with rest parameter 'use strict'; return this.run(args); }; This can be converted to the followi...
...tion sum([a, b]) { return a + b; }; })
(); Arrow function If an arrow function needs to access the this variable, you can use the arrow function as the enclosing function: var callback = (...args) => { // SyntaxError: "use strict" not allowed in function with rest parameter 'use strict'; return this.run(args); }; This can be converted to the following expression: var callback = (
() => { 'use strict'; return (...args) => { return this.run(args); }; })
(); ...
TypeError: invalid 'instanceof' operand 'x' - JavaScript
is not callable (Chrome) Error type TypeError What went wrong? The instanceof operator expects the right hand side operands to be a constructor object, i.e. an object which has a prototype property and is callable. Examples instanceof vs typeof "test" instanceof ""; // TypeError: invalid 'instanceof' operand "" 42 instanceof 0; // TypeError: invalid 'instanceof' operand 0 function Foo
() {} var f = Foo
(); // Foo
() is called and returns undefined var x = new Foo
(); x instanceof f; // TypeError: invalid 'instanceof' operand f x instanceof x; // TypeError: x is not a function To fix these errors, you will either need to replace the instanceof operator with the typeof operator, or to make sure you use the function name, instead of the result of its evaluation. ...
...); x instanceof f; // TypeError: invalid 'instanceof' operand f x instanceof x; // TypeError: x is not a function To fix these errors, you will either need to replace the instanceof operator with the typeof operator, or to make sure you use the function name, instead of the result of its evaluation. typeof "test" == "string"; // true typeof 42 == "number" // true function Foo
() {} var f = Foo; // Do not call Foo. var x = new Foo
(); x instanceof f; // true x instanceof Foo; // true ...
AggregateError - JavaScript
Instance properties AggregateError.prototype.message Error message, defaults to "". AggregateError.prototype.name Error name, defaults to AggregateError. ...
... Instance properties AggregateError.prototype.message Error message, defaults to "". AggregateError.prototype.name Error name, defaults to AggregateError. ...
get Array[@@species] - JavaScript
turn value The Array constructor. Description The species accessor property returns the default constructor for Array objects. Subclass constructors may override it to change the constructor assignment. ...
... // function Array
() Species in derived objects In a derived collection object (e.g. your custom array MyArray), the MyArray species is the MyArray constructor. However, you might want to overwrite this, in order to return parent Array objects in your derived class methods: class MyArray extends Array { // Overwrite MyArray species to the parent Array constructor static get [Symbol.species]
() { return Array; } } Specifications Specification ECMAScript (ECMA-262)The definition of 'get Array [ @@species ]' in that specification. ...
Array.prototype[@@unscopables] - JavaScript
The @@unscopable symbol property contains property names that were not included in the ECMAScript standard prior to the ES2015 version. These properties are excluded from with statement bindings. Description The default array properties that are excluded from with bindings are: copyWithin
() entries
() fill
() find
() findIndex
() includes
() keys
() values
() See Symbol.unscopables for how to set unscopables for your own objects. ...
...copables for how to set unscopables for your own objects. Property attributes of Array.prototype[@@unscopables] Writable no Enumerable no Configurable yes Examples Use in with environments 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(Arra...
get ArrayBuffer[@@species] - JavaScript
or. Description The species accessor property returns the default constructor for ArrayBuffer objects. Subclass constructors may over-ride it to change the constructor assignment. Examples Species in ordinary objects The species property returns the default constructor function, which is the ArrayBuffer constructor for ArrayBuffer objects: ArrayBuffer[Symbol.species]; // function ArrayBuffer
() Species in derived objects In a derived collection object (e.g. your custom array buffer MyArrayBuffer), the MyArrayBuffer species is the MyArrayBuffer constructor. However, you might want to overwrite this, in order to return parent ArrayBuffer objects in your derived class methods: class MyArrayBuffer extends ArrayBuffer { // Overwrite MyArrayBuffer species to the parent ArrayBuffer constr...
...derived collection object (e.g. your custom array buffer MyArrayBuffer), the MyArrayBuffer species is the MyArrayBuffer constructor. However, you might want to overwrite this, in order to return parent ArrayBuffer objects in your derived class methods: class MyArrayBuffer extends ArrayBuffer { // Overwrite MyArrayBuffer species to the parent ArrayBuffer constructor static get [Symbol.species]
() { return ArrayBuffer; } } Specifications Specification ECMAScript (ECMA-262)The definition of 'get ArrayBuffer [ @@species ]' in that specification. ...
ArrayBuffer - JavaScript
represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".You cannot directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer. The ArrayBuffer
() constructor creates a new ArrayBuffer of the given length in bytes. You can also get an array buffer from existing data, for example from a Base64 string or from a local file. Constructor ArrayBuffer
() Creates a new ArrayBuffer object. Static properties get ArrayBuffer[@@species] The constructor function that is used to create derived objects. Static methods ArrayBuffer.isView(arg...
...s. Static methods ArrayBuffer.isView(arg) Returns true if arg is one of the ArrayBuffer views, such as typed array objects or a DataView. Returns false otherwise. Instance properties ArrayBuffer.prototype.byteLength The read-only size, in bytes, of the ArrayBuffer. This is established when the array is constructed and cannot be changed. Instance methods ArrayBuffer.prototype.slice
() Returns a new ArrayBuffer whose contents are a copy of this ArrayBuffer's bytes from begin (inclusive) up to end (exclusive). If either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning. Examples Creating an ArrayBuffer In this example, we create a 8-byte buffer with a Int32Array view referring to the buffer: const buffer = new Array...
Boolean - JavaScript
= new String('Hello'); // string object var s = Boolean(myString); // initial value of true Do not use a Boolean object in place of a Boolean primitive. Note: When the non-standard property document.all is used as an argument for this constructor, the result is a Boolean object with the value false. This property is legacy and non-standard and should not be used. Constructor Boolean
() Creates a new Boolean object. Instance methods Boolean.prototype.toString
() Returns a string of either true or false depending upon the value of the object. Overrides the Object.prototype.toString
() method. Boolean.prototype.valueOf
() Returns the primitive value of the Boolean object. Overrides the Object.prototype.valueOf
() method. Examples Creating Boolean objects with an initial va...
...ce methods Boolean.prototype.toString
() Returns a string of either true or false depending upon the value of the object. Overrides the Object.prototype.toString
() method. Boolean.prototype.valueOf
() Returns the primitive value of the Boolean object. Overrides the Object.prototype.valueOf
() method. ...
Date.prototype[@@toPrimitive] - JavaScript
The [@@toPrimitive]
() method converts a Date object to a primitive value. Syntax Date
()[Symbol.toPrimitive](hint); Return value The primitive value of the given Date object. Depending on the argument, the method can return either a string or a number. Description The [@@toPrimitive]
() method of the Date object returns a primitive value, that is either of type number or of type string. If hint is "string" or "default", [@@toPrimitive]
() tries to call the toString method. If the toString property does not exist, it tries to call the valueOf method and if the valueOf does not exist either, [@@toPrimitive]
() throws a TypeError. If hint is "number", [@@toPrimitive]
() first tries to call valueOf, and if that fails, it calls toString. ...
...pe string. If hint is "string" or "default", [@@toPrimitive]
() tries to call the toString method. If the toString property does not exist, it tries to call the valueOf method and if the valueOf does not exist either, [@@toPrimitive]
() throws a TypeError. If hint is "number", [@@toPrimitive]
() first tries to call valueOf, and if that fails, it calls toString. JavaScript calls the [@@toPrimitive]
() method to convert an object to a primitive value. You rarely need to invoke the [@@toPrimitive]
() method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. Examples Returning date primitives const testDate = new Date(1590757517834); // "Date Fri May 29 2020 14:05:17 GMT+0100 (British Summer Time)" testDate[Symbol.toPrimitive]('string...
get Set[@@species] - JavaScript
cessor property returns the Set constructor. Description The species accessor property returns the default constructor for Set objects. Subclass constructors may override it to change the constructor assignment. ...
...Set[Symbol.species]; // function Set
() Species in derived objects In a derived collection object (e.g. your custom set MySet), the MySet species is the MySet constructor. However, you might want to overwrite this, in order to return parent Set objects in your derived class methods: class MySet extends Set { // Overwrite MySet species to the parent Set constructor static get [Symbol.species]
() { return Set; } } Specifications Specification ECMAScript (ECMA-262)The definition of 'get Set [ @@species ]' in that specification. ...
Symbol.prototype[@@toPrimitive] - JavaScript
The [@@toPrimitive]
() method converts a Symbol object to a primitive value. Syntax Symbol
()[Symbol.toPrimitive](hint) Return value The primitive value of the specified Symbol object. Description The [@@toPrimitive]
() method of Symbol returns the primitive value of a Symbol object as a Symbol data type. The hint argument is not used. JavaScript calls the [@@toPrimitive]
() method to convert an object to a primitive value. You rarely need to invoke the [@@toPrimitive]
() method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ...
... Symbol data type. The hint argument is not used. JavaScript calls the [@@toPrimitive]
() method to convert an object to a primitive value. You rarely need to invoke the [@@toPrimitive]
() method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. Examples Using @@toPrimitive const sym = Symbol("example"); sym === sym[Symbol.toPrimitive]
(); // true Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.prototype.@@toPrimitive' in that specification. ...
Symbol.asyncIterator - JavaScript
cIterator key. Property attributes of Symbol.asyncIterator Writable no Enumerable no Configurable no Examples User-defined Async Iterables You can define your own async iterable by setting the [Symbol.asyncIterator] property on an object. ...
... Writable no Enumerable no Configurable no Examples User-defined Async Iterables You can define your own async iterable by setting the [Symbol.asyncIterator] property on an object. const myAsyncIterable = { async* [Symbol.asyncIterator]
() { yield "hello"; yield "async"; yield "iteration!"; } }; (async
() => { for await (const x of myAsyncIterable) { console.log(x); // expected output: // "hello" // "async" // "iteration!" } })
(); When creating an API, remember that async iterables are designed to represent something iterable -- like a stream of data or a list --, not to completely replace callbacks and events in most situations. Built-in...
Symbol.isConcatSpreadable - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Description The @@isConcatSpreadable symbol (Symbol.isConcatSpreadable) can be defined as an own or inherited property and its value is a boolean. ...
...g in these cases. For array-like objects, the default behavior is no spreading or flattening. Symbol.isConcatSpreadable can force flattening in these cases. ...
Symbol.replace - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
... 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. ...
Symbol.species - JavaScript
r property allows subclasses to override the default constructor for objects. Property attributes of Symbol.species Writable no Enumerable no Configurable no Examples Using species You might want to return Array objects in your derived array class MyArray. ...
... You might want to return Array objects in your derived array class MyArray. For example, when using methods such as map
() that return the default constructor, you want these methods to return a parent Array object, instead of the MyArray object. The species symbol lets you do this: class MyArray extends Array { // Overwrite species to the parent Array constructor static get [Symbol.species]
() { return Array; } } let a = new MyArray(1,2,3); let mapped = a.map(x => x * x); console.log(mapped instanceof MyArray); // false console.log(mapped instanceof Array); // true Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.species' in that specification. ...
TypeError - JavaScript
ion could not be performed, typically (but not exclusively) when a value is not of the expected type. A TypeError may be thrown when: an operand or argument passed to a function is incompatible with the type expected by that operator or function; or when attempting to modify a value that cannot be changed; or when attempting to use a value in an inappropriate way. Constructor TypeError
() Creates a new TypeError object. Instance properties TypeError.prototype.message Error message. Although ECMA-262 specifies that TypeError should provide its own message property, in SpiderMonkey, it inherits Error.prototype.message. TypeError.prototype.name Error name. Inherited from Error. TypeError.prototype.fileName Path to file that raised this error. Inherited from Error. TypeErr...
...peError.prototype.fileName Path to file that raised this error. Inherited from Error. TypeError.prototype.lineNumber Line number in file that raised this error. Inherited from Error. TypeError.prototype.columnNumber Column number in line that raised this error. Inherited from Error. TypeError.prototype.stack Stack trace. Inherited from Error. ...
get TypedArray[@@species] - JavaScript
on The species accessor property returns the default constructor for typed array objects. Subclass constructors may over-ride it to change the constructor assignment. Examples Species in ordinary objects The species property returns the default constructor function, which is one of the typed array constructors for a given typed array object: Int8Array[Symbol.species]; // function Int8Array
() Uint8Array[Symbol.species]; // function Uint8Array
() Float32Array[Symbol.species]; // function Float32Array
() Species in derived objects In a derived collection object (e.g. your custom typed array MyTypedArray), the MyTypedArray species is the MyTypedArray constructor. However, you might want to overwrite this, in order to return a parent typed array object in your derived class methods: c...
... In a derived collection object (e.g. your custom typed array MyTypedArray), the MyTypedArray species is the MyTypedArray constructor. However, you might want to overwrite this, in order to return a parent typed array object in your derived class methods: class MyTypedArray extends Uint8Array { // Overwrite MyTypedArray species to the parent Uint8Array constructor static get [Symbol.species]
() { return Uint8Array; } } Specifications Specification ECMAScript (ECMA-262)The definition of 'get %TypedArray% [ @@species ]' in that specification. ...
WebAssembly.Instance.prototype.exports - JavaScript
donly property of the WebAssembly.Instance object prototype returns an object containing as its members all the functions exported from the WebAssembly module instance, to allow them to be accessed and used by JavaScript. ...
... Specifications Specification WebAssembly JavaScript InterfaceThe definition of 'WebAssembly.Instance: exports' in that specification. Browser compatibility The compatibility table on this page is generated from structured data. ...
Logical AND (&&) - JavaScript
falsy expression) && expr is short-circuit evaluated to the falsy expression; Short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). This happens because the value of the operator is already determined after the evaluation of the first operand. ...
...o the falsy expression; Short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). This happens because the value of the operator is already determined after the evaluation of the first operand. See example: function A
(){ console.log('called A'); return false; } function B
(){ console.log('called B'); return true; } console.log( A
() && B
() ); // logs "called A" due to the function call, // then logs false (which is the resulting value of the operator) Operator precedence The following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence). true || false && false // returns tru...
Logical OR (||) - JavaScript
ruthy expression) || expr is short-circuit evaluated to the truthy expression. Short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). This happens because the value of the operator is already determined after the evaluation of the first operand. ...
... the truthy expression. Short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). This happens because the value of the operator is already determined after the evaluation of the first operand. See example: function A
(){ console.log('called A'); return false; } function B
(){ console.log('called B'); return true; } console.log( B
() || A
() ); // logs "called B" due to the function call, // then logs true (which is the resulting value of the operator) Operator precedence The following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence). true || false && false // returns true...
Property accessors - JavaScript
e.log(object.1); // SyntaxError Here, the method named createElement is retrieved from document and is called. document.createElement('pre') If you use a method for a numeric literal, and the numeric literal has no exponent and no decimal point, you should leave white-space(s) before the dot preceding the method call, so that the dot is not interpreted as a decimal point. 77 .toExponential
() // or 77 .toExponential
() // or ;(77).toExponential
() // or 77..toExponential
() // or 77.0.toExponential
() // because 77. === 77.0, no ambiguity Bracket notation In the object[property_name] syntax, the property_name is just a string or Symbol. So, it can be any string, including '1foo', '!bar!', or even ' ' (a space). const variable = object[property_name] object[property_name] = value; This...
...ring would be "[object Object]". Method binding A method is not bound to the object that it is a method of. Specifically, this is not fixed in a method. Put another way, this does not necessarily refer to the object containing a method. Instead, this is "passed" by the function call. See method binding. Examples Bracket notation vs. eval JavaScript novices often make the mistake of using eval
() where the bracket notation can be used instead. For example, the following syntax is often seen in many scripts. x = eval('document.forms.form_name.elements.' + strFormControl + '.value') eval
() is slow and should be avoided whenever possible. Also, strFormControl would have to hold an identifier, which is not required for names and ids of form controls. It is better to use bracket notation i...
void operator - JavaScript
he resolution of the expression following the void operator: void 2 == '2'; // (void 2) == '2', returns false void (2 == '2'); // void (2 == '2'), returns undefined Examples Immediately Invoked Function Expressions When using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration. void function iife
() { console.log("Executed!"); }
(); // Output: "Executed!" Executing the above function without the void keyword will result in an Uncaught SyntaxError. JavaScript URIs When a browser follows a javascript: URI, it evaluates the code in the URI and then replaces the contents of the page with the returned value, unless the returned value is undefined. The void operator can be used to return u...
...a short-hand braceless syntax that returns an expression. This can cause unintended side effects by returning the result of a function call that previously returned nothing. To be safe, when the return value of a function is not intended to be used, it can be passed to the void operator to ensure that (for example) changing APIs do not cause arrow functions' behaviors to change. button.onclick =
() => void doSomething
(); This ensures the return value of doSomething changing from undefined to true will not change the behavior of this code. Specifications Specification ECMAScript (ECMA-262)The definition of 'The void Operator' in that specification. ...
empty - JavaScript
let i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ; console.log(arr); // [0, 0, 0] Unintentional usage It is a good idea to comment intentional use of the empty statement, as it is not really obvious to distinguish from a normal semicolon. ...
...y obvious to distinguish from a normal semicolon. In the following example, the usage is probably not intentional: if (condition); // Caution, this "if" does nothing! killTheUniverse
() // So this always gets executed!!! In the next example, an if...else statement without curly braces ({}) is used. If three is true, nothing will happen, four does not matter, and also the launchRocket
() function in the else case will not be executed. if (one) doOne
(); else if (two) doTwo
(); else if (three) ; // nothing here else if (four) doFour
(); else launchRocket
(); Specifications Specification ECMAScript (ECMA-262)The definition of 'Empty statement' in that specification. ...
label - JavaScript
ak statements can make use of non-loop labels. foo: { console.log('face'); break foo; console.log('this will not be executed'); } console.log('swap'); // this will log: // "face" // "swap" Labeled function declarations Starting with ECMAScript 2015, labeled function declarations are now standardized for non-strict code in the web compatibility annex of the specification. ...
...sole.log('this will not be executed'); } console.log('swap'); // this will log: // "face" // "swap" Labeled function declarations Starting with ECMAScript 2015, labeled function declarations are now standardized for non-strict code in the web compatibility annex of the specification. L: function F
() {} In strict mode code, however, this will throw a SyntaxError: 'use strict'; L: function F
() {} // SyntaxError: functions cannot be labelled Generator functions can neither be labeled in strict code, nor in non-strict code: L: function* F
() {} // SyntaxError: generator functions cannot be labelled Specifications Specification ECMAScript (ECMA-262)The definition of 'Labelled statement' in that specification. ...
return - JavaScript
rn; a + b; The console will warn "unreachable code after return statement". Starting with Firefox 40, a warning is shown in the console if unreachable code is found after a return statement. To avoid this problem (to prevent ASI), you could use parentheses: return ( a + b ); Examples Interrupt a function A function immediately stops at the point where return is called. ...
...theses: return ( a + b ); Examples Interrupt a function A function immediately stops at the point where return is called. function counter
() { for (var count = 1; ; count++) { // infinite loop console.log(count + 'A'); // until 5 if (count === 5) { return; } console.log(count + 'B'); // until 4 } console.log(count + 'C'); // never appears } counter
(); // Output: // 1A // 1B // 2A // 2B // 3A // 3B // 4A // 4B // 5A Returning a function See also the article about Closures. function magic
() { return function calc(x) { return x * 42; }; } var answer = magic
(); answer(1337); // 56154 Specifications Specification ECMAScript (ECMA-262)The definition of 'Return statement' in that specification. ...
Authoring MathML - MathML
io/mathml-warning.js/mpadded-min.js"></script> If you don't want to use this link to GitHub but instead to integrate these polyfills or others in your own project, you might need the detection scripts to verify the level of MathML support. ...
...he level of MathML support. For example the following function verifies the MathML support by testing the mspace element (you may replace mspace with mpadded): function hasMathMLSupport
() { var div = document.createElement("div"), box; div.innerHTML = "<math><mspace height='23px' width='77px'/></math>"; document.body.appendChild(div); box = div.firstChild.firstChild.getBoundingClientRect
(); document.body.removeChild(div); return Math.abs(box.height - 23) <= 1 && Math.abs(box.width - 77) <= 1; } Alternatively, the following UA string sniffing will allow to detect the rendering engines with native MathML support (Gecko and WebKit). Note that UA string sniffing is not the most reliable method and might break from version to version: var ua = navigator.userAgent; var isGecko = u...
Web video codec guide - Web media technologies
Maintaining organization Google Specification RFC 6386 Licensing Open and free of royalties and any other licensing requirements [1] Edge support for VP8 requires the use of Media Source Extensions. [2] Safari only supports VP8 in WebRTC connections. [3] Firefox only supports VP8 in MSE when no H.264 hardware decoder is available. Use MediaSource.isTypeSupported
() to check for availability. VP9 Video Processor 9 (VP9) is the successor to the older VP8 standard developed by Google. Like VP8, VP9 is entirely open and royalty-free. Its encoding and decoding performance is comparable to or slightly faster than that of AVC, but with better quality. VP9's encoded video quality is comparable to that of HEVC at similar bit rates. VP9's main profile supports onl...
... Container support MP4, Ogg, WebM RTP / WebRTC compatible Yes Supporting/Maintaining organization Google Specification https://www.webmproject.org/vp9/ Licensing Open and free of royalties and any other licensing requirements [1] Firefox only supports VP8 in MSE when no H.264 hardware decoder is available. Use MediaSource.isTypeSupported
() to check for availability. Choosing a video codec The decision as to which codec or codecs to use begins with a series of questions to prepare yourself: Do you wish to use an open format, or are proprietary formats also to be considered? Do you have the resources to produce more than one format for each of your videos? The ability to provide a fallback option vastly simplifies the decision-...
The "codecs" parameter in common media types - Web media technologies
avc1.4d002a" An MPEG-4 file containing AVC (H.264) video, Main Profile, Level 4.2. As is the case with any MIME type parameter, codecs must be changed to codecs* (note the asterisk character, *) if any of the properties of the codec use special characters which must be percent-encoded per RFC 2231, section 4: MIME Parameter Value and Encoded Word Extensions. You can use the JavaScript encodeURI
() function to encode the parameter list; similarly, you can use decodeURI
() to decode a previously encoded parameter list. When the codecs parameter is used, the specified list of codecs must include every codec used for the contents of the file. The list may also contain codecs not present in the file.= Codec options by container The containers below support extended codec options in their co...
...n use the codecs parameter in a few situations. Firstly, you can use it with the <source> element when creating an <audio> or <video> element, in order to establish a group of options for the browser to choose from when selecting the format of the media to present to the user in the element. You can also use the codecs parameter when specifying a MIME media type to the MediaSource.isTypeSupported
() method; this method returns a Boolean which indicates whether or not the media is likely to work on the current device. ...
Progressive web app structure - Progressive web apps (PWAs)
content').innerHTML = content; Next, it registers a service worker: if('serviceWorker' in navigator) { navigator.serviceWorker.register('/pwa-examples/js13kpwa/sw.js'); }; The next code block requests permission for notifications when a button is clicked: var button = document.getElementById("notifications"); button.addEventListener('click', function(e) { Notification.requestPermission
().then(function(result) { if(result === 'granted') { randomNotification
(); } }); }); The last block creates notifications that display a randomly-selected item from the games list: function randomNotification
() { var randomItem = Math.floor(Math.random
()*games.length); var notifTitle = games[randomItem].name; var notifBody = 'Created by '+games[randomIt...
..., function(e) { e.respondWith( caches.match(e.request).then(function(r) { console.log('[Service Worker] Fetching resource: '+e.request.url); return r || fetch(e.request).then(function(response) { return caches.open(cacheName).then(function(cache) { console.log('[Service Worker] Caching new resource: '+e.request.url); cache.put(e.request, response.clone
()); return response; }); }); }) ); }); The JavaScript data The games data is present in the data folder in a form of a JavaScript object (games.js): var games = [ { slug: 'lost-in-cyberspace', name: 'Lost in Cyberspace', author: 'Zosia and Bartek', twitter: 'bartaz', website: '', github: 'github.com/bartaz/lost-in-...
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
d:lime;"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam. </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing <b class="target">elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</b> Ut enim ad minim veniam. ...
...is establishes a clipping area made of a circle and rectangle, assigns it the ID #clipping-path-1, then references it in the CSS. The clip path can be assigned to any element with the target class. You can make changes to the SVG in real time and see them immediately affect the rendering of the HTML. For example, you can resize the circle in the clip path established above: function toggleRadius
() { var circle = document.getElementById("circle"); circle.r.baseVal.value = 0.40 - circle.r.baseVal.value; } Example: Filtering This demonstrates applying a filter to HTML content using SVG. It establishes several filters, which are applied with CSS to three elements in both the normal and mouse hover states. <p class="target" style="background: lime;"> Lorem ipsum dolor sit amet, co...
clip-path - SVG: Scalable Vector Graphics
ft: Apply a custom defined clipping path --> <rect x="1" y="1" width="8" height="8" stroke="green" clip-path="url(#myClip)" /> <!-- Top-right: Apply a CSS basic shape on a fill-box geometry. This is the same as having a custom clipping path with a clipPathUnits set to objectBoundingBox --> <rect x="11" y="1" width="8" height="8" stroke="green" clip-path="circle
() fill-box" /> <!-- Bottom-left --> <rect x="1" y="11" width="8" height="8" stroke="green" clip-path="circle
() stroke-box" /> <!-- Bottom-right: Apply a CSS basic shape on a view-box geometry. This is the same as having a custom clipping path with a clipPathUnits set to userSpaceOnUse --> <rect x="11" y="11" width="8" height="8" stroke="green" clip-path="circ...
...ill-box" /> <!-- Bottom-left --> <rect x="1" y="11" width="8" height="8" stroke="green" clip-path="circle
() stroke-box" /> <!-- Bottom-right: Apply a CSS basic shape on a view-box geometry. ...
clip - SVG: Scalable Vector Graphics
The value of auto defines a clipping path along the bounds of the viewport created by the given element. ...
...0" width="10" height="10" clip="auto"> <circle cx="5" cy="5" r="4" stroke="green" /> </svg> <!-- Rect(top, right, bottom, left) clipping --> <svg x="10" width="10" height="10" clip="rect(1, 9, 8, 2)"> <circle cx="5" cy="5" r="4" stroke="green" /> </svg> </svg> Usage notes Warning: This property is deprecated. Use clip-path instead. Value auto | rect
() Default value auto Animatable Yes The value auto defines a clipping path along the bounds of the viewport created by the given element.The value rect
() defines a clipping rectangle following the following syntax: rect(<top>, <right>, <bottom>, <left>). The <top> and <bottom> values specify offsets from the top border edge of the element viewport, while <right> and <...
textLength - SVG: Scalable Vector Graphics
/span> </div> The <input> element, of type "range", is used to create the slider control the user will manipulate to change the width of the text. A <span> element of ID "widthDisplay" is provided to display the current width value. JavaScript Finally, let's have a look at the JavaScript code. ...
...ue = baseLength; widthSlider.addEventListener("input", function(event) { textElement.textLength.baseVal.newValueSpecifiedUnits( SVGLength.SVG_LENGTHTYPE_PX, widthSlider.valueAsNumber); widthDisplay.innerText = widthSlider.value; }, false); widthSlider.dispatchEvent(new Event("input")); After fetching the element references, an EventListener is established by calling addEventListener
() on the slider control, to receive any input events which occur. These events will be sent any time the slider's value changes, even if the user hasn't stopped moving it, so we can responsively adjust the text width. When an "input" event occurs, we call SVGLength.newValueSpecifiedUnits
() to set the value of textLength to the slider's new value, using the SVGLength interface's SVG_LENGTHTYPE_PX u...
<script> - SVG: Scalable Vector Graphics
G's script element is equivalent to the HTML <script> element, it has some discrepancies, like it uses the href attribute instead of src and it doesn't support ECMAScript modules so far (See browser compatibility below for details) html,body,svg { height:100% } <svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <script> // <![CDATA[ window.addEventListener('DOMContentLoaded',
() => { function getColor
() { const R = Math.round(Math.random
() * 255).toString(16).padStart(2,'0') const G = Math.round(Math.random
() * 255).toString(16).padStart(2,'0') const B = Math.round(Math.random
() * 255).toString(16).padStart(2,'0') return `#${R}${G}${B}` } document.querySelector('circle').addEventListener('click', (e) => { e.target.style.fill = ...
... Value type: <string>; Default value: ?; Animatable: yes href The URL to the script to load. ...
SVG In HTML Introduction - SVG: Scalable Vector Graphics
can be used to manipulate the picture in the same way you would script regular HTML. ...
...ttribute("class", "invalid"); } </script> </head> <body id="body" style="position:absolute; z-index:0; border:1px solid black; left:5%; top:5%; width:90%; height:90%;"> <form> <fieldset> <legend>HTML Form</legend> <p><label>Enter something:</label> <input type="text"> <span id="err">Incorrect value!</span></p> <p><input type="button" value="Activate!" onclick="signalError
();"></p> </fieldset> </form> <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice" style="width:100%; height:100%; position:absolute; top:0; left:0; z-index:-1;"> <linearGradient id="gradient"> <stop class="begin" offset="0%"/> <stop class="end" offset="100%"/> </linearGradient> <rect x="0" y="0" width="100" height="100" style="fill:url(#gradient)" /> <circle cx="50...
Features restricted to secure contexts - Web security
tion Restricted to secure contexts in 50 Restricted to secure contexts in 10 Restricted to secure contexts in 55 Device Orientaion / Device Motion Deprecation warning Deprecation warnings since 60. Note that these apply to secure contexts as well. Encrypted Media Extensions Restricted to secure contexts in 58 Planned. getUserMedia
() Restricted to secure contexts in Chrome 47 Temporary access available only (users cannot choose "Remember this decision" in the permission request dialog). Restricted to secure contexts in Firefox 68. Notifications Restricted to secure contexts in Chrome 62 Restricted to secure contexts in Firefox 67. <a ping> attribute Disabled in non...
... ...
Using shadow DOM - Web Components
f a <video> element, with the default browser controls exposed. All you see in the DOM is the <video> element, but it contains a series of buttons and other controls inside its shadow DOM. The shadow DOM spec has made it so that you are allowed to actually manipulate the shadow DOM of your own custom elements. Basic usage You can attach a shadow root to any element using the Element.attachShadow
() method. This takes as its parameter an options object that contains one option -- mode -- with a value of open or closed: let shadow = elementRef.attachShadow({mode: 'open'}); let shadow = elementRef.attachShadow({mode: 'closed'}); open means that you can access the shadow DOM using JavaScript written in the main page context, for example using the Element.shadowRoot property: let myShadowDom ...
...lement -- <popup-info> (see a live example also). This takes an image icon and a text string, and embeds the icon into the page. When the icon is focused, it displays the text in a pop up information box to provide further in-context information. To begin with, in our JavaScript file we define a class called PopUpInfo, which extends HTMLElement: class PopUpInfo extends HTMLElement { constructor
() { // Always call super first in constructor super
(); // write element functionality in here ... } } Inside the class definition we define the element's constructor, which defines all the functionality the element will have when an instance of it is instantiated. Creating the shadow root We first attach a shadow root to the custom element: // Create a shadow root let shadow...
position - XPath
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The position function returns a number equal to the context position from the expression evaluation context. Syntax position
() Returns An integer equal to the context position from the expression evaluation context. Notes Note that a node's position in a context is not zero-based. The first node has a position of 1. The context is determined by the rest of the path. ...
...tion returns a number equal to the context position from the expression evaluation context. Syntax position
() Returns An integer equal to the context position from the expression evaluation context. Notes Note that a node's position in a context is not zero-based. The first node has a position of 1. The context is determined by the rest of the path. <xsl:template match="//a[position
() = 5]"> <!-- this template matches the fifth a element anywhere in the document. --> </xsl:template> <xsl:template match="//div[@class='foo']/bar[position
() = 1]"> <!-- this template matches the first bar element that is a child of a div element with a class attribute equal to "foo" --> </xsl:template> Defined XPath 1.0 4.1 Gecko support Supported. ...
unparsed-entity-url - XPath
The name should be an XML Name. ...
...The name should be an XML Name. Returns The URI of the unparsed entity retrieved from the DTD, if it exists. ...